blob: de0da96ccb3ced96da1c5a23aadedccb3c18e9ea [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Eric Laurentb2fb4102024-06-21 12:25:26 +000069using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000070using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070071
Eric Laurentdc462862016-07-19 12:29:53 -070072//FIXME: workaround for truncated touch sounds
73// to be removed when the problem is handled by system UI
74#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070075
76// Largest difference in dB on earpiece in call between the voice volume and another
77// media / notification / system volume.
78constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
79
jiabin06e4bab2019-07-29 10:13:34 -070080template <typename T>
81bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
82{
83 if (left.size() != right.size()) {
84 return false;
85 }
86 for (size_t index = 0; index < right.size(); index++) {
87 if (left[index] != right[index]) {
88 return false;
89 }
90 }
91 return true;
92}
93
94template <typename T>
95bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
96{
97 return !(left == right);
98}
99
Eric Laurente552edb2014-03-10 17:42:56 -0700100// ----------------------------------------------------------------------------
101// AudioPolicyInterface implementation
102// ----------------------------------------------------------------------------
103
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100104status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
105 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
106 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800107 nextAudioPortGeneration();
108 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800109}
110
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100111status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
112 audio_policy_dev_state_t state,
113 const char* device_address,
114 const char* device_name,
115 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800116 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100117 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
118 status == OK) {
119 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
120 } else {
121 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
122 return status;
123 }
124}
125
François Gaffie11d30102018-11-02 16:09:09 +0100126void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000127 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200128{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000129 audio_port_v7 devicePort;
130 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000131 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000132 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700133 ALOGE("Error %d while setting connected state %d for device %s",
134 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000135 device->getDeviceTypeAddr().toString(false).c_str());
136 }
François Gaffie44481e72016-04-20 07:49:57 +0200137}
138
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100139status_t AudioPolicyManager::setDeviceConnectionStateInt(
140 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
141 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100142 if (port.ext.getTag() != AudioPortExt::device) {
143 return BAD_VALUE;
144 }
145 audio_devices_t device_type;
146 std::string device_address;
147 if (status_t status = aidl2legacy_AudioDevice_audio_device(
148 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
149 status != OK) {
150 return status;
151 };
152 const char* device_name = port.name.c_str();
153 // connect/disconnect only 1 device at a time
154 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
155 return BAD_VALUE;
156
157 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
158 device_type, device_address.c_str(), device_name, encodedFormat,
159 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000160 if (device == nullptr) {
161 return INVALID_OPERATION;
162 }
163 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
164 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
165 }
166 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167}
168
François Gaffie11d30102018-11-02 16:09:09 +0100169status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800170 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100171 const char* device_address,
172 const char* device_name,
173 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800174 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100175 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
176 status == OK) {
177 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
178 } else {
179 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
180 return status;
181 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182}
Paul McLeane743a472015-01-28 11:07:31 -0800183
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700184status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
185 audio_policy_dev_state_t state)
186{
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700188 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700189 SortedVector <audio_io_handle_t> outputs;
190
François Gaffie11d30102018-11-02 16:09:09 +0100191 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192
Eric Laurente552edb2014-03-10 17:42:56 -0700193 // save a copy of the opened output descriptors before any output is opened or closed
194 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
195 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100196
197 bool wasLeUnicastActive = isLeUnicastActive();
198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 switch (state)
200 {
201 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800202 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100204 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700205 return INVALID_OPERATION;
206 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800207 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700208 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700209
Eric Laurente552edb2014-03-10 17:42:56 -0700210 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200211 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700212 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700213 }
214
François Gaffie44481e72016-04-20 07:49:57 +0200215 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
216 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000217 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200218
François Gaffie11d30102018-11-02 16:09:09 +0100219 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
220 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200221
jiabinc0048632023-04-27 22:04:31 +0000222 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700223
224 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 return INVALID_OPERATION;
226 }
François Gaffie2110e042015-03-24 08:41:51 +0100227
jiabin1c4794b2020-05-05 10:08:05 -0700228 // Populate encapsulation information when a output device is connected.
229 device->setEncapsulationInfoFromHal(mpClientInterface);
230
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700231 // outputs should never be empty here
232 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
233 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700237 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700238 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700239 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100240 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700241 return INVALID_OPERATION;
242 }
243
François Gaffie11d30102018-11-02 16:09:09 +0100244 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700245
jiabinc0048632023-04-27 22:04:31 +0000246 // Notify the HAL to prepare to disconnect device
247 broadcastDeviceConnectionState(
248 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700249
Eric Laurente552edb2014-03-10 17:42:56 -0700250 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100251 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700252
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100253 mOutputs.clearSessionRoutesForDevice(device);
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100256
jiabinc0048632023-04-27 22:04:31 +0000257 // Send Disconnect to HALs
258 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
259
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800260 // Reset active device codec
261 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
262
Kriti Dangef6be8f2020-11-05 11:58:19 +0100263 // remove device from mReportedFormatsMap cache
264 mReportedFormatsMap.erase(device);
265
jiabina84c3d32022-12-02 18:59:55 +0000266 // remove preferred mixer configurations
267 mPreferredMixerAttrInfos.erase(device->getId());
268
Eric Laurente552edb2014-03-10 17:42:56 -0700269 } break;
270
271 default:
François Gaffie11d30102018-11-02 16:09:09 +0100272 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700273 return BAD_VALUE;
274 }
275
Eric Laurent736a1022019-03-27 18:28:46 -0700276 // Propagate device availability to Engine
277 setEngineDeviceConnectionState(device, state);
278
Eric Laurentae970022019-01-29 14:25:04 -0800279 // No need to evaluate playback routing when connecting a remote submix
280 // output device used by a dynamic policy of type recorder as no
281 // playback use case is affected.
282 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700283 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800284 for (audio_io_handle_t output : outputs) {
285 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800286 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
287 if (policyMix != nullptr
288 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000289 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800290 doCheckForDeviceAndOutputChanges = false;
291 break;
292 }
293 }
294 }
295
296 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // outputs must be closed after checkOutputForAllStrategies() is executed
298 if (!outputs.isEmpty()) {
299 for (audio_io_handle_t output : outputs) {
300 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100301 // close unused outputs after device disconnection or direct outputs that have
302 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200303 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200304 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
305 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200306 (desc->mDirectOpenCount == 0))
307 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
308 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200309 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 closeOutput(output);
311 }
Eric Laurente552edb2014-03-10 17:42:56 -0700312 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700313 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
314 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700315 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700316 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800317 };
318
319 if (doCheckForDeviceAndOutputChanges) {
320 checkForDeviceAndOutputChanges(checkCloseOutputs);
321 } else {
322 checkCloseOutputs();
323 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100324 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100325 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700326 const DeviceVector activeMediaDevices =
327 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000328 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700329 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700330 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530331 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
332 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100333 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 // do not force device change on duplicated output because if device is 0, it will
335 // also force a device 0 for the two outputs it is duplicated to which may override
336 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100337 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100338 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700339 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700340 // always force when disconnecting (a non-duplicated device)
341 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000342 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000343 // If the device is using preferred mixer attributes, the output need to reopen
344 // with default configuration when the new selected devices are different from
345 // current routing devices
346 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
347 continue;
348 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530349 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700350 }
jiabinbce0c1d2020-10-05 11:20:18 -0700351 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000352 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700353 desc->supportsDevicesForPlayback(activeMediaDevices)) {
354 // Reopen the output to query the dynamic profiles when there is not active
355 // clients or all active clients will be rerouted. Otherwise, set the flag
356 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
357 // can be reopened to query dynamic profiles when all clients are inactive.
358 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000359 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700360 } else {
361 desc->mPendingReopenToQueryProfiles = true;
362 }
363 }
364 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
365 // Clear the flag that previously set for re-querying profiles.
366 desc->mPendingReopenToQueryProfiles = false;
367 }
368 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000369 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700370
Eric Laurentd60560a2015-04-10 11:31:20 -0700371 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100372 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700373 }
374
Eric Laurent96d1dda2022-03-14 17:14:19 +0100375 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
376
Eric Laurent72aa32f2014-05-30 18:51:48 -0700377 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700378 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } // end if is output device
380
Eric Laurente552edb2014-03-10 17:42:56 -0700381 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700382 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700384 switch (state)
385 {
386 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700390 return INVALID_OPERATION;
391 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700392
393 if (mAvailableInputDevices.add(device) < 0) {
394 return NO_MEMORY;
395 }
396
François Gaffie44481e72016-04-20 07:49:57 +0200397 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
398 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000399 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700400 // Propagate device availability to Engine
401 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200402
Eric Laurent0dd51852019-04-19 18:18:58 -0700403 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700404 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
405
Eric Laurent0dd51852019-04-19 18:18:58 -0700406 mAvailableInputDevices.remove(device);
407
jiabinc0048632023-04-27 22:04:31 +0000408 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100409
410 mHwModules.cleanUpForDevice(device);
411
Eric Laurentd4692962014-05-05 18:13:44 -0700412 return INVALID_OPERATION;
413 }
414
Eric Laurentd4692962014-05-05 18:13:44 -0700415 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700416
417 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700418 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700419 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100420 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700421 return INVALID_OPERATION;
422 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700423
François Gaffie11d30102018-11-02 16:09:09 +0100424 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700425
jiabinc0048632023-04-27 22:04:31 +0000426 // Notify the HAL to prepare to disconnect device
427 broadcastDeviceConnectionState(
428 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700429
François Gaffie11d30102018-11-02 16:09:09 +0100430 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700431
432 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100433
jiabinc0048632023-04-27 22:04:31 +0000434 // Set Disconnect to HALs
435 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
436
Kriti Dangef6be8f2020-11-05 11:58:19 +0100437 // remove device from mReportedFormatsMap cache
438 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700439
440 // Propagate device availability to Engine
441 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700442 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700443
444 default:
François Gaffie11d30102018-11-02 16:09:09 +0100445 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700446 return BAD_VALUE;
447 }
448
Eric Laurent0dd51852019-04-19 18:18:58 -0700449 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700450 // As the input device list can impact the output device selection, update
451 // getDeviceForStrategy() cache
452 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700453
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100454 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200455 // Reconnect Audio Source
456 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
457 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
458 checkAudioSourceForAttributes(attributes);
459 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700460 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100461 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700462 }
463
Eric Laurentb52c1522014-05-20 11:27:36 -0700464 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700465 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700466 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700467
François Gaffie11d30102018-11-02 16:09:09 +0100468 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700469 return BAD_VALUE;
470}
471
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100472status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
473 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800474 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700475 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
476 devDescr->setName(device_name);
477 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100478}
479
Eric Laurent736a1022019-03-27 18:28:46 -0700480void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
481 audio_policy_dev_state_t state) {
482
483 // the Engine does not have to know about remote submix devices used by dynamic audio policies
484 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
485 return;
486 }
487 mEngine->setDeviceConnectionState(device, state);
488}
489
490
Eric Laurente0720872014-03-11 09:30:41 -0700491audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100492 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700493{
Eric Laurent634b7142016-04-20 13:48:02 -0700494 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800495 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
496 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700497 (strlen(device_address) != 0)/*matchAddress*/);
498
499 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100500 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700501 device, device_address);
502 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
503 }
François Gaffie53615e22015-03-19 09:24:12 +0100504
Eric Laurent3a4311c2014-03-17 12:00:47 -0700505 DeviceVector *deviceVector;
506
Eric Laurente552edb2014-03-10 17:42:56 -0700507 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700509 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700510 deviceVector = &mAvailableInputDevices;
511 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100512 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700513 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700514 }
Eric Laurent634b7142016-04-20 13:48:02 -0700515
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 return (deviceVector->getDevice(
517 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700518 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800519}
520
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
522 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800523 const char *device_name,
524 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
527 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800529 // connect/disconnect only 1 device at a time
530 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
531
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700533 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800535 // Nothing to do: device is not connected
536 return NO_ERROR;
537 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800539
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700540 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 // configure codecs.
542 // Handle two specific cases by sending a set parameter to
543 // configure A2DP codecs. No need to toggle device state.
544 // Case 1: A2DP active device switches from primary to primary
545 // module
546 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700548 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800549 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
550 if (availablePrimaryOutputDevices().contains(devDesc) &&
551 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100552 bool isA2dp = audio_is_a2dp_out_device(device);
553 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
554 : String8(AudioParameter::keyReconfigLeSupported);
555 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800556 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100557 int isReconfigSupported;
558 repliedParameters.getInt(supportKey, isReconfigSupported);
559 if (isReconfigSupported) {
560 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
561 : String8(AudioParameter::keyReconfigLe);
562 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800563 param.add(key, String8("true"));
564 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
565 devDesc->setEncodedFormat(encodedFormat);
566 return NO_ERROR;
567 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700568 }
569 }
cnx421bd2dcc42020-07-11 14:58:44 +0800570 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000571 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800572 for (size_t i = 0; i < mOutputs.size(); i++) {
573 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000574 // mute media strategies to avoid sending the music tail into
575 // the earpiece or headset.
576 if (desc->isStrategyActive(musicStrategy)) {
577 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
578 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
579 tempRecommendedMuteDuration : desc->latency() * 4;
580 if (muteWaitMs < tempMuteDurationMs) {
581 muteWaitMs = tempMuteDurationMs;
582 }
583 }
cnx421bd2dcc42020-07-11 14:58:44 +0800584 setStrategyMute(musicStrategy, true, desc);
585 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
586 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
587 nullptr, true /*fromCache*/).types());
588 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000589 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
590 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
591 // happens after the actual device switch.
592 if (muteWaitMs > 0) {
593 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
594 usleep(muteWaitMs * 1000);
595 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800596 // Toggle the device state: UNAVAILABLE -> AVAILABLE
597 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100598 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800599 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800600 device_address, device_name,
601 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800602 if (status != NO_ERROR) {
603 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
604 status);
605 return status;
606 }
607
608 status = setDeviceConnectionState(device,
609 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800610 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800611 if (status != NO_ERROR) {
612 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
613 status);
614 return status;
615 }
616
617 return NO_ERROR;
618}
619
Pattydd807582021-11-04 21:01:03 +0800620status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
621 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800622{
Pattydd807582021-11-04 21:01:03 +0800623 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800624 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800625 std::unordered_set<audio_format_t> formatSet;
626 sp<HwModule> primaryModule =
627 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700628 if (primaryModule == nullptr) {
629 ALOGE("%s() unable to get primary module", __func__);
630 return NO_INIT;
631 }
Pattydd807582021-11-04 21:01:03 +0800632
633 DeviceTypeSet audioDeviceSet;
634
635 switch(device) {
636 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
637 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
638 break;
639 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800640 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
641 break;
642 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
643 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800644 break;
645 default:
646 ALOGE("%s() device type 0x%08x not supported", __func__, device);
647 return BAD_VALUE;
648 }
649
jiabin9a3361e2019-10-01 09:38:30 -0700650 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800651 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800652 for (const auto& device : declaredDevices) {
653 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800654 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800655 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800656 return status;
657}
658
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100659DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
660{
661 DeviceVector rxSinkdevices{};
662 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
663 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
664 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
665 auto rxSinkDevice = rxSinkdevices.itemAt(0);
666 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
667 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
668 // retrieve Rx Source device descriptor
669 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
670 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
671
672 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
673 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
674 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
675 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
676 return DeviceVector(rxSinkDevice);
677 }
678 }
679 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
680 // the device returned is not necessarily reachable via this output
681 // (filter later by setOutputDevices())
682 return getNewOutputDevices(mPrimaryOutput, fromCache);
683}
684
685status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
686{
François Gaffiedb1755b2023-09-01 11:50:35 +0200687 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100688 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
689 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
690 }
691 return INVALID_OPERATION;
692}
693
694status_t AudioPolicyManager::updateCallRoutingInternal(
695 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696{
697 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100698 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700699 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200700 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700701 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100702 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700703 }
François Gaffie11d30102018-11-02 16:09:09 +0100704
Francois Gaffie716e1432019-01-14 16:58:59 +0100705 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100706 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200707
Eric Laurentb2fb4102024-06-21 12:25:26 +0000708 if (!fix_call_audio_patch()) {
709 disconnectTelephonyAudioSource(mCallRxSourceClient);
710 disconnectTelephonyAudioSource(mCallTxSourceClient);
711 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200712
713 if (rxDevices.isEmpty()) {
714 ALOGW("%s() no selected output device", __func__);
715 return INVALID_OPERATION;
716 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000717 if (txSourceDevice == nullptr) {
718 ALOGE("%s() selected input device not available", __func__);
719 return INVALID_OPERATION;
720 }
François Gaffiec005e562018-11-06 15:04:49 +0100721
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100722 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100723 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700724
François Gaffie9eb18552018-11-05 10:33:26 +0100725 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700726 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100727 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700728 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100729 // retrieve Rx Source and Tx Sink device descriptors
730 sp<DeviceDescriptor> rxSourceDevice =
731 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
732 String8(),
733 AUDIO_FORMAT_DEFAULT);
734 sp<DeviceDescriptor> txSinkDevice =
735 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
736 String8(),
737 AUDIO_FORMAT_DEFAULT);
738
739 // RX and TX Telephony device are declared by Primary Audio HAL
740 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
741 (telephonyRxModule->getHalVersionMajor() >= 3)) {
742 if (rxSourceDevice == 0 || txSinkDevice == 0) {
743 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100744 ALOGE("%s() no telephony Tx and/or RX device", __func__);
745 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100746 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100747 // createAudioPatchInternal now supports both HW / SW bridging
748 createRxPatch = true;
749 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100750 } else {
751 // If the RX device is on the primary HW module, then use legacy routing method for
752 // voice calls via setOutputDevice() on primary output.
753 // Otherwise, create two audio patches for TX and RX path.
754 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
755 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700756 // If the TX device is also on the primary HW module, setOutputDevice() will take care
757 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100758 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
759 (txSinkDevice != 0);
760 }
761 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
762 // Otherwise, create two audio patches for TX and RX path.
763 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000764 if (fix_call_audio_patch()) {
765 disconnectTelephonyAudioSource(mCallRxSourceClient);
766 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200767 if (!hasPrimaryOutput()) {
768 ALOGW("%s() no primary output available", __func__);
769 return INVALID_OPERATION;
770 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530771 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700772 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000773 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800774 // If the TX device is on the primary HW module but RX device is
775 // on other HW module, SinkMetaData of telephony input should handle it
776 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700777 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700778 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100779 // terminate active capture if on the same HW module as the call TX source device
780 // FIXME: would be better to refine to only inputs whose profile connects to the
781 // call TX device but this information is not in the audio patch and logic here must be
782 // symmetric to the one in startInput()
783 for (const auto& activeDesc : mInputs.getActiveInputs()) {
784 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
785 closeActiveClients(activeDesc);
786 }
787 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200788 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000789 } else if (fix_call_audio_patch()) {
790 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800791 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100792 if (waitMs != nullptr) {
793 *waitMs = muteWaitMs;
794 }
795 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800796}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700797
Mikhail Naganov100f0122018-11-29 11:22:16 -0800798bool AudioPolicyManager::isDeviceOfModule(
799 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
800 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
801 if (module != 0) {
802 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
803 .indexOf(devDesc) != NAME_NOT_FOUND
804 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
805 .indexOf(devDesc) != NAME_NOT_FOUND;
806 }
807 return false;
808}
809
David Lif85c5e32024-07-01 13:14:10 +0000810void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200811{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000812 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
813
814 if (fix_call_audio_patch()) {
815 if (mCallRxSourceClient != nullptr) {
816 DeviceVector rxDevices =
817 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
818 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
819 "connectTelephonyRxAudioSource(): no device found for call RX source");
820 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
821 if (mCallRxSourceClient->isConnected()
822 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
823 return;
824 }
825 disconnectTelephonyAudioSource(mCallRxSourceClient);
826 }
827 } else {
828 disconnectTelephonyAudioSource(mCallRxSourceClient);
829 }
830
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200831 const struct audio_port_config source = {
832 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
833 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
834 };
Eric Laurent541a2002024-01-15 18:11:42 +0100835 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000836
Eric Laurentccbd7872024-06-20 12:34:15 +0000837 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000838 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100839 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
840 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000841 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
842 mCallRxSourceClient->srcDevice()->toString().c_str(),
843 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200844 ALOGE_IF(mCallRxSourceClient == nullptr,
845 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200846}
847
Francois Gaffie601801d2021-06-22 13:27:39 +0200848void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200849{
Francois Gaffie601801d2021-06-22 13:27:39 +0200850 if (clientDesc == nullptr) {
851 return;
852 }
853 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
854 "%s error stopping audio source", __func__);
855 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200856}
857
858void AudioPolicyManager::connectTelephonyTxAudioSource(
859 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
860 uint32_t delayMs)
861{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200862 if (srcDevice == nullptr || sinkDevice == nullptr) {
863 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
864 return;
865 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000866
867 if (fix_call_audio_patch()) {
868 if (mCallTxSourceClient != nullptr) {
869 if (mCallTxSourceClient->isConnected()
870 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
871 return;
872 }
873 disconnectTelephonyAudioSource(mCallTxSourceClient);
874 }
875 } else {
876 disconnectTelephonyAudioSource(mCallTxSourceClient);
877 }
878
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200879 PatchBuilder patchBuilder;
880 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000881
Francois Gaffie601801d2021-06-22 13:27:39 +0200882 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200883 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
884
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200885 struct audio_port_config source = {};
886 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100887 mCallTxSourceClient = new SourceClientDescriptor(
888 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000889 mCommunnicationStrategy, toVolumeSource(aa), true,
890 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100891 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
892
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200893 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
894 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200895 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
896 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200897 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000898 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
899 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200900 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200901 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200902 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200903}
904
Eric Laurente0720872014-03-11 09:30:41 -0700905void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700906{
907 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100908 // store previous phone state for management of sonification strategy below
909 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100910 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100911
912 if (mEngine->setPhoneState(state) != NO_ERROR) {
913 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700914 return;
915 }
François Gaffie2110e042015-03-24 08:41:51 +0100916 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700917 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700918 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700919 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800920 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700921 }
922
François Gaffie2110e042015-03-24 08:41:51 +0100923 /**
924 * Switching to or from incall state or switching between telephony and VoIP lead to force
925 * routing command.
926 */
Eric Laurent74b71512019-11-06 17:21:57 -0800927 bool force = ((isStateInCall(oldState) != isStateInCall(state))
928 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700929
930 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700931 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700932
Eric Laurente552edb2014-03-10 17:42:56 -0700933 int delayMs = 0;
934 if (isStateInCall(state)) {
935 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100936 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
937 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700938 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700939 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700940 // mute media and sonification strategies and delay device switch by the largest
941 // latency of any output where either strategy is active.
942 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100943 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
944 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
945 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700946 (delayMs < (int)desc->latency()*2)) {
947 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700948 }
François Gaffiec005e562018-11-06 15:04:49 +0100949 setStrategyMute(musicStrategy, true, desc);
950 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
951 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
952 nullptr, true /*fromCache*/).types());
953 setStrategyMute(sonificationStrategy, true, desc);
954 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
955 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
956 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700957 }
958 }
959
François Gaffiedb1755b2023-09-01 11:50:35 +0200960 if (state == AUDIO_MODE_IN_CALL) {
961 (void)updateCallRouting(false /*fromCache*/, delayMs);
962 } else {
963 if (oldState == AUDIO_MODE_IN_CALL) {
964 disconnectTelephonyAudioSource(mCallRxSourceClient);
965 disconnectTelephonyAudioSource(mCallTxSourceClient);
966 }
967 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100968 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
969 // force routing command to audio hardware when ending call
970 // even if no device change is needed
971 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
972 rxDevices = mPrimaryOutput->devices();
973 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530974 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700975 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700976 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700977
jiabin3ff8d7d2022-12-13 06:27:44 +0000978 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700979 // reevaluate routing on all outputs in case tracks have been started during the call
980 for (size_t i = 0; i < mOutputs.size(); i++) {
981 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100982 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000983 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
984 && desc->mPreferredAttrInfo != nullptr) {
985 // If the output is using preferred mixer attributes and the audio mode is not normal,
986 // the output need to reopen with default configuration.
987 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
988 continue;
989 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200990 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
991 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530992 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200993 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700994 }
995 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000996 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700997
Eric Laurent96d1dda2022-03-14 17:14:19 +0100998 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
999
Eric Laurente552edb2014-03-10 17:42:56 -07001000 if (isStateInCall(state)) {
1001 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001002 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001003 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001004 }
1005
1006 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001007 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1008 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001009}
1010
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001011audio_mode_t AudioPolicyManager::getPhoneState() {
1012 return mEngine->getPhoneState();
1013}
1014
Eric Laurente0720872014-03-11 09:30:41 -07001015void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001016 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001017{
François Gaffie2110e042015-03-24 08:41:51 +01001018 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001019 if (config == mEngine->getForceUse(usage)) {
1020 return;
1021 }
Eric Laurente552edb2014-03-10 17:42:56 -07001022
François Gaffie2110e042015-03-24 08:41:51 +01001023 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1024 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1025 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
François Gaffie2110e042015-03-24 08:41:51 +01001027 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1028 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1029 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001030
1031 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001032 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001033
Eric Laurent22fcda22019-05-17 16:28:47 -07001034 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1035 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001036 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001037 }
1038
Eric Laurentdc462862016-07-19 12:29:53 -07001039 //FIXME: workaround for truncated touch sounds
1040 // to be removed when the problem is handled by system UI
1041 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001042 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1043 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1044 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001045
1046 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001047 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001048}
1049
Eric Laurente0720872014-03-11 09:30:41 -07001050void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001051{
1052 ALOGV("setSystemProperty() property %s, value %s", property, value);
1053}
1054
Dorin Drimusecc9f422022-03-09 17:57:40 +01001055// Find an MSD output profile compatible with the parameters passed.
1056// When "directOnly" is set, restrict search to profiles for direct outputs.
1057sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1058 const DeviceVector& devices,
1059 uint32_t samplingRate,
1060 audio_format_t format,
1061 audio_channel_mask_t channelMask,
1062 audio_output_flags_t flags,
1063 bool directOnly)
1064{
1065 flags = getRelevantFlags(flags, directOnly);
1066
1067 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1068 if (msdModule != nullptr) {
1069 // for the msd module check if there are patches to the output devices
1070 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1071 HwModuleCollection modules;
1072 modules.add(msdModule);
1073 return searchCompatibleProfileHwModules(
1074 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1075 flags, directOnly);
1076 }
1077 }
1078 return nullptr;
1079}
1080
Michael Chana94fbb22018-04-24 14:31:19 +10001081// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1082// search to profiles for direct outputs.
1083sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001084 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001085 uint32_t samplingRate,
1086 audio_format_t format,
1087 audio_channel_mask_t channelMask,
1088 audio_output_flags_t flags,
1089 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001090{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001091 flags = getRelevantFlags(flags, directOnly);
1092
1093 return searchCompatibleProfileHwModules(
1094 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1095}
1096
1097audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1098 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001099 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001100 // only retain flags that will drive the direct output profile selection
1101 // if explicitly requested
1102 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001103 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001104 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1105 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001106 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001107 return flags;
1108}
Eric Laurent861a6282015-05-18 15:40:16 -07001109
Dorin Drimusecc9f422022-03-09 17:57:40 +01001110sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1111 const HwModuleCollection& hwModules,
1112 const DeviceVector& devices,
1113 uint32_t samplingRate,
1114 audio_format_t format,
1115 audio_channel_mask_t channelMask,
1116 audio_output_flags_t flags,
1117 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001118 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001119 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001120 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001121 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001122 samplingRate, NULL /*updatedSamplingRate*/,
1123 format, NULL /*updatedFormat*/,
1124 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001125 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 continue;
1127 }
1128 // reject profiles not corresponding to a device currently available
1129 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1130 continue;
1131 }
1132 // reject profiles if connected device does not support codec
1133 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1134 continue;
1135 }
1136 if (!directOnly) {
1137 return curProfile;
1138 }
1139
1140 // when searching for direct outputs, if several profiles are compatible, give priority
1141 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001142 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001143 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001144 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001145 }
1146 profile = curProfile;
1147 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1148 break;
1149 }
Eric Laurente552edb2014-03-10 17:42:56 -07001150 }
1151 }
Eric Laurent861a6282015-05-18 15:40:16 -07001152 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001153}
1154
Eric Laurentfa0f6742021-08-17 18:39:44 +02001155sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001156 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001157{
1158 for (const auto& hwModule : mHwModules) {
1159 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001160 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001161 continue;
1162 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001163 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001164 // reject profiles not corresponding to a device currently available
1165 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1166 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1167 continue;
1168 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001169 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1170 != devices.size()) {
1171 continue;
1172 }
1173 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001174 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1175 return curProfile;
1176 }
1177 }
1178 return nullptr;
1179}
1180
Eric Laurentf4e63452017-11-06 19:31:46 +00001181audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001182{
François Gaffiec005e562018-11-06 15:04:49 +01001183 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001184
1185 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1186 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1187 // format, flags, etc. This may result in some discrepancy for functions that utilize
1188 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1189 // and AudioSystem::getOutputSamplingRate().
1190
François Gaffie11d30102018-11-02 16:09:09 +01001191 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001192 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1193 if (stream == AUDIO_STREAM_MUSIC &&
1194 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1195 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1196 }
1197 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001198
François Gaffie11d30102018-11-02 16:09:09 +01001199 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1200 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001201 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001202}
1203
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001204status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1205 const audio_attributes_t *srcAttr,
1206 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001207{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001208 if (srcAttr != NULL) {
1209 if (!isValidAttributes(srcAttr)) {
1210 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1211 __func__,
1212 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1213 srcAttr->tags);
1214 return BAD_VALUE;
1215 }
1216 *dstAttr = *srcAttr;
1217 } else {
1218 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1219 ALOGE("%s: invalid stream type", __func__);
1220 return BAD_VALUE;
1221 }
François Gaffiec005e562018-11-06 15:04:49 +01001222 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001223 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001224
1225 // Only honor audibility enforced when required. The client will be
1226 // forced to reconnect if the forced usage changes.
1227 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001228 dstAttr->flags = static_cast<audio_flags_mask_t>(
1229 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001230 }
1231
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001232 return NO_ERROR;
1233}
1234
Kevin Rocard153f92d2018-12-18 18:33:28 -08001235status_t AudioPolicyManager::getOutputForAttrInt(
1236 audio_attributes_t *resultAttr,
1237 audio_io_handle_t *output,
1238 audio_session_t session,
1239 const audio_attributes_t *attr,
1240 audio_stream_type_t *stream,
1241 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001242 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001243 audio_output_flags_t *flags,
1244 audio_port_handle_t *selectedDeviceId,
1245 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001246 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001247 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001248 bool *isSpatialized,
1249 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001250{
François Gaffiec005e562018-11-06 15:04:49 +01001251 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001252 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001253 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001254 const sp<DeviceDescriptor> requestedDevice =
1255 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1256
Eric Laurent8a1095a2019-11-08 14:44:16 -08001257 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001258 *isSpatialized = false;
1259
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001260 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1261 if (status != NO_ERROR) {
1262 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001263 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001264 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001265 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001266 }
François Gaffiec005e562018-11-06 15:04:49 +01001267 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001268
François Gaffiec005e562018-11-06 15:04:49 +01001269 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1270 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001271
Oscar Azucena873d10f2023-01-12 18:34:42 -08001272 bool usePrimaryOutputFromPolicyMixes = false;
1273
Kevin Rocard153f92d2018-12-18 18:33:28 -08001274 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1275 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1276 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001277 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001278 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1279 .channel_mask = config->channel_mask,
1280 .format = config->format,
1281 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001282 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001283 mAvailableOutputDevices, requestedDevice, primaryMix,
1284 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001285 if (status != OK) {
1286 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001287 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001288
Kevin Rocard153f92d2018-12-18 18:33:28 -08001289 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001290 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1291 && !audio_is_linear_pcm(config->format)) {
1292 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001293 return BAD_VALUE;
1294 }
1295 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001296 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001297 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1298 primaryMix->mDeviceAddress,
1299 AUDIO_FORMAT_DEFAULT);
1300 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001301 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001302 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1303 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001304 // if a direct output can be opened to deliver the track's multi-channel content to the
1305 // output rather than being downmixed by the primary output, then use this direct
1306 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1307 // mix.
1308 bool tryDirectForChannelMask = policyDesc != nullptr
1309 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1310 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001311 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001312 audio_io_handle_t newOutput;
1313 status = openDirectOutput(
1314 *stream, session, config,
1315 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001316 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001317 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001318 policyDesc = mOutputs.valueFor(newOutput);
1319 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001320 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001321 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001322 policyDesc = nullptr;
1323 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001324 }
1325 if (policyDesc != nullptr) {
1326 policyDesc->mPolicyMix = primaryMix;
1327 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001328 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1329 : AUDIO_PORT_HANDLE_NONE;
1330 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1331 // Remove direct flag as it is not on a direct output.
1332 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1333 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001334
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001335 ALOGV("getOutputForAttr() returns output %d", *output);
1336 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1337 *outputType = API_OUT_MIX_PLAYBACK;
1338 } else {
1339 *outputType = API_OUTPUT_LEGACY;
1340 }
1341 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001342 } else {
1343 if (policyMixDevice != nullptr) {
1344 ALOGE("%s, try to use primary mix but no output found", __func__);
1345 return INVALID_OPERATION;
1346 }
1347 // Fallback to default engine selection as the selected primary mix device is not
1348 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001349 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001350 }
François Gaffiec005e562018-11-06 15:04:49 +01001351 // Virtual sources must always be dynamicaly or explicitly routed
1352 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1353 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1354 return BAD_VALUE;
1355 }
1356 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1357 // in order to let the choice of the order to future vendor engine
1358 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001359
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001360 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001361 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001362 }
1363
Nadav Barb2f18162018-07-18 13:01:53 +03001364 // Set incall music only if device was explicitly set, and fallback to the device which is
1365 // chosen by the engine if not.
1366 // FIXME: provide a more generic approach which is not device specific and move this back
1367 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001368 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001369 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001370 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001371 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001372 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001373 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001374 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001375 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001376 }
1377 }
1378
François Gaffiec005e562018-11-06 15:04:49 +01001379 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1380 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1381 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001382
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001383 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001384 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001385 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001386 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001387 ALOGV("%s() Using MSD devices %s instead of devices %s",
1388 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001389 } else {
1390 *output = AUDIO_IO_HANDLE_NONE;
1391 }
1392 }
1393 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001394 sp<PreferredMixerAttributesInfo> info = nullptr;
1395 if (outputDevices.size() == 1) {
1396 info = getPreferredMixerAttributesInfo(
1397 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001398 mEngine->getProductStrategyForAttributes(*resultAttr),
1399 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001400 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1401 // and it is currently active.
1402 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001403 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001404 info = nullptr;
1405 }
jiabin220eea12024-05-17 17:55:20 +00001406 if (com::android::media::audioserver::
1407 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1408 if (info != nullptr && info->getUid() == uid &&
1409 info->configMatches(*config) &&
1410 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1411 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1412 [this, &outputDevices](audio_usage_t usage) {
1413 return mOutputs.isUsageActiveOnDevice(
1414 usage, outputDevices[0]); }))) {
1415 // Bit-perfect request is not allowed when the phone mode is not normal or
1416 // there is any higher priority user case active.
1417 return INVALID_OPERATION;
1418 }
1419 }
jiabina84c3d32022-12-02 18:59:55 +00001420 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001421 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001422 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001423 // The client will be active if the client is currently preferred mixer owner and the
1424 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001425 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001426 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001427 && info->getUid() == uid
1428 && *output != AUDIO_IO_HANDLE_NONE
1429 // When bit-perfect output is selected for the preferred mixer attributes owner,
1430 // only need to consider the config matches.
1431 && mOutputs.valueFor(*output)->isConfigurationMatched(
1432 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001433
1434 if (*isBitPerfect) {
1435 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1436 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001437 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001438 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001439 AudioProfileVector profiles;
1440 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1441 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001442 const auto channels = profiles[0]->getChannels();
1443 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1444 config->channel_mask = *channels.begin();
1445 }
1446 const auto sampleRates = profiles[0]->getSampleRates();
1447 if (!sampleRates.empty() &&
1448 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1449 config->sample_rate = *sampleRates.begin();
1450 }
jiabinf1c73972022-04-14 16:28:52 -07001451 config->format = profiles[0]->getFormat();
1452 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001453 return INVALID_OPERATION;
1454 }
Paul McLeanaa981192015-03-21 09:55:15 -07001455
François Gaffiec005e562018-11-06 15:04:49 +01001456 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001457 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001458 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001459 *selectedDeviceId = outputDevice->getId();
1460 break;
1461 }
1462 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001463
Eric Laurent8a1095a2019-11-08 14:44:16 -08001464 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1465 *outputType = API_OUTPUT_TELEPHONY_TX;
1466 } else {
1467 *outputType = API_OUTPUT_LEGACY;
1468 }
1469
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001470 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1471
1472 return NO_ERROR;
1473}
1474
1475status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1476 audio_io_handle_t *output,
1477 audio_session_t session,
1478 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001479 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001480 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001481 audio_output_flags_t *flags,
1482 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001483 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001484 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001485 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001486 bool *isSpatialized,
1487 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001488{
1489 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1490 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1491 return INVALID_OPERATION;
1492 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001493 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001494 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001495 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001496 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001497 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001498 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001499 const sp<DeviceDescriptor> requestedDevice =
1500 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1501
1502 // Prevent from storing invalid requested device id in clients
1503 const audio_port_handle_t sanitizedRequestedPortId =
1504 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1505 *selectedDeviceId = sanitizedRequestedPortId;
1506
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001507 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001508 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001509 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1510 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001511 if (status != NO_ERROR) {
1512 return status;
1513 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001514 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001515 if (secondaryOutputs != nullptr) {
1516 for (auto &secondaryMix : secondaryMixes) {
1517 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1518 if (outputDesc != nullptr &&
1519 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1520 secondaryOutputs->push_back(outputDesc->mIoHandle);
1521 weakSecondaryOutputDescs.push_back(outputDesc);
1522 }
1523 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001524 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001525
Eric Laurent8fc147b2018-07-22 19:13:55 -07001526 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001527 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001528 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001529 };
jiabin4ef93452019-09-10 14:29:54 -07001530 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001531
Eric Laurentc209fe42020-06-05 18:11:23 -07001532 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001533 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001534 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001535 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001536 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001537 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001538 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001539 std::move(weakSecondaryOutputDescs),
1540 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001541 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001542
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001543 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1544 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001545
Eric Laurente83b55d2014-11-14 10:06:21 -08001546 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001547}
1548
Eric Laurentc529cf62020-04-17 18:19:10 -07001549status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1550 audio_session_t session,
1551 const audio_config_t *config,
1552 audio_output_flags_t flags,
1553 const DeviceVector &devices,
1554 audio_io_handle_t *output) {
1555
1556 *output = AUDIO_IO_HANDLE_NONE;
1557
1558 // skip direct output selection if the request can obviously be attached to a mixed output
1559 // and not explicitly requested
1560 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1561 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1562 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1563 return NAME_NOT_FOUND;
1564 }
1565
1566 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1567 // This prevents creating an offloaded track and tearing it down immediately after start
1568 // when audioflinger detects there is an active non offloadable effect.
1569 // FIXME: We should check the audio session here but we do not have it in this context.
1570 // This may prevent offloading in rare situations where effects are left active by apps
1571 // in the background.
1572 sp<IOProfile> profile;
1573 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1574 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1575 profile = getProfileForOutput(
1576 devices, config->sample_rate, config->format, config->channel_mask,
1577 flags, true /* directOnly */);
1578 }
1579
1580 if (profile == nullptr) {
1581 return NAME_NOT_FOUND;
1582 }
1583
1584 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1585 for (size_t i = 0; i < mOutputs.size(); i++) {
1586 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1587 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1588 // reuse direct output if currently open by the same client
1589 // and configured with same parameters
1590 if ((config->sample_rate == desc->getSamplingRate()) &&
1591 (config->format == desc->getFormat()) &&
1592 (config->channel_mask == desc->getChannelMask()) &&
1593 (session == desc->mDirectClientSession)) {
1594 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001595 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001596 mOutputs.keyAt(i), session);
1597 *output = mOutputs.keyAt(i);
1598 return NO_ERROR;
1599 }
1600 }
1601 }
1602
1603 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001604 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1605 return NAME_NOT_FOUND;
1606 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1607 // MMAP gracefully handles lack of an exclusive track resource by mixing
1608 // above the audio framework. For AAudio to know that the limit is reached,
1609 // return an error.
1610 return NAME_NOT_FOUND;
1611 } else {
1612 // Close outputs on this profile, if available, to free resources for this request
1613 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1614 const auto desc = mOutputs.valueAt(i);
1615 if (desc->mProfile == profile) {
1616 closeOutput(desc->mIoHandle);
1617 }
1618 }
1619 }
1620 }
1621
1622 // Unable to close streams to find free resources for this request
1623 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001624 return NAME_NOT_FOUND;
1625 }
1626
Atneya Nairb16666a2023-12-11 20:18:33 -08001627 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001628
Michael Chan6fb34492020-12-08 15:44:49 +11001629 // An MSD patch may be using the only output stream that can service this request. Release
1630 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001631 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001632
Eric Laurentf1f22e72021-07-13 14:04:14 +02001633 status_t status =
1634 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001635
1636 // only accept an output with the requested parameters
1637 if (status != NO_ERROR ||
1638 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1639 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1640 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1641 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1642 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1643 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1644 config->channel_mask, outputDesc->getChannelMask());
1645 if (*output != AUDIO_IO_HANDLE_NONE) {
1646 outputDesc->close();
1647 }
1648 // fall back to mixer output if possible when the direct output could not be open
1649 if (audio_is_linear_pcm(config->format) &&
1650 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1651 return NAME_NOT_FOUND;
1652 }
1653 *output = AUDIO_IO_HANDLE_NONE;
1654 return BAD_VALUE;
1655 }
1656 outputDesc->mDirectOpenCount = 1;
1657 outputDesc->mDirectClientSession = session;
1658
1659 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001660 setOutputDevices(__func__, outputDesc,
1661 devices,
1662 true,
1663 0,
1664 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001665 mPreviousOutputs = mOutputs;
1666 ALOGV("%s returns new direct output %d", __func__, *output);
1667 mpClientInterface->onAudioPortListUpdate();
1668 return NO_ERROR;
1669}
1670
François Gaffie11d30102018-11-02 16:09:09 +01001671audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1672 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001673 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001674 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001675 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001676 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001677 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001678 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001679 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001680{
Andy Hungc88b0642018-04-27 15:42:35 -07001681 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001682
jiabine375d412019-02-26 12:54:53 -08001683 // Discard haptic channel mask when forcing muting haptic channels.
1684 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001685 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1686 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001687
Eric Laurente552edb2014-03-10 17:42:56 -07001688 // open a direct output if required by specified parameters
1689 //force direct flag if offload flag is set: offloading implies a direct output stream
1690 // and all common behaviors are driven by checking only the direct flag
1691 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001692 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1693 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001694 }
Nadav Bar766fb022018-01-07 12:18:03 +02001695 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1696 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001697 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001698
1699 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1700
Eric Laurente83b55d2014-11-14 10:06:21 -08001701 // only allow deep buffering for music stream type
1702 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001703 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001704 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001705 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001706 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1707 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001708 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001709 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001710 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001711 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001712 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001713 audio_is_linear_pcm(config->format) &&
1714 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001715 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001716 AUDIO_OUTPUT_FLAG_DIRECT);
1717 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001718 }
Eric Laurente552edb2014-03-10 17:42:56 -07001719
Carter Hsua3abb402021-10-26 11:11:20 +08001720 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1721 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1722 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1723 }
1724
Eric Laurentf9230d52024-01-26 18:49:09 +01001725 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001726 // was specified and offload or direct playback is not explicitly requested, and there is no
1727 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001728 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001729 if (mSpatializerOutput != nullptr &&
1730 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1731 prefMixerConfigInfo == nullptr &&
1732 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1733 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001734 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001735 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001736 }
1737
Eric Laurentc529cf62020-04-17 18:19:10 -07001738 audio_config_t directConfig = *config;
1739 directConfig.channel_mask = channelMask;
1740 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1741 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001742 return output;
1743 }
1744
Eric Laurent14cbfca2016-03-17 09:42:16 -07001745 // A request for HW A/V sync cannot fallback to a mixed output because time
1746 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001747 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001748 return AUDIO_IO_HANDLE_NONE;
1749 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001750 // A request for Tuner cannot fallback to a mixed output
1751 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1752 return AUDIO_IO_HANDLE_NONE;
1753 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001754
Eric Laurente552edb2014-03-10 17:42:56 -07001755 // ignoring channel mask due to downmix capability in mixer
1756
1757 // open a non direct output
1758
1759 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001760 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001761 // get which output is suitable for the specified stream. The actual
1762 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001763 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001764 if (prefMixerConfigInfo != nullptr) {
1765 for (audio_io_handle_t outputHandle : outputs) {
1766 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1767 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1768 output = outputHandle;
1769 break;
1770 }
1771 }
1772 if (output == AUDIO_IO_HANDLE_NONE) {
1773 // No output open with the preferred profile. Open a new one.
1774 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1775 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1776 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1777 config.format = prefMixerConfigInfo->getConfigBase().format;
1778 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1779 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1780 &config, prefMixerConfigInfo->getFlags());
1781 if (preferredOutput == nullptr) {
1782 ALOGE("%s failed to open output with preferred mixer config", __func__);
1783 } else {
1784 output = preferredOutput->mIoHandle;
1785 }
1786 }
1787 } else {
1788 // at this stage we should ignore the DIRECT flag as no direct output could be
1789 // found earlier
1790 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001791 if (com::android::media::audioserver::
1792 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1793 // If the preferred mixer attributes is null, do not select the bit-perfect output
1794 // unless the bit-perfect output is the only output.
1795 // The bit-perfect output can exist while the passed in preferred mixer attributes
1796 // info is null when it is a high priority client. The high priority clients are
1797 // ringtone or alarm, which is not a bit-perfect use case.
1798 size_t i = 0;
1799 while (i < outputs.size() && outputs.size() > 1) {
1800 auto desc = mOutputs.valueFor(outputs[i]);
1801 // The output descriptor must not be null here.
1802 if (desc->isBitPerfect()) {
1803 outputs.removeItemsAt(i);
1804 } else {
1805 i += 1;
1806 }
1807 }
1808 }
jiabina84c3d32022-12-02 18:59:55 +00001809 output = selectOutput(
1810 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1811 }
Eric Laurente552edb2014-03-10 17:42:56 -07001812 }
François Gaffie11d30102018-11-02 16:09:09 +01001813 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001814 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001815 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001816
Eric Laurente552edb2014-03-10 17:42:56 -07001817 return output;
1818}
1819
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001820sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001821 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1822 mAvailableInputDevices);
1823 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1824}
1825
1826DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1827 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1828 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001829}
1830
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001831const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001833 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1834 if (msdModule != 0) {
1835 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1836 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1837 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1838 const struct audio_port_config *source = &patch->mPatch.sources[j];
1839 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1840 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001841 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001842 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001843 }
1844 }
1845 }
1846 return msdPatches;
1847}
1848
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001849bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1850 ssize_t index = mAudioPatches.indexOfKey(handle);
1851 if (index < 0) {
1852 return false;
1853 }
1854 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1855 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1856 if (msdModule == nullptr) {
1857 return false;
1858 }
1859 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1860 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1861 return true;
1862 }
1863 index = getMsdOutputPatches().indexOfKey(handle);
1864 if (index < 0) {
1865 return false;
1866 }
1867 return true;
1868}
1869
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001870status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1871 const InputProfileCollection &inputProfiles,
1872 const OutputProfileCollection &outputProfiles,
1873 const sp<DeviceDescriptor> &sourceDevice,
1874 const sp<DeviceDescriptor> &sinkDevice,
1875 AudioProfileVector& sourceProfiles,
1876 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001878 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001879 return NO_INIT;
1880 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001883 return NO_INIT;
1884 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1887 inProfile->supportsDevice(sourceDevice)) {
1888 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 }
1890 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001891 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001892 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001893 outProfile->supportsDevice(sinkDevice)) {
1894 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001895 }
1896 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001897 return NO_ERROR;
1898}
1899
1900status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1901 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1902 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1903{
Dean Wheatley16809da2022-12-09 14:55:46 +11001904 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1905 static const std::vector<audio_format_t> formatsOrder = {{
1906 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001907 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1908 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001909 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1910 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1911 // preferred).
1912 std::vector<audio_channel_mask_t> masks = {{
1913 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1914 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1915 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1916 // insert index masks (higher counts most preferred) as preferred over position masks
1917 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1918 masks.insert(
1919 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1920 }
1921 return masks;
1922 }();
1923
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001924 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001925 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1926 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001927 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001928 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1929 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001930 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001931 }
1932 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1933 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1934 sinkConfig->format = bestSinkConfig.format;
1935 // For encoded streams force direct flag to prevent downstream mixing.
1936 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1937 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001938 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1939 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001940 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001941 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1942 // raw and IEC61937 framed streams.
1943 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1944 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1945 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001946 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1947 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001948 sourceConfig->channel_mask =
1949 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1950 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1951 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952 sourceConfig->format = bestSinkConfig.format;
1953 // Copy input stream directly without any processing (e.g. resampling).
1954 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1955 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1956 if (hwAvSync) {
1957 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1958 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1959 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1960 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1961 }
1962 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1963 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1964 sinkConfig->config_mask |= config_mask;
1965 sourceConfig->config_mask |= config_mask;
1966 return NO_ERROR;
1967}
1968
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001969PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1970 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001971{
1972 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001973 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1974 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1975 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1976 if (deviceModule == nullptr) {
1977 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1978 return patchBuilder;
1979 }
1980 const InputProfileCollection inputProfiles = msdIsSource ?
1981 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1982 const OutputProfileCollection outputProfiles = msdIsSource ?
1983 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1984
1985 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1986 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1987 device : getMsdAudioOutDevices().itemAt(0);
1988 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1989
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001990 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1991 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001992 AudioProfileVector sourceProfiles;
1993 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001994 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1995 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001996 for (auto hwAvSync : { true, false }) {
1997 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1998 sourceProfiles, sinkProfiles) != NO_ERROR) {
1999 continue;
2000 }
2001 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2002 &sinkConfig) == NO_ERROR) {
2003 // Found a matching config. Re-create PatchBuilder with this config.
2004 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2005 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002006 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002007 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002008 " supporting PCM format conversion.", __func__);
2009 return patchBuilder;
2010}
2011
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002012status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002013 DeviceVector devices;
2014 if (outputDevices != nullptr && outputDevices->size() > 0) {
2015 devices.add(*outputDevices);
2016 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002017 // Use media strategy for unspecified output device. This should only
2018 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2019 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002020 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002021 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002022 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002023 }
Michael Chan6fb34492020-12-08 15:44:49 +11002024 std::vector<PatchBuilder> patchesToCreate;
2025 for (auto i = 0u; i < devices.size(); ++i) {
2026 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002027 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002028 }
2029 // Retain only the MSD patches associated with outputDevices request.
2030 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002031 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002032 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2033 auto retainedPatch = false;
2034 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2035 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2036 patchesToRemove.removeItemsAt(i);
2037 retainedPatch = true;
2038 break;
2039 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002040 }
Michael Chan6fb34492020-12-08 15:44:49 +11002041 if (retainedPatch) {
2042 it = patchesToCreate.erase(it);
2043 continue;
2044 }
2045 ++it;
2046 }
2047 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2048 return NO_ERROR;
2049 }
2050 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2051 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002052 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002053 }
Michael Chan6fb34492020-12-08 15:44:49 +11002054 status_t status = NO_ERROR;
2055 for (const auto &p : patchesToCreate) {
2056 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2057 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2058 char message[256];
2059 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2060 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2061 currStatus == NO_ERROR ? "Success" : "Error",
2062 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2063 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2064 if (currStatus == NO_ERROR) {
2065 ALOGD("%s", message);
2066 } else {
2067 ALOGE("%s", message);
2068 if (status == NO_ERROR) {
2069 status = currStatus;
2070 }
2071 }
2072 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002073 return status;
2074}
2075
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002076void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2077 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002078 for (size_t i = 0; i < msdPatches.size(); i++) {
2079 const auto& patch = msdPatches[i];
2080 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2081 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2082 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2083 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2084 releaseAudioPatch(patch->getHandle(), mUidCached);
2085 break;
2086 }
2087 }
2088 }
2089}
2090
Dorin Drimus94d94412022-02-02 09:05:02 +01002091bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002092 DeviceVector devicesToCheck =
2093 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002094 AudioPatchCollection msdPatches = getMsdOutputPatches();
2095 for (size_t i = 0; i < msdPatches.size(); i++) {
2096 const auto& patch = msdPatches[i];
2097 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2098 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2099 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2100 const auto& foundDevice = devicesToCheck.getDevice(
2101 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2102 if (foundDevice != nullptr) {
2103 devicesToCheck.remove(foundDevice);
2104 if (devicesToCheck.isEmpty()) {
2105 return true;
2106 }
2107 }
2108 }
2109 }
2110 }
2111 return false;
2112}
2113
Eric Laurente0720872014-03-11 09:30:41 -07002114audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002115 audio_output_flags_t flags,
2116 audio_format_t format,
2117 audio_channel_mask_t channelMask,
2118 uint32_t samplingRate,
2119 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002120{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002121 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2122 "%s called with format %#x", __func__, format);
2123
jiabinebb6af42020-06-09 17:31:17 -07002124 // Return the output that haptic-generating attached to when 1) session id is specified,
2125 // 2) haptic-generating effect exists for given session id and 3) the output that
2126 // haptic-generating effect attached to is in given outputs.
2127 if (sessionId != AUDIO_SESSION_NONE) {
2128 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2129 sessionId, FX_IID_HAPTICGENERATOR);
2130 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2131 return hapticGeneratingOutput;
2132 }
2133 }
2134
Eric Laurent16c66dd2019-05-01 17:54:10 -07002135 // Flags disqualifying an output: the match must happen before calling selectOutput()
2136 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2137 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2138
2139 // Flags expressing a functional request: must be honored in priority over
2140 // other criteria
2141 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2142 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002143 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2144 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002145 // Flags expressing a performance request: have lower priority than serving
2146 // requested sampling rate or channel mask
2147 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2148 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2149 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2150
2151 const audio_output_flags_t functionalFlags =
2152 (audio_output_flags_t)(flags & kFunctionalFlags);
2153 const audio_output_flags_t performanceFlags =
2154 (audio_output_flags_t)(flags & kPerformanceFlags);
2155
2156 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2157
Eric Laurente552edb2014-03-10 17:42:56 -07002158 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002159 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002160 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002161 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002162 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002163 // with tiebreak preferring the minimum number of extra functional flags
2164 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002165 // 3: the output supporting the exact channel mask
2166 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002167 // 5: the output with the highest sampling rate if the requested sample rate is
2168 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002169 // 6: the output with the highest number of requested performance flags
2170 // 7: the output with the bit depth the closest to the requested one
2171 // 8: the primary output
2172 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002173
Eric Laurent16c66dd2019-05-01 17:54:10 -07002174 // matching criteria values in priority order for best matching output so far
2175 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002176
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002177 const bool hasOrphanHaptic =
2178 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002179 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2180 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2181 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002182
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002183 for (audio_io_handle_t output : outputs) {
2184 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002185 // matching criteria values in priority order for current output
2186 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002187
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 if (outputDesc->isDuplicated()) {
2189 continue;
2190 }
2191 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2192 continue;
2193 }
Eric Laurent8838a382014-09-08 16:44:28 -07002194
Eric Laurent16c66dd2019-05-01 17:54:10 -07002195 // If haptic channel is specified, use the haptic output if present.
2196 // When using haptic output, same audio format and sample rate are required.
2197 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002198 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002199 // skip if haptic channel specified but output does not support it, or output support haptic
2200 // but there is no haptic channel requested AND no orphan haptic effect exist
2201 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2202 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002203 continue;
2204 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002205 // In the case of audio-coupled-haptic playback, there is no format conversion and
2206 // resampling in the framework, same format/channel/sampleRate for client and the output
2207 // thread is required. In the case of HapticGenerator effect, do not require format
2208 // matching.
2209 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2210 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002211 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002212 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002213 }
2214
2215 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002216 const int matchingFunctionalFlags =
2217 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2218 const int totalFunctionalFlags =
2219 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2220 // Prefer matching functional flags, but subtract unnecessary functional flags.
2221 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002222
2223 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002224 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2225 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002226 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2227 channelCount <= outputChannelCount) {
2228 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002229 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2230 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002232 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002233 currentMatchCriteria[3] = outputChannelCount;
2234 }
2235
2236 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002237 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002238 int diff; // avoid unsigned integer overflow.
2239 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2240
2241 // prefer the closest output sampling rate greater than or equal to target
2242 // if none exists, prefer the closest output sampling rate less than target.
2243 //
2244 // criteria is offset to make non-negative.
2245 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002246 }
2247
2248 // performance flags match
2249 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2250
2251 // format match
2252 if (format != AUDIO_FORMAT_INVALID) {
2253 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002254 PolicyAudioPort::kFormatDistanceMax -
2255 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002256 }
2257
2258 // primary output match
2259 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2260
2261 // compare match criteria by priority then value
2262 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2263 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2264 bestMatchCriteria = currentMatchCriteria;
2265 bestOutput = output;
2266
2267 std::stringstream result;
2268 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2269 std::ostream_iterator<int>(result, " "));
2270 ALOGV("%s new bestOutput %d criteria %s",
2271 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002272 }
2273 }
2274
Eric Laurent16c66dd2019-05-01 17:54:10 -07002275 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002276}
2277
Eric Laurent8fc147b2018-07-22 19:13:55 -07002278status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002279{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002280 ALOGV("%s portId %d", __FUNCTION__, portId);
2281
2282 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2283 if (outputDesc == 0) {
2284 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002285 return BAD_VALUE;
2286 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002287 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002288
Eric Laurent8fc147b2018-07-22 19:13:55 -07002289 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002290 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002291
jiabin220eea12024-05-17 17:55:20 +00002292 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2293 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2294 && outputDesc->isBitPerfect()) {
2295 // Usually, APM selects bit-perfect output for high priority use cases only when
2296 // bit-perfect output is the only output that can be routed to the selected device.
2297 // However, here is no need to play high priority use cases such as ringtone and alarm
2298 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2299 // can attach to new output.
2300 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2301 __func__, client->stream());
2302 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2303 return DEAD_OBJECT;
2304 }
2305
Eric Laurent733ce942017-12-07 12:18:25 -08002306 status_t status = outputDesc->start();
2307 if (status != NO_ERROR) {
2308 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002309 }
2310
Eric Laurent97ac8712018-07-27 18:59:02 -07002311 uint32_t delayMs;
2312 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002313
2314 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002315 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002316 if (status == DEAD_OBJECT) {
2317 sp<SwAudioOutputDescriptor> desc =
2318 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2319 if (desc == nullptr) {
2320 // This is not common, it may indicate something wrong with the HAL.
2321 ALOGE("%s unable to open output with default config", __func__);
2322 return status;
2323 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002324 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002325 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002326 }
jiabina84c3d32022-12-02 18:59:55 +00002327
2328 // If the client is the first one active on preferred mixer parameters, reopen the output
2329 // if the current mixer parameters doesn't match the preferred one.
2330 if (outputDesc->devices().size() == 1) {
2331 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2332 outputDesc->devices()[0]->getId(), client->strategy());
2333 if (info != nullptr && info->getUid() == client->uid()) {
2334 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2335 info->getConfigBase(), info->getFlags())) {
2336 stopSource(outputDesc, client);
2337 outputDesc->stop();
2338 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2339 config.channel_mask = info->getConfigBase().channel_mask;
2340 config.sample_rate = info->getConfigBase().sample_rate;
2341 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002342 sp<SwAudioOutputDescriptor> desc =
2343 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2344 if (desc == nullptr) {
2345 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002346 }
jiabin220eea12024-05-17 17:55:20 +00002347 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002348 // Intentionally return error to let the client side resending request for
2349 // creating and starting.
2350 return DEAD_OBJECT;
2351 }
2352 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002353 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002354 // If it is first bit-perfect client, reroute all clients that will be routed to
2355 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2356 PortHandleVector clientsToInvalidate;
2357 for (size_t i = 0; i < mOutputs.size(); i++) {
2358 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002359 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002360 continue;
2361 }
2362 for (const auto& c : mOutputs[i]->getClientIterable()) {
2363 clientsToInvalidate.push_back(c->portId());
2364 }
2365 }
2366 if (!clientsToInvalidate.empty()) {
2367 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2368 __func__);
2369 mpClientInterface->invalidateTracks(clientsToInvalidate);
2370 }
2371 }
jiabina84c3d32022-12-02 18:59:55 +00002372 }
2373 }
2374
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002375 if (client->hasPreferredDevice()) {
2376 // playback activity with preferred device impacts routing occurred, inform upper layers
2377 mpClientInterface->onRoutingUpdated();
2378 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002379 if (delayMs != 0) {
2380 usleep(delayMs * 1000);
2381 }
2382
jiabin220eea12024-05-17 17:55:20 +00002383 if (status == NO_ERROR &&
2384 outputDesc->mPreferredAttrInfo != nullptr &&
2385 outputDesc->isBitPerfect() &&
2386 com::android::media::audioserver::
2387 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2388 // A new client is started on bit-perfect output, update all clients internal mute.
2389 updateClientsInternalMute(outputDesc);
2390 }
2391
Eric Laurentc75307b2015-03-17 15:29:32 -07002392 return status;
2393}
2394
Eric Laurent96d1dda2022-03-14 17:14:19 +01002395bool AudioPolicyManager::isLeUnicastActive() const {
2396 if (isInCall()) {
2397 return true;
2398 }
2399 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2400}
2401
2402bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2403 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2404 return false;
2405 }
2406 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2407 ALOGV("%s active %d", __func__, active);
2408 return active;
2409}
2410
Eric Laurent97ac8712018-07-27 18:59:02 -07002411status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2412 const sp<TrackClientDescriptor>& client,
2413 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002414{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002415 // cannot start playback of STREAM_TTS if any other output is being used
2416 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002417
2418 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002419 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002420 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002421 auto clientStrategy = client->strategy();
2422 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002423 if (stream == AUDIO_STREAM_TTS) {
2424 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002425 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002426 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002427 return INVALID_OPERATION;
2428 } else {
2429 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2430 }
2431 } else {
2432 // some playback other than beacon starts
2433 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2434 }
2435
Eric Laurent77305a62016-07-25 16:39:22 -07002436 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002437 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002438 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002439
François Gaffie11d30102018-11-02 16:09:09 +01002440 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002441 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002442 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002443 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002444 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002445 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002446 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002447 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002448 } else {
2449 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002450 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002451 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2452 AUDIO_FORMAT_DEFAULT);
2453 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2454 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002455 }
2456
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002457 // requiresMuteCheck is false when we can bypass mute strategy.
2458 // It covers a common case when there is no materially active audio
2459 // and muting would result in unnecessary delay and dropped audio.
2460 const uint32_t outputLatencyMs = outputDesc->latency();
2461 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002462 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002463
Eric Laurente552edb2014-03-10 17:42:56 -07002464 // increment usage count for this stream on the requested output:
2465 // NOTE that the usage count is the same for duplicated output and hardware output which is
2466 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002467 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002468
2469 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002470 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002471 // Preferred device may be exclusive, use only if no other active clients on this output
2472 devices = DeviceVector(
2473 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2474 } else {
2475 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2476 }
François Gaffie11d30102018-11-02 16:09:09 +01002477 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002478 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002479 }
2480 }
Eric Laurente552edb2014-03-10 17:42:56 -07002481
François Gaffiec005e562018-11-06 15:04:49 +01002482 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002483 selectOutputForMusicEffects();
2484 }
2485
François Gaffie1c878552018-11-22 16:53:21 +01002486 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002487 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002488 if (devices.isEmpty()) {
2489 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002490 }
François Gaffiec005e562018-11-06 15:04:49 +01002491 bool shouldWait =
2492 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2493 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2494 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002495 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002496 const bool needToCloseBitPerfectOutput =
2497 (com::android::media::audioserver::
2498 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2499 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2500 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002501 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002502 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002503 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002504 // An output has a shared device if
2505 // - managed by the same hw module
2506 // - supports the currently selected device
2507 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002508 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002509
Eric Laurent77305a62016-07-25 16:39:22 -07002510 // force a device change if any other output is:
2511 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002512 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002513 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002514 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002515 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002516 // change the device currently selected by the other output.
2517 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002518 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002519 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002520 force = true;
2521 }
2522 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002523 // a notification so that audio focus effect can propagate, or that a mute/unmute
2524 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002525 const uint32_t latencyMs = desc->latency();
2526 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2527
2528 if (shouldWait && isActive && (waitMs < latencyMs)) {
2529 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002530 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002531
2532 // Require mute check if another output is on a shared device
2533 // and currently active to have proper drain and avoid pops.
2534 // Note restoring AudioTracks onto this output needs to invoke
2535 // a volume ramp if there is no mute.
2536 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002537
2538 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2539 outputsToReopen.push_back(desc);
2540 }
Eric Laurente552edb2014-03-10 17:42:56 -07002541 }
2542 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002543
jiabin220eea12024-05-17 17:55:20 +00002544 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002545 // If the output is open with preferred mixer attributes, but the routed device is
2546 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2547 // changed.
2548 return DEAD_OBJECT;
2549 }
jiabin220eea12024-05-17 17:55:20 +00002550 for (auto& outputToReopen : outputsToReopen) {
2551 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2552 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002553 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302554 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2555 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002556
Eric Laurente552edb2014-03-10 17:42:56 -07002557 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002558 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002559 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002560 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002561 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002562 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002563 outputDesc->useHwGain() /*force*/)) {
2564 // request AudioService to reinitialize the volume curves asynchronously
2565 ALOGE("checkAndSetVolume failed, requesting volume range init");
2566 mpClientInterface->onVolumeRangeInitRequest();
2567 };
Eric Laurente552edb2014-03-10 17:42:56 -07002568
2569 // update the outputs if starting an output with a stream that can affect notification
2570 // routing
2571 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002572
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002573 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002574 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002575 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002576 }
Eric Laurentdc462862016-07-19 12:29:53 -07002577
2578 if (waitMs > muteWaitMs) {
2579 *delayMs = waitMs - muteWaitMs;
2580 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002581
2582 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2583 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2584 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2585 // change occurs after the MixerThread starts and causes a stream volume
2586 // glitch.
2587 //
2588 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002589 }
Eric Laurentdc462862016-07-19 12:29:53 -07002590
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002591 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002592 mEngine->getForceUse(
2593 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002594 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002595 }
2596
Eric Laurent97ac8712018-07-27 18:59:02 -07002597 // Automatically enable the remote submix input when output is started on a re routing mix
2598 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002599 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2600 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002601 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2602 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2603 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002604 "remote-submix",
2605 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002606 }
2607
Eric Laurent96d1dda2022-03-14 17:14:19 +01002608 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2609
Eric Laurente552edb2014-03-10 17:42:56 -07002610 return NO_ERROR;
2611}
2612
Eric Laurent96d1dda2022-03-14 17:14:19 +01002613void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2614 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2615 bool isUnicastActive = isLeUnicastActive();
2616
2617 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002618 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002619 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2620 for (size_t i = 0; i < mOutputs.size(); i++) {
2621 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2622 if (desc != ignoredOutput && desc->isActive()
2623 && ((isUnicastActive &&
2624 !desc->devices().
2625 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2626 || (wasUnicastActive &&
2627 !desc->devices().getDevicesFromTypes(
2628 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2629 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2630 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002631 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002632 // If the device is using preferred mixer attributes, the output need to reopen
2633 // with default configuration when the new selected devices are different from
2634 // current routing devices.
2635 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2636 continue;
2637 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302638 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002639 // re-apply device specific volume if not done by setOutputDevice()
2640 if (!force) {
2641 applyStreamVolumes(desc, newDevices.types(), delayMs);
2642 }
2643 }
2644 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002645 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002646 }
2647}
2648
Eric Laurent8fc147b2018-07-22 19:13:55 -07002649status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002650{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002651 ALOGV("%s portId %d", __FUNCTION__, portId);
2652
2653 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2654 if (outputDesc == 0) {
2655 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002656 return BAD_VALUE;
2657 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002658 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002659
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002660 if (client->hasPreferredDevice(true)) {
2661 // playback activity with preferred device impacts routing occurred, inform upper layers
2662 mpClientInterface->onRoutingUpdated();
2663 }
2664
Eric Laurent97ac8712018-07-27 18:59:02 -07002665 ALOGV("stopOutput() output %d, stream %d, session %d",
2666 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002667
Eric Laurent97ac8712018-07-27 18:59:02 -07002668 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002669
Eric Laurent733ce942017-12-07 12:18:25 -08002670 if (status == NO_ERROR ) {
2671 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002672 } else {
2673 return status;
2674 }
2675
2676 if (outputDesc->devices().size() == 1) {
2677 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2678 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002679 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002680 if (info != nullptr && info->getUid() == client->uid()) {
2681 info->decreaseActiveClient();
2682 if (info->getActiveClientCount() == 0) {
2683 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002684 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002685 }
2686 }
jiabin220eea12024-05-17 17:55:20 +00002687 if (com::android::media::audioserver::
2688 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2689 !outputReopened && outputDesc->isBitPerfect()) {
2690 // Only need to update the clients' internal mute when the output is bit-perfect and it
2691 // is not reopened.
2692 updateClientsInternalMute(outputDesc);
2693 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002694 }
2695 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002696}
2697
Eric Laurent97ac8712018-07-27 18:59:02 -07002698status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2699 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002700{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002701 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002702 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002703 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002704 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002705
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002706 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2707
François Gaffie1c878552018-11-22 16:53:21 +01002708 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2709 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002710 // Automatically disable the remote submix input when output is stopped on a
2711 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002712 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002713 if (isSingleDeviceType(
2714 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002715 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002716 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002717 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2718 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002719 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002720 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002721 }
2722 }
2723 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002724 if (client->hasPreferredDevice(true) &&
2725 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002726 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002727 forceDeviceUpdate = true;
2728 }
2729
Eric Laurente552edb2014-03-10 17:42:56 -07002730 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002731 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002732
Eric Laurente552edb2014-03-10 17:42:56 -07002733 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002734 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002735 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002736 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002737
2738 // If the routing does not change, if an output is routed on a device using HwGain
2739 // (aka setAudioPortConfig) and there are still active clients following different
2740 // volume group(s), force reapply volume
2741 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2742 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2743
Eric Laurente552edb2014-03-10 17:42:56 -07002744 // delay the device switch by twice the latency because stopOutput() is executed when
2745 // the track stop() command is received and at that time the audio track buffer can
2746 // still contain data that needs to be drained. The latency only covers the audio HAL
2747 // and kernel buffers. Also the latency does not always include additional delay in the
2748 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302749 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002750 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002751
2752 // force restoring the device selection on other active outputs if it differs from the
2753 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002754 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002755 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002756 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002757 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002758 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002759 desc->isActive() &&
2760 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002761 (newDevices != desc->devices())) {
2762 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2763 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002764
jiabin220eea12024-05-17 17:55:20 +00002765 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002766 // If the device is using preferred mixer attributes, the output need to
2767 // reopen with default configuration when the new selected devices are
2768 // different from current routing devices.
2769 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2770 continue;
2771 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302772 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002773
Eric Laurent57de36c2016-09-28 16:59:11 -07002774 // re-apply device specific volume if not done by setOutputDevice()
2775 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002776 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002777 }
Eric Laurente552edb2014-03-10 17:42:56 -07002778 }
2779 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002780 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002781 // update the outputs if stopping one with a stream that can affect notification routing
2782 handleNotificationRoutingForStream(stream);
2783 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002784
2785 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2786 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002787 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002788 }
2789
François Gaffiec005e562018-11-06 15:04:49 +01002790 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002791 selectOutputForMusicEffects();
2792 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002793
2794 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2795
Eric Laurente552edb2014-03-10 17:42:56 -07002796 return NO_ERROR;
2797 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002798 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002799 return INVALID_OPERATION;
2800 }
2801}
2802
jiabinbce0c1d2020-10-05 11:20:18 -07002803bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002804{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002805 ALOGV("%s portId %d", __FUNCTION__, portId);
2806
2807 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2808 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002809 // If an output descriptor is closed due to a device routing change,
2810 // then there are race conditions with releaseOutput from tracks
2811 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2812 // destroyed shortly thereafter.
2813 //
2814 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002815 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002816 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002817 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002818
2819 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002820
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302821 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2822 if (outputDesc->isClientActive(client)) {
2823 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2824 stopOutput(portId);
2825 }
2826
Eric Laurent8fc147b2018-07-22 19:13:55 -07002827 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2828 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002829 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002830 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002831 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002832 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002833 if (--outputDesc->mDirectOpenCount == 0) {
2834 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002835 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002836 }
2837 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302838
Andy Hung39efb7a2018-09-26 15:39:28 -07002839 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002840 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2841 // The output is pending reopened to query dynamic profiles and
2842 // there is no active clients
2843 closeOutput(outputDesc->mIoHandle);
2844 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2845 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2846 if (newOutputDesc == nullptr) {
2847 ALOGE("%s failed to open output", __func__);
2848 }
2849 return true;
2850 }
2851 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002852}
2853
Eric Laurentcaf7f482014-11-25 17:50:47 -08002854status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2855 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002856 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002857 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002858 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002859 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002860 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002861 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002862 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002863 audio_port_handle_t *portId,
2864 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002865{
François Gaffiec005e562018-11-06 15:04:49 +01002866 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002867 "flags %#x attributes=%s requested device ID %d",
2868 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2869 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002870
Eric Laurentad2e7b92017-09-14 20:06:42 -07002871 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002872 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002873 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002874 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002875 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002876 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002877 sp<RecordClientDescriptor> clientDesc;
2878 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002879 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002880 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881
2882 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2883 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2884 return INVALID_OPERATION;
2885 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002886
Francois Gaffie716e1432019-01-14 16:58:59 +01002887 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2888 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002889 }
2890
Paul McLean466dc8e2015-04-17 13:15:36 -06002891 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002892 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002893 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002894
Eric Laurentad2e7b92017-09-14 20:06:42 -07002895 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2896 // possible
2897 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2898 *input != AUDIO_IO_HANDLE_NONE) {
2899 ssize_t index = mInputs.indexOfKey(*input);
2900 if (index < 0) {
2901 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2902 status = BAD_VALUE;
2903 goto error;
2904 }
2905 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002906 RecordClientVector clients = inputDesc->getClientsForSession(session);
2907 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002908 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2909 status = BAD_VALUE;
2910 goto error;
2911 }
2912 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2913 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002914 // corresponds to a new client and is only permitted from the same UID.
2915 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002916 if (clients.size() > 1) {
2917 for (const auto& client : clients) {
2918 // The client map is ordered by key values (portId) and portIds are allocated
2919 // incrementaly. So the first client in this list is the one opened by audio flinger
2920 // when the mmap stream is created and should be ignored as it does not correspond
2921 // to an actual client
2922 if (client == *clients.cbegin()) {
2923 continue;
2924 }
2925 if (uid != client->uid() && !client->isSilenced()) {
2926 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2927 uid, client->portId(), client->uid());
2928 status = INVALID_OPERATION;
2929 goto error;
2930 }
Eric Laurent331679c2018-04-16 17:03:16 -07002931 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002932 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002933 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002934 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002935
Eric Laurentfecbceb2021-02-09 14:46:43 +01002936 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002937 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002938 }
2939
2940 *input = AUDIO_IO_HANDLE_NONE;
2941 *inputType = API_INPUT_INVALID;
2942
Francois Gaffie716e1432019-01-14 16:58:59 +01002943 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002944 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002945 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002946 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002947 ALOGW("%s could not find input mix for attr %s",
2948 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002949 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002950 }
jiabinc1de2df2019-05-07 14:26:40 -07002951 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2952 String8(attr->tags + strlen("addr=")),
2953 AUDIO_FORMAT_DEFAULT);
2954 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002955 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002956 __func__, attributes.source, attributes.tags);
2957 status = BAD_VALUE;
2958 goto error;
2959 }
2960
Kevin Rocard25f9b052019-02-27 15:08:54 -08002961 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2962 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2963 } else {
2964 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2965 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002966 if (virtualDeviceId) {
2967 *virtualDeviceId = policyMix->mVirtualDeviceId;
2968 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002969 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002970 if (explicitRoutingDevice != nullptr) {
2971 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002972 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002973 // Prevent from storing invalid requested device id in clients
2974 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002975 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002976 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2977 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002978 }
François Gaffie11d30102018-11-02 16:09:09 +01002979 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002980 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002981 status = BAD_VALUE;
2982 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002983 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002984 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2985 *inputType = API_INPUT_MIX_CAPTURE;
2986 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002987 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2988 // there is an external policy, but this input is attached to a mix of recorders,
2989 // meaning it receives audio injected into the framework, so the recorder doesn't
2990 // know about it and is therefore considered "legacy"
2991 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002992
2993 if (virtualDeviceId) {
2994 *virtualDeviceId = policyMix->mVirtualDeviceId;
2995 }
François Gaffie11d30102018-11-02 16:09:09 +01002996 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002997 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002998 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002999 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003000 } else {
3001 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003002 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003003
Eric Laurent599c7582015-12-07 18:05:55 -08003004 }
3005
François Gaffiec005e562018-11-06 15:04:49 +01003006 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003007 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003008 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003009 AudioProfileVector profiles;
3010 status_t ret = getProfilesForDevices(
3011 DeviceVector(device), profiles, flags, true /*isInput*/);
3012 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003013 const auto channels = profiles[0]->getChannels();
3014 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3015 config->channel_mask = *channels.begin();
3016 }
3017 const auto sampleRates = profiles[0]->getSampleRates();
3018 if (!sampleRates.empty() &&
3019 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3020 config->sample_rate = *sampleRates.begin();
3021 }
jiabinf1c73972022-04-14 16:28:52 -07003022 config->format = profiles[0]->getFormat();
3023 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003024 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003025 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003026
Marvin Ramine5a122d2023-12-07 13:57:59 +01003027
3028 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3029 *virtualDeviceId = policyMix->mVirtualDeviceId;
3030 }
3031
Eric Laurent8f42ea12018-08-08 09:08:25 -07003032exit:
3033
François Gaffiec005e562018-11-06 15:04:49 +01003034 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3035 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003036
Francois Gaffie716e1432019-01-14 16:58:59 +01003037 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003038 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003039 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040
Mikhail Naganov2996f672019-04-18 12:29:59 -07003041 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003042 requestedDeviceId, attributes.source, flags,
3043 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003044 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003045 // Move (if found) effect for the client session to its input
3046 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003047 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003048
3049 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3050 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003051
Eric Laurent599c7582015-12-07 18:05:55 -08003052 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003053
3054error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003055 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003056}
3057
3058
François Gaffie11d30102018-11-02 16:09:09 +01003059audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003060 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003061 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003062 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003063 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003064 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003065{
3066 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003067 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003068 bool isSoundTrigger = false;
3069
François Gaffiec005e562018-11-06 15:04:49 +01003070 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003071 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3072 if (index >= 0) {
3073 input = mSoundTriggerSessions.valueFor(session);
3074 isSoundTrigger = true;
3075 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3076 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3077 } else {
3078 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003079 }
François Gaffiec005e562018-11-06 15:04:49 +01003080 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003081 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003082 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003083 }
3084
Carter Hsua3abb402021-10-26 11:11:20 +08003085 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3086 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3087 }
3088
Eric Laurentfe231122017-11-17 17:48:06 -08003089 // sampling rate and flags may be updated by getInputProfile
3090 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3091 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003092 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003093 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003094 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003095 // find a compatible input profile (not necessarily identical in parameters)
3096 sp<IOProfile> profile = getInputProfile(
3097 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3098 if (profile == nullptr) {
3099 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003100 }
jiabin2fd710d2022-05-02 23:20:22 +00003101
Glenn Kasten05ddca52016-02-11 08:17:12 -08003102 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003103 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003104 if (samplingRate == 0) {
3105 samplingRate = profileSamplingRate;
3106 }
Eric Laurente552edb2014-03-10 17:42:56 -07003107
Eric Laurent322b4d22015-04-03 15:57:54 -07003108 if (profile->getModuleHandle() == 0) {
3109 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003110 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003111 }
3112
Eric Laurentec376dc2021-04-08 20:41:22 +02003113 // Reuse an already opened input if a client with the same session ID already exists
3114 // on that input
3115 for (size_t i = 0; i < mInputs.size(); i++) {
3116 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3117 if (desc->mProfile != profile) {
3118 continue;
3119 }
3120 RecordClientVector clients = desc->clientsList();
3121 for (const auto &client : clients) {
3122 if (session == client->session()) {
3123 return desc->mIoHandle;
3124 }
3125 }
3126 }
3127
Eric Laurentc71b11b2024-06-03 12:54:53 +00003128 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003129 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003130 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3131 // First pick best candidate for preemption (there may not be any):
3132 // - Preempt and input if:
3133 // - It has only strictly lower priority use cases than the new client
3134 // - It has equal priority use cases than the new client, was not
3135 // opened thanks to preemption or has been active since opened.
3136 // - Order the preemption candidates by inactive first and priority second
3137 sp<AudioInputDescriptor> closeCandidate;
3138 int leastCloseRank = INT_MAX;
3139 static const int sCloseActive = 0x100;
3140
3141 for (size_t i = 0; i < mInputs.size(); i++) {
3142 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3143 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003144 continue;
3145 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003146 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3147 if (topPrioClient == nullptr) {
3148 continue;
3149 }
3150 int topPrio = source_priority(topPrioClient->source());
3151 if (topPrio < source_priority(attributes.source)
3152 || (topPrio == source_priority(attributes.source)
3153 && !desc->isPreemptor())) {
3154 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3155 if (closeRank < leastCloseRank) {
3156 leastCloseRank = closeRank;
3157 closeCandidate = desc;
3158 }
3159 }
3160 }
3161
3162 if (closeCandidate != nullptr) {
3163 closeInput(closeCandidate->mIoHandle);
3164 // Mark the new input as being issued from a preemption
3165 // so that is will not be preempted later
3166 isPreemptor = true;
3167 } else {
3168 // Then pick the best reusable input (There is always one)
3169 // The order of preference is:
3170 // 1) active inputs with same use case as the new client
3171 // 2) inactive inputs with same use case
3172 // 3) active inputs with different use cases
3173 // 4) inactive inputs with different use cases
3174 sp<AudioInputDescriptor> reuseCandidate;
3175 int leastReuseRank = INT_MAX;
3176 static const int sReuseDifferentUseCase = 0x100;
3177
3178 for (size_t i = 0; i < mInputs.size(); i++) {
3179 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3180 if (desc->mProfile != profile) {
3181 continue;
3182 }
3183 int reuseRank = sReuseDifferentUseCase;
3184 for (const auto& client: desc->getClientIterable()) {
3185 if (client->source() == attributes.source) {
3186 reuseRank = 0;
3187 break;
3188 }
3189 }
3190 reuseRank += desc->isActive() ? 0 : 1;
3191 if (reuseRank < leastReuseRank) {
3192 leastReuseRank = reuseRank;
3193 reuseCandidate = desc;
3194 }
3195 }
3196 return reuseCandidate->mIoHandle;
3197 }
3198 } else { // fix_input_sharing_logic()
3199 for (size_t i = 0; i < mInputs.size(); ) {
3200 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3201 if (desc->mProfile != profile) {
3202 i++;
3203 continue;
3204 }
3205 // if sound trigger, reuse input if used by other sound trigger on same session
3206 // else
3207 // reuse input if active client app is not in IDLE state
3208 //
3209 RecordClientVector clients = desc->clientsList();
3210 bool doClose = false;
3211 for (const auto& client : clients) {
3212 if (isSoundTrigger != client->isSoundTrigger()) {
3213 continue;
3214 }
3215 if (client->isSoundTrigger()) {
3216 if (session == client->session()) {
3217 return desc->mIoHandle;
3218 }
3219 continue;
3220 }
3221 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003222 return desc->mIoHandle;
3223 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003224 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003225 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003226 if (doClose) {
3227 closeInput(desc->mIoHandle);
3228 } else {
3229 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003230 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003231 }
3232 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003233 }
3234
Eric Laurentc71b11b2024-06-03 12:54:53 +00003235 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3236 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003237
Eric Laurentfe231122017-11-17 17:48:06 -08003238 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3239 lConfig.sample_rate = profileSamplingRate;
3240 lConfig.channel_mask = profileChannelMask;
3241 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003242
François Gaffie11d30102018-11-02 16:09:09 +01003243 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003244
3245 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003246 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003247 (profileSamplingRate != lConfig.sample_rate) ||
3248 !audio_formats_match(profileFormat, lConfig.format) ||
3249 (profileChannelMask != lConfig.channel_mask)) {
3250 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003251 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003252 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003253 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003254 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003255 }
Eric Laurent599c7582015-12-07 18:05:55 -08003256 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003257 }
3258
Eric Laurentc722f302014-12-10 11:21:49 -08003259 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003260
Eric Laurent599c7582015-12-07 18:05:55 -08003261 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003262 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003263
Eric Laurent599c7582015-12-07 18:05:55 -08003264 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003265}
3266
Eric Laurent4eb58f12018-12-07 16:41:02 -08003267status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003268{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003269 ALOGV("%s portId %d", __FUNCTION__, portId);
3270
3271 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3272 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003273 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003274 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003275 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003276 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003277 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003278 if (client->active()) {
3279 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3280 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003281 }
3282
Eric Laurent8f42ea12018-08-08 09:08:25 -07003283 audio_session_t session = client->session();
3284
Eric Laurent4eb58f12018-12-07 16:41:02 -08003285 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003286
Eric Laurent4eb58f12018-12-07 16:41:02 -08003287 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003288
Eric Laurent4eb58f12018-12-07 16:41:02 -08003289 status_t status = inputDesc->start();
3290 if (status != NO_ERROR) {
3291 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003292 }
Eric Laurente552edb2014-03-10 17:42:56 -07003293
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003294 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003295 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003296 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003297
Eric Laurent8f42ea12018-08-08 09:08:25 -07003298 // indicate active capture to sound trigger service if starting capture from a mic on
3299 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003300 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003301 if (device != nullptr) {
3302 status = setInputDevice(input, device, true /* force */);
3303 } else {
3304 ALOGW("%s no new input device can be found for descriptor %d",
3305 __FUNCTION__, inputDesc->getId());
3306 status = BAD_VALUE;
3307 }
Eric Laurente552edb2014-03-10 17:42:56 -07003308
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003309 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003310 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003311 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003312 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003313 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3314 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003315 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003316 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003317
François Gaffie11d30102018-11-02 16:09:09 +01003318 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3319 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003320 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003321 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003322 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003323
Eric Laurent8f42ea12018-08-08 09:08:25 -07003324 // automatically enable the remote submix output when input is started if not
3325 // used by a policy mix of type MIX_TYPE_RECORDERS
3326 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003327 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003328 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003329 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003330 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003331 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3332 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003333 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334 if (address != "") {
3335 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3336 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003337 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003338 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003339 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003340 } else if (status != NO_ERROR) {
3341 // Restore client activity state.
3342 inputDesc->setClientActive(client, false);
3343 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003344 }
3345
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003346 ALOGV("%s input %d source = %d status = %d exit",
3347 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003348
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003349 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003350}
3351
Eric Laurent8fc147b2018-07-22 19:13:55 -07003352status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003353{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003354 ALOGV("%s portId %d", __FUNCTION__, portId);
3355
3356 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3357 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003358 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003359 return BAD_VALUE;
3360 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003361 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003362 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003363 if (!client->active()) {
3364 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003365 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003366 }
Carter Hsue6139d52021-07-08 10:30:20 +08003367 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003368 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003369
Eric Laurent8f42ea12018-08-08 09:08:25 -07003370 inputDesc->stop();
3371 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003372 auto current_source = inputDesc->source();
3373 setInputDevice(input, getNewInputDevice(inputDesc),
3374 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003375 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003376 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003377 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003378 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003379 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3380 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003381 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003382 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003383
3384 // automatically disable the remote submix output when input is stopped if not
3385 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003386 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003387 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003388 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003389 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003390 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3391 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003392 }
3393 if (address != "") {
3394 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3395 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003396 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003397 }
3398 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003399 resetInputDevice(input);
3400
3401 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3402 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003403 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3404 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003405 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003406 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003407 }
3408 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003409 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003410 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003411}
3412
Eric Laurent8fc147b2018-07-22 19:13:55 -07003413void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003414{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003415 ALOGV("%s portId %d", __FUNCTION__, portId);
3416
3417 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3418 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003419 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003420 return;
3421 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003422 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003423 audio_io_handle_t input = inputDesc->mIoHandle;
3424
Eric Laurent8f42ea12018-08-08 09:08:25 -07003425 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003426
Andy Hung39efb7a2018-09-26 15:39:28 -07003427 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003428
3429 // If no more clients are present in this session, park effects to an orphan chain
3430 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3431 if (clientsOnSession.size() == 0) {
3432 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3433 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003434 if (inputDesc->getClientCount() > 0) {
3435 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003436 return;
3437 }
3438
Eric Laurent05b90f82014-08-27 15:32:29 -07003439 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003440 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003441 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003442}
3443
Eric Laurent8f42ea12018-08-08 09:08:25 -07003444void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003445{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003446 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003447
3448 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003449 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003450 }
3451}
3452
Eric Laurent8f42ea12018-08-08 09:08:25 -07003453void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3454{
3455 stopInput(portId);
3456 releaseInput(portId);
3457}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003458
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003459bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3460 if (input->clientsList().size() == 0
3461 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3462 return true;
3463 }
3464 for (const auto& client : input->clientsList()) {
3465 sp<DeviceDescriptor> device =
3466 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3467 client->session());
3468 if (!input->supportedDevices().contains(device)) {
3469 return true;
3470 }
3471 }
3472 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3473 return false;
3474}
3475
Eric Laurent0dd51852019-04-19 18:18:58 -07003476void AudioPolicyManager::checkCloseInputs() {
3477 // After connecting or disconnecting an input device, close input if:
3478 // - it has no client (was just opened to check profile) OR
3479 // - none of its supported devices are connected anymore OR
3480 // - one of its clients cannot be routed to one of its supported
3481 // devices anymore. Otherwise update device selection
3482 std::vector<audio_io_handle_t> inputsToClose;
3483 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003484 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003485 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003486 }
3487 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003488 for (const audio_io_handle_t handle : inputsToClose) {
3489 ALOGV("%s closing input %d", __func__, handle);
3490 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003491 }
Eric Laurentd4692962014-05-05 18:13:44 -07003492}
3493
Vlad Popa87e0e582024-05-20 18:49:20 -07003494status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3495 const char *address __unused,
3496 bool enabled,
3497 audio_stream_type_t streamToDriveAbs)
3498{
3499 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3500 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3501 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3502 toString(streamToDriveAbs).c_str());
3503 return BAD_VALUE;
3504 }
3505
3506 if (enabled) {
3507 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3508 } else {
3509 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3510 }
3511
3512 return NO_ERROR;
3513}
3514
François Gaffie251c7f02018-11-07 10:41:08 +01003515void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003516{
3517 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003518 if (indexMin < 0 || indexMax < 0) {
3519 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3520 return;
3521 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003522 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003523
3524 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003525 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3526 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003527 continue;
3528 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003529 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003530 }
Eric Laurente552edb2014-03-10 17:42:56 -07003531}
3532
Eric Laurente0720872014-03-11 09:30:41 -07003533status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003534 int index,
3535 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003536{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003537 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003538 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3539 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3540 return NO_ERROR;
3541 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003542 ALOGV("%s: stream %s attributes=%s", __func__,
3543 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003544 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003545}
3546
Eric Laurente0720872014-03-11 09:30:41 -07003547status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003548 int *index,
3549 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003550{
François Gaffiec005e562018-11-06 15:04:49 +01003551 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3552 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003553 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003554 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003555 deviceTypes = mEngine->getOutputDevicesForStream(
3556 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003557 }
jiabin9a3361e2019-10-01 09:38:30 -07003558 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003559}
3560
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003561status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003562 int index,
3563 audio_devices_t device)
3564{
3565 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003566 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3567 if (group == VOLUME_GROUP_NONE) {
3568 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003569 return BAD_VALUE;
3570 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003571 ALOGV("%s: group %d matching with %s index %d",
3572 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003573 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003574 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003575 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003576 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3577 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3578 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3579 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003580 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3581
3582 status = setVolumeCurveIndex(index, device, curves);
3583 if (status != NO_ERROR) {
3584 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3585 return status;
3586 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003587
jiabin9a3361e2019-10-01 09:38:30 -07003588 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003589 auto curCurvAttrs = curves.getAttributes();
3590 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3591 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003592 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003593 } else if (!curves.getStreamTypes().empty()) {
3594 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003595 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003596 } else {
3597 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3598 return BAD_VALUE;
3599 }
jiabin9a3361e2019-10-01 09:38:30 -07003600 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3601 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003602
François Gaffiecfe17322018-11-07 13:41:29 +01003603 // update volume on all outputs and streams matching the following:
3604 // - The requested stream (or a stream matching for volume control) is active on the output
3605 // - The device (or devices) selected by the engine for this stream includes
3606 // the requested device
3607 // - For non default requested device, currently selected device on the output is either the
3608 // requested device or one of the devices selected by the engine for this stream
3609 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3610 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003611 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003612 for (size_t i = 0; i < mOutputs.size(); i++) {
3613 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003614 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003615
jiabin9a3361e2019-10-01 09:38:30 -07003616 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3617 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003618 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003619
3620 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003621 continue;
3622 }
3623 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3624 curDevices.find(device) == curDevices.end()) {
3625 continue;
3626 }
3627 bool applyVolume = false;
3628 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3629 curSrcDevices.insert(device);
3630 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003631 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3632 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003633 } else {
3634 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3635 }
3636 if (!applyVolume) {
3637 continue; // next output
3638 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003639 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3640 // If a higher priority strategy is active, and the output is routed to a device with a
3641 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003642 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003643 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003644 // If the volume source is active with higher priority source, ensure at least Sw Muted
3645 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003646 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3647 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3648 false /*preferredDevice*/);
3649 if (activeClients.empty()) {
3650 continue;
3651 }
3652 bool isPreempted = false;
3653 bool isHigherPriority = productStrategy < strategy;
3654 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003655 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003656 ALOGV("%s: Strategy=%d (\nrequester:\n"
3657 " group %d, volumeGroup=%d attributes=%s)\n"
3658 " higher priority source active:\n"
3659 " volumeGroup=%d attributes=%s) \n"
3660 " on output %zu, bailing out", __func__, productStrategy,
3661 group, group, toString(attributes).c_str(),
3662 client->volumeSource(), toString(client->attributes()).c_str(), i);
3663 applyVolume = false;
3664 isPreempted = true;
3665 break;
3666 }
3667 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003668 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003669 applyVolume = true;
3670 }
3671 }
3672 if (isPreempted || applyVolume) {
3673 break;
3674 }
3675 }
3676 if (!applyVolume) {
3677 continue; // next output
3678 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003679 }
François Gaffieed91f582020-01-31 10:35:37 +01003680 //FIXME: workaround for truncated touch sounds
3681 // delayed volume change for system stream to be removed when the problem is
3682 // handled by system UI
3683 status_t volStatus = checkAndSetVolume(
3684 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003685 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003686 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3687 if (volStatus != NO_ERROR) {
3688 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003689 }
3690 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003691
3692 // update voice volume if the an active call route exists
3693 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3694 && (curSrcDevices.find(
3695 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3696 != curSrcDevices.end())) {
3697 bool isVoiceVolSrc;
3698 bool isBtScoVolSrc;
3699 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3700 isVoiceVolSrc, isBtScoVolSrc, __func__)
3701 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003702 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3703 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3704 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003705 }
3706 }
3707
François Gaffiecfe17322018-11-07 13:41:29 +01003708 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3709 return status;
3710}
3711
François Gaffieaaac0fd2018-11-22 17:56:39 +01003712status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003713 audio_devices_t device,
3714 IVolumeCurves &volumeCurves)
3715{
3716 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3717 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003718 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3719 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003720 (index > volumeCurves.getVolumeIndexMax())) {
3721 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3722 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3723 return BAD_VALUE;
3724 }
3725 if (!audio_is_output_device(device)) {
3726 return BAD_VALUE;
3727 }
3728
3729 // Force max volume if stream cannot be muted
3730 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3731
François Gaffieaaac0fd2018-11-22 17:56:39 +01003732 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003733 volumeCurves.addCurrentVolumeIndex(device, index);
3734 return NO_ERROR;
3735}
3736
3737status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3738 int &index,
3739 audio_devices_t device)
3740{
3741 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3742 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003743 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003744 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003745 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003746 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003747 }
jiabin9a3361e2019-10-01 09:38:30 -07003748 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003749}
3750
3751status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3752 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003753 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003754{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003755 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003756 return BAD_VALUE;
3757 }
jiabin9a3361e2019-10-01 09:38:30 -07003758 index = curves.getVolumeIndex(deviceTypes);
3759 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003760 return NO_ERROR;
3761}
3762
3763status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3764 int &index)
3765{
3766 index = getVolumeCurves(attr).getVolumeIndexMin();
3767 return NO_ERROR;
3768}
3769
3770status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3771 int &index)
3772{
3773 index = getVolumeCurves(attr).getVolumeIndexMax();
3774 return NO_ERROR;
3775}
3776
Eric Laurent36829f92017-04-07 19:04:42 -07003777audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003778{
3779 // select one output among several suitable for global effects.
3780 // The priority is as follows:
3781 // 1: An offloaded output. If the effect ends up not being offloadable,
3782 // AudioFlinger will invalidate the track and the offloaded output
3783 // will be closed causing the effect to be moved to a PCM output.
3784 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003785 // 3: The primary output
3786 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003787
François Gaffiec005e562018-11-06 15:04:49 +01003788 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3789 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003790 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003791
Eric Laurent36829f92017-04-07 19:04:42 -07003792 if (outputs.size() == 0) {
3793 return AUDIO_IO_HANDLE_NONE;
3794 }
Eric Laurente552edb2014-03-10 17:42:56 -07003795
Eric Laurent36829f92017-04-07 19:04:42 -07003796 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3797 bool activeOnly = true;
3798
3799 while (output == AUDIO_IO_HANDLE_NONE) {
3800 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3801 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3802 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3803
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003804 for (audio_io_handle_t output : outputs) {
3805 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003806 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003807 continue;
3808 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003809 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3810 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003811 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003812 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003813 }
3814 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003815 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003816 }
3817 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003818 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003819 }
3820 }
3821 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3822 output = outputOffloaded;
3823 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3824 output = outputDeepBuffer;
3825 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3826 output = outputPrimary;
3827 } else {
3828 output = outputs[0];
3829 }
3830 activeOnly = false;
3831 }
3832
3833 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003834 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3835 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003836 mMusicEffectOutput = output;
3837 }
3838
3839 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003840 return output;
3841}
3842
Eric Laurent36829f92017-04-07 19:04:42 -07003843audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3844{
3845 return selectOutputForMusicEffects();
3846}
3847
Eric Laurente0720872014-03-11 09:30:41 -07003848status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003849 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003850 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003851 int session,
3852 int id)
3853{
Shunkai Yao29d10572024-03-19 04:31:47 +00003854 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003855 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003856 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003857 index = mInputs.indexOfKey(io);
3858 if (index < 0) {
3859 ALOGW("registerEffect() unknown io %d", io);
3860 return INVALID_OPERATION;
3861 }
Eric Laurente552edb2014-03-10 17:42:56 -07003862 }
3863 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003864 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3865 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3866 || strategy == PRODUCT_STRATEGY_NONE));
3867 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003868}
3869
Eric Laurentc241b0d2018-11-28 09:08:49 -08003870status_t AudioPolicyManager::unregisterEffect(int id)
3871{
3872 if (mEffects.getEffect(id) == nullptr) {
3873 return INVALID_OPERATION;
3874 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003875 if (mEffects.isEffectEnabled(id)) {
3876 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3877 setEffectEnabled(id, false);
3878 }
3879 return mEffects.unregisterEffect(id);
3880}
3881
3882status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3883{
3884 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3885 if (effect == nullptr) {
3886 return INVALID_OPERATION;
3887 }
3888
3889 status_t status = mEffects.setEffectEnabled(id, enabled);
3890 if (status == NO_ERROR) {
3891 mInputs.trackEffectEnabled(effect, enabled);
3892 }
3893 return status;
3894}
3895
Eric Laurent6c796322019-04-09 14:13:17 -07003896
3897status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3898{
3899 mEffects.moveEffects(ids, io);
3900 return NO_ERROR;
3901}
3902
Eric Laurentc75307b2015-03-17 15:29:32 -07003903bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3904{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003905 auto vs = toVolumeSource(stream, false);
3906 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003907}
3908
3909bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3910{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003911 auto vs = toVolumeSource(stream, false);
3912 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003913}
3914
Eric Laurente0720872014-03-11 09:30:41 -07003915bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003916{
3917 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003918 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003919 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003920 return true;
3921 }
3922 }
3923 return false;
3924}
3925
Eric Laurent275e8e92014-11-30 15:14:47 -08003926// Register a list of custom mixes with their attributes and format.
3927// When a mix is registered, corresponding input and output profiles are
3928// added to the remote submix hw module. The profile contains only the
3929// parameters (sampling rate, format...) specified by the mix.
3930// The corresponding input remote submix device is also connected.
3931//
3932// When a remote submix device is connected, the address is checked to select the
3933// appropriate profile and the corresponding input or output stream is opened.
3934//
3935// When capture starts, getInputForAttr() will:
3936// - 1 look for a mix matching the address passed in attribtutes tags if any
3937// - 2 if none found, getDeviceForInputSource() will:
3938// - 2.1 look for a mix matching the attributes source
3939// - 2.2 if none found, default to device selection by policy rules
3940// At this time, the corresponding output remote submix device is also connected
3941// and active playback use cases can be transferred to this mix if needed when reconnecting
3942// after AudioTracks are invalidated
3943//
3944// When playback starts, getOutputForAttr() will:
3945// - 1 look for a mix matching the address passed in attribtutes tags if any
3946// - 2 if none found, look for a mix matching the attributes usage
3947// - 3 if none found, default to device and output selection by policy rules.
3948
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003949status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003950{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003951 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3952 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003953 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003954 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003955 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003956 // examine each mix's route type
3957 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003958 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003959 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3960 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3961 ALOGE("Unsupported Policy Mix %zu of %zu: "
3962 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3963 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003964 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003965 break;
3966 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003967 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3968 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003969 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003970 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3971 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003972 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003973 rSubmixModule = mHwModules.getModuleFromName(
3974 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3975 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003976 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003977 i);
3978 res = INVALID_OPERATION;
3979 break;
3980 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003981 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003982
Eric Laurent97ac8712018-07-27 18:59:02 -07003983 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003984 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003985 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003986 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003987 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3988 } else {
3989 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3990 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003991 }
François Gaffie036e1e92015-03-19 10:16:24 +01003992
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003993 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003994 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003995 res = INVALID_OPERATION;
3996 break;
3997 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003998 audio_config_t outputConfig = mix.mFormat;
3999 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004000 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4001 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004002 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4003 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004004 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004005 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4006 audio_is_linear_pcm(outputConfig.format)
4007 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004008 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004009 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4010 audio_is_linear_pcm(inputConfig.format)
4011 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004012
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004013 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004014 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004015 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004016 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004017 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004018 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004019 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004020 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4021 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004022 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004023 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004024 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004025
4026 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4027 mix.mDeviceType, mix.mDeviceAddress,
4028 String8(), AUDIO_FORMAT_DEFAULT);
4029 if (device == nullptr) {
4030 res = INVALID_OPERATION;
4031 break;
4032 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004033
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004034 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004035 // First try to find an already opened output supporting the device
4036 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004037 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004038
Eric Laurentc529cf62020-04-17 18:19:10 -07004039 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004040 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004041 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004042 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004043 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004044 } else {
4045 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004046 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004047 }
4048 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004049 // If no output found, try to find a direct output profile supporting the device
4050 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4051 sp<HwModule> module = mHwModules[i];
4052 for (size_t j = 0;
4053 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4054 j++) {
4055 sp<IOProfile> profile = module->getOutputProfiles()[j];
4056 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4057 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4058 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004059 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004060 res = INVALID_OPERATION;
4061 } else {
4062 foundOutput = true;
4063 }
4064 }
4065 }
4066 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004067 if (res != NO_ERROR) {
4068 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004069 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004070 res = INVALID_OPERATION;
4071 break;
4072 } else if (!foundOutput) {
4073 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004074 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004075 res = INVALID_OPERATION;
4076 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004077 } else {
4078 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004079 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004080 }
Eric Laurentc722f302014-12-10 11:21:49 -08004081 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004082 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004083 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004084 if (audio_flags::audio_mix_ownership()) {
4085 // Only unregister mixes that were actually registered to not accidentally unregister
4086 // mixes that already existed previously.
4087 unregisterPolicyMixes(registeredMixes);
4088 registeredMixes.clear();
4089 } else {
4090 unregisterPolicyMixes(mixes);
4091 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004092 } else if (checkOutputs) {
4093 checkForDeviceAndOutputChanges();
4094 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004095 }
4096 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004097}
4098
4099status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4100{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004101 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004102 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004103 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004104 sp<HwModule> rSubmixModule;
4105 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004106 for (const auto& mix : mixes) {
4107 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004108
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004109 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004110 rSubmixModule = mHwModules.getModuleFromName(
4111 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4112 if (rSubmixModule == 0) {
4113 res = INVALID_OPERATION;
4114 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004115 }
4116 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004117
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004118 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004119
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004120 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004121 res = INVALID_OPERATION;
4122 continue;
4123 }
4124
Marvin Ramin0783e202024-03-05 12:45:50 +01004125 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004126 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004127 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4128 status_t currentRes =
4129 setDeviceConnectionStateInt(device,
4130 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4131 address.c_str(),
4132 "remote-submix",
4133 AUDIO_FORMAT_DEFAULT);
4134 if (!audio_flags::audio_mix_ownership()) {
4135 res = currentRes;
4136 }
4137 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004138 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004139 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004140 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004141 }
4142 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004143 }
jiabin5740f082019-08-19 15:08:30 -07004144 rSubmixModule->removeOutputProfile(address.c_str());
4145 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004146
Kevin Rocard153f92d2018-12-18 18:33:28 -08004147 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004148 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004149 res = INVALID_OPERATION;
4150 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004151 } else {
4152 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004153 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004154 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004155 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004156
4157 if (res == NO_ERROR && checkOutputs) {
4158 checkForDeviceAndOutputChanges();
4159 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004160 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004161 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004162}
4163
Marvin Raminbdefaf02023-11-01 09:10:32 +01004164status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4165 if (!audio_flags::audio_mix_test_api()) {
4166 return INVALID_OPERATION;
4167 }
4168
4169 _aidl_return.clear();
4170 _aidl_return.reserve(mPolicyMixes.size());
4171 for (const auto &policyMix: mPolicyMixes) {
4172 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4173 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4174 policyMix->mCbFlags);
4175 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004176 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004177 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004178 }
4179
Vlad Popaa5d73f32024-03-08 16:05:38 -08004180 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004181 return OK;
4182}
4183
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004184status_t AudioPolicyManager::updatePolicyMix(
4185 const AudioMix& mix,
4186 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4187 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4188 if (res == NO_ERROR) {
4189 checkForDeviceAndOutputChanges();
4190 updateCallAndOutputRouting();
4191 }
4192 return res;
4193}
4194
Mikhail Naganov100f0122018-11-29 11:22:16 -08004195void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4196{
4197 size_t i = 0;
4198 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4199 for (const auto& fmt : mManualSurroundFormats) {
4200 if (i++ != 0) dst->append(", ");
4201 std::string sfmt;
4202 FormatConverter::toString(fmt, sfmt);
4203 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4204 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4205 }
4206}
4207
Eric Laurentc529cf62020-04-17 18:19:10 -07004208// Returns true if all devices types match the predicate and are supported by one HW module
4209bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004210 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004211 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004212 const char *context,
4213 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004214 for (size_t i = 0; i < devices.size(); i++) {
4215 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004216 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004217 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004218 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004219 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004220 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004221 return false;
4222 }
4223 }
4224 return true;
4225}
4226
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004227void AudioPolicyManager::changeOutputDevicesMuteState(
4228 const AudioDeviceTypeAddrVector& devices) {
4229 ALOGVV("%s() num devices %zu", __func__, devices.size());
4230
4231 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4232 getSoftwareOutputsForDevices(devices);
4233
4234 for (size_t i = 0; i < outputs.size(); i++) {
4235 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4236 DeviceVector prevDevices = outputDesc->devices();
4237 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4238 }
4239}
4240
4241std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4242 const AudioDeviceTypeAddrVector& devices) const
4243{
4244 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4245 DeviceVector deviceDescriptors;
4246 for (size_t j = 0; j < devices.size(); j++) {
4247 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4248 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4249 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4250 ALOGE("%s: device type %#x address %s not supported or not an output device",
4251 __func__, devices[j].mType, devices[j].getAddress());
4252 continue;
4253 }
4254 deviceDescriptors.add(desc);
4255 }
4256 for (size_t i = 0; i < mOutputs.size(); i++) {
4257 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4258 continue;
4259 }
4260 outputs.push_back(mOutputs.valueAt(i));
4261 }
4262 return outputs;
4263}
4264
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004265status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004266 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004267 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004268 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4269 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004270 }
4271 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004272 if (res != NO_ERROR) {
4273 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4274 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004275 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004276
4277 checkForDeviceAndOutputChanges();
4278 updateCallAndOutputRouting();
4279
4280 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004281}
4282
4283status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4284 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004285 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4286 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004287 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004288 __FUNCTION__, uid);
4289 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004290 }
4291
Eric Laurentc529cf62020-04-17 18:19:10 -07004292 checkForDeviceAndOutputChanges();
4293 updateCallAndOutputRouting();
4294
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004295 return res;
4296}
4297
Eric Laurent2517af32020-11-25 15:31:27 +01004298
jiabin0a488932020-08-07 17:32:40 -07004299status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4300 device_role_t role,
4301 const AudioDeviceTypeAddrVector &devices) {
4302 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4303 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004304
Eric Laurentc529cf62020-04-17 18:19:10 -07004305 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004306 return BAD_VALUE;
4307 }
jiabin0a488932020-08-07 17:32:40 -07004308 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004309 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004310 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4311 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004312 return status;
4313 }
4314
4315 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004316
4317 bool forceVolumeReeval = false;
4318 // FIXME: workaround for truncated touch sounds
4319 // to be removed when the problem is handled by system UI
4320 uint32_t delayMs = 0;
4321 if (strategy == mCommunnicationStrategy) {
4322 forceVolumeReeval = true;
4323 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4324 updateInputRouting();
4325 }
4326 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004327
4328 return NO_ERROR;
4329}
4330
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004331void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4332 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004333{
4334 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004335 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004336 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004337 // Only apply special touch sound delay once
4338 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004339 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004340 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004341 for (size_t i = 0; i < mOutputs.size(); i++) {
4342 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4343 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004344 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4345 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004346 // As done in setDeviceConnectionState, we could also fix default device issue by
4347 // preventing the force re-routing in case of default dev that distinguishes on address.
4348 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004349 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004350 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004351 // If the device is using preferred mixer attributes, the output need to reopen
4352 // with default configuration when the new selected devices are different from
4353 // current routing devices.
4354 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4355 continue;
4356 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304357
4358 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4359 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004360 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004361 // Only apply special touch sound delay once
4362 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004363 }
4364 if (forceVolumeReeval && !newDevices.isEmpty()) {
4365 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4366 }
4367 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004368 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004369 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004370}
4371
Eric Laurent2517af32020-11-25 15:31:27 +01004372void AudioPolicyManager::updateInputRouting() {
4373 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304374 // Skip for hotword recording as the input device switch
4375 // is handled within sound trigger HAL
4376 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4377 continue;
4378 }
Eric Laurent2517af32020-11-25 15:31:27 +01004379 auto newDevice = getNewInputDevice(activeDesc);
4380 // Force new input selection if the new device can not be reached via current input
4381 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4382 setInputDevice(activeDesc->mIoHandle, newDevice);
4383 } else {
4384 closeInput(activeDesc->mIoHandle);
4385 }
4386 }
4387}
4388
Paul Wang5d7cdb52022-11-22 09:45:06 +00004389status_t
4390AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4391 device_role_t role,
4392 const AudioDeviceTypeAddrVector &devices) {
4393 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4394 dumpAudioDeviceTypeAddrVector(devices).c_str());
4395
Eric Laurent78fedbf2023-03-09 14:40:44 +01004396 if (!areAllDevicesSupported(
4397 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004398 return BAD_VALUE;
4399 }
4400 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4401 if (status != NO_ERROR) {
4402 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4403 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4404 return status;
4405 }
4406
4407 checkForDeviceAndOutputChanges();
4408
4409 bool forceVolumeReeval = false;
4410 // TODO(b/263479999): workaround for truncated touch sounds
4411 // to be removed when the problem is handled by system UI
4412 uint32_t delayMs = 0;
4413 if (strategy == mCommunnicationStrategy) {
4414 forceVolumeReeval = true;
4415 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4416 updateInputRouting();
4417 }
4418 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4419
4420 return NO_ERROR;
4421}
4422
4423status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4424 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004425{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004426 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004427
Paul Wang5d7cdb52022-11-22 09:45:06 +00004428 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004429 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004430 ALOGW_IF(status != NAME_NOT_FOUND,
4431 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004432 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004433 return status;
4434 }
4435
4436 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004437
4438 bool forceVolumeReeval = false;
4439 // FIXME: workaround for truncated touch sounds
4440 // to be removed when the problem is handled by system UI
4441 uint32_t delayMs = 0;
4442 if (strategy == mCommunnicationStrategy) {
4443 forceVolumeReeval = true;
4444 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4445 updateInputRouting();
4446 }
4447 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004448
4449 return NO_ERROR;
4450}
4451
jiabin0a488932020-08-07 17:32:40 -07004452status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4453 device_role_t role,
4454 AudioDeviceTypeAddrVector &devices) {
4455 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004456}
4457
Jiabin Huang3b98d322020-09-03 17:54:16 +00004458status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4459 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4460 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4461 dumpAudioDeviceTypeAddrVector(devices).c_str());
4462
Mikhail Naganov55773032020-10-01 15:08:13 -07004463 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004464 return BAD_VALUE;
4465 }
4466 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4467 ALOGW_IF(status != NO_ERROR,
4468 "Engine could not set preferred devices %s for audio source %d role %d",
4469 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4470
4471 return status;
4472}
4473
4474status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4475 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4476 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4477 dumpAudioDeviceTypeAddrVector(devices).c_str());
4478
Mikhail Naganov55773032020-10-01 15:08:13 -07004479 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004480 return BAD_VALUE;
4481 }
4482 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4483 ALOGW_IF(status != NO_ERROR,
4484 "Engine could not add preferred devices %s for audio source %d role %d",
4485 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4486
Eric Laurent2517af32020-11-25 15:31:27 +01004487 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004488 return status;
4489}
4490
4491status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4492 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4493{
4494 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4495 dumpAudioDeviceTypeAddrVector(devices).c_str());
4496
Eric Laurent78fedbf2023-03-09 14:40:44 +01004497 if (!areAllDevicesSupported(
4498 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004499 return BAD_VALUE;
4500 }
4501
4502 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4503 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004504 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004505 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004506 if (status == NO_ERROR) {
4507 updateInputRouting();
4508 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004509 return status;
4510}
4511
4512status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4513 device_role_t role) {
4514 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4515
4516 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004517 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004518 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004519 if (status == NO_ERROR) {
4520 updateInputRouting();
4521 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004522 return status;
4523}
4524
4525status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4526 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4527 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4528}
4529
Oscar Azucena90e77632019-11-27 17:12:28 -08004530status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004531 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004532 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004533 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4534 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004535 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004536 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4537 if (status != NO_ERROR) {
4538 ALOGE("%s() could not set device affinity for userId %d",
4539 __FUNCTION__, userId);
4540 return status;
4541 }
4542
4543 // reevaluate outputs for all devices
4544 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004545 changeOutputDevicesMuteState(devices);
4546 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4547 true /* skipDelays */);
4548 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004549
4550 return NO_ERROR;
4551}
4552
4553status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004554 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004555 AudioDeviceTypeAddrVector devices;
4556 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004557 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4558 if (status != NO_ERROR) {
4559 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4560 __FUNCTION__, userId);
4561 return status;
4562 }
4563
4564 // reevaluate outputs for all devices
4565 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004566 changeOutputDevicesMuteState(devices);
4567 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4568 true /* skipDelays */);
4569 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004570
4571 return NO_ERROR;
4572}
4573
Andy Hungc29d82b2018-10-05 12:23:17 -07004574void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004575{
Andy Hungc29d82b2018-10-05 12:23:17 -07004576 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004577 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004578 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004579 std::string stateLiteral;
4580 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004581 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004582 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4583 "communications", "media", "record", "dock", "system",
4584 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4585 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4586 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004587 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4588 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4589 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4590 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4591 dst->append(" (MANUAL: ");
4592 dumpManualSurroundFormats(dst);
4593 dst->append(")");
4594 }
4595 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004596 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004597 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4598 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004599 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004600 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004601
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004602 dst->append("\n");
4603 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4604 dst->append("\n");
4605 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004606 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004607 mOutputs.dump(dst);
4608 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004609 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004610 mAudioPatches.dump(dst);
4611 mPolicyMixes.dump(dst);
4612 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004613
Kevin Rocardb99cc752019-03-21 20:52:24 -07004614 dst->appendFormat(" AllowedCapturePolicies:\n");
4615 for (auto& policy : mAllowedCapturePolicies) {
4616 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4617 }
4618
jiabina84c3d32022-12-02 18:59:55 +00004619 dst->appendFormat(" Preferred mixer audio configuration:\n");
4620 for (const auto it : mPreferredMixerAttrInfos) {
4621 dst->appendFormat(" - device port id: %d\n", it.first);
4622 for (const auto preferredMixerInfoIt : it.second) {
4623 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4624 preferredMixerInfoIt.second->dump(dst);
4625 }
4626 }
4627
François Gaffiec005e562018-11-06 15:04:49 +01004628 dst->appendFormat("\nPolicy Engine dump:\n");
4629 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004630
4631 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4632 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4633 dst->appendFormat(" - device type: %s, driving stream %d\n",
4634 dumpDeviceTypes({it.first}).c_str(),
4635 mEngine->getVolumeGroupForAttributes(it.second));
4636 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004637}
4638
4639status_t AudioPolicyManager::dump(int fd)
4640{
4641 String8 result;
4642 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004643 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004644 return NO_ERROR;
4645}
4646
Kevin Rocardb99cc752019-03-21 20:52:24 -07004647status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4648{
4649 mAllowedCapturePolicies[uid] = capturePolicy;
4650 return NO_ERROR;
4651}
4652
Eric Laurente552edb2014-03-10 17:42:56 -07004653// This function checks for the parameters which can be offloaded.
4654// This can be enhanced depending on the capability of the DSP and policy
4655// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004656audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004657{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004658 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004659 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004660 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004661 offloadInfo.format,
4662 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4663 offloadInfo.has_video);
4664
jiabin2b9d5a12021-12-10 01:06:29 +00004665 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004666 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004667 }
4668
4669 // See if there is a profile to support this.
4670 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004671 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004672 offloadInfo.sample_rate,
4673 offloadInfo.format,
4674 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004675 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4676 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004677 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4678 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4679 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004680 if (profile == nullptr) {
4681 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4682 }
4683 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4684 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4685 }
4686 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004687}
4688
Michael Chana94fbb22018-04-24 14:31:19 +10004689bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4690 const audio_attributes_t& attributes) {
4691 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004692 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004693 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4694 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004695 config.sample_rate,
4696 config.format,
4697 config.channel_mask,
4698 output_flags,
4699 true /* directOnly */);
4700 ALOGV("%s() profile %sfound with name: %s, "
4701 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4702 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004703 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004704 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004705
4706 // also try the MSD module if compatible profile not found
4707 if (profile == nullptr) {
4708 profile = getMsdProfileForOutput(outputDevices,
4709 config.sample_rate,
4710 config.format,
4711 config.channel_mask,
4712 output_flags,
4713 true /* directOnly */);
4714 ALOGV("%s() MSD profile %sfound with name: %s, "
4715 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4716 __FUNCTION__, profile != 0 ? "" : "NOT ",
4717 (profile != 0 ? profile->getTagName().c_str() : "null"),
4718 config.sample_rate, config.format, config.channel_mask, output_flags);
4719 }
4720 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004721}
4722
jiabin2b9d5a12021-12-10 01:06:29 +00004723bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4724 bool durationIgnored) {
4725 if (mMasterMono) {
4726 return false; // no offloading if mono is set.
4727 }
4728
4729 // Check if offload has been disabled
4730 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4731 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4732 return false;
4733 }
4734
4735 // Check if stream type is music, then only allow offload as of now.
4736 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4737 {
4738 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4739 return false;
4740 }
4741
4742 //TODO: enable audio offloading with video when ready
4743 const bool allowOffloadWithVideo =
4744 property_get_bool("audio.offload.video", false /* default_value */);
4745 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4746 ALOGV("%s: has_video == true, returning false", __func__);
4747 return false;
4748 }
4749
4750 //If duration is less than minimum value defined in property, return false
4751 const int min_duration_secs = property_get_int32(
4752 "audio.offload.min.duration.secs", -1 /* default_value */);
4753 if (!durationIgnored) {
4754 if (min_duration_secs >= 0) {
4755 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4756 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4757 __func__, min_duration_secs);
4758 return false;
4759 }
4760 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4761 ALOGV("%s: Offload denied by duration < default min(=%u)",
4762 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4763 return false;
4764 }
4765 }
4766
4767 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4768 // creating an offloaded track and tearing it down immediately after start when audioflinger
4769 // detects there is an active non offloadable effect.
4770 // FIXME: We should check the audio session here but we do not have it in this context.
4771 // This may prevent offloading in rare situations where effects are left active by apps
4772 // in the background.
4773 if (mEffects.isNonOffloadableEffectEnabled()) {
4774 return false;
4775 }
4776
4777 return true;
4778}
4779
4780audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4781 const audio_config_t *config) {
4782 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4783 offloadInfo.format = config->format;
4784 offloadInfo.sample_rate = config->sample_rate;
4785 offloadInfo.channel_mask = config->channel_mask;
4786 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4787 offloadInfo.has_video = false;
4788 offloadInfo.is_streaming = false;
4789 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4790
4791 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4792 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4793 audio_flags_to_audio_output_flags(attr->flags, &flags);
4794 // only retain flags that will drive compressed offload or passthrough
4795 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4796 if (offloadPossible) {
4797 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4798 }
4799 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4800
Dorin Drimusfae3c642022-03-17 18:36:30 +01004801 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004802 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004803 DeviceVector outputDevices = engineOutputDevices;
4804 // the MSD module checks for different conditions and output devices
4805 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4806 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4807 continue;
4808 }
4809 outputDevices = getMsdAudioOutDevices();
4810 }
jiabin2b9d5a12021-12-10 01:06:29 +00004811 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004812 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004813 config->sample_rate, nullptr /*updatedSamplingRate*/,
4814 config->format, nullptr /*updatedFormat*/,
4815 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004816 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004817 continue;
4818 }
4819 // reject profiles not corresponding to a device currently available
4820 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4821 continue;
4822 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004823 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4824 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004825 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004826 != AUDIO_DIRECT_NOT_SUPPORTED) {
4827 // Already reports offload gapless supported. No need to report offload support.
4828 continue;
4829 }
4830 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4831 != AUDIO_OUTPUT_FLAG_NONE) {
4832 // If offload gapless is reported, no need to report offload support.
4833 directMode = (audio_direct_mode_t) ((directMode &
4834 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4835 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4836 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004837 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004838 }
4839 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004840 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004841 }
4842 }
4843 }
4844 return directMode;
4845}
4846
Dorin Drimusf2196d82022-01-03 12:11:18 +01004847status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4848 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004849 if (mEffects.isNonOffloadableEffectEnabled()) {
4850 return OK;
4851 }
jiabinf1c73972022-04-14 16:28:52 -07004852 DeviceVector devices;
4853 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004854 if (status != OK) {
4855 return status;
4856 }
4857 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4858 if (devices.empty()) {
4859 return OK; // no output devices for the attributes
4860 }
jiabinf1c73972022-04-14 16:28:52 -07004861 return getProfilesForDevices(devices, audioProfilesVector,
4862 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004863}
4864
jiabina84c3d32022-12-02 18:59:55 +00004865status_t AudioPolicyManager::getSupportedMixerAttributes(
4866 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4867 ALOGV("%s, portId=%d", __func__, portId);
4868 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4869 if (deviceDescriptor == nullptr) {
4870 ALOGE("%s the requested device is currently unavailable", __func__);
4871 return BAD_VALUE;
4872 }
jiabin96daffc2023-05-11 17:51:55 +00004873 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4874 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4875 deviceDescriptor->type());
4876 return BAD_VALUE;
4877 }
jiabina84c3d32022-12-02 18:59:55 +00004878 for (const auto& hwModule : mHwModules) {
4879 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4880 if (curProfile->supportsDevice(deviceDescriptor)) {
4881 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4882 }
4883 }
4884 }
4885 return NO_ERROR;
4886}
4887
4888status_t AudioPolicyManager::setPreferredMixerAttributes(
4889 const audio_attributes_t *attr,
4890 audio_port_handle_t portId,
4891 uid_t uid,
4892 const audio_mixer_attributes_t *mixerAttributes) {
4893 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4894 "mixerBehavior=%d}, uid=%d, portId=%u",
4895 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4896 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4897 mixerAttributes->mixer_behavior, uid, portId);
4898 if (attr->usage != AUDIO_USAGE_MEDIA) {
4899 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4900 return BAD_VALUE;
4901 }
4902 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4903 if (deviceDescriptor == nullptr) {
4904 ALOGE("%s the requested device is currently unavailable", __func__);
4905 return BAD_VALUE;
4906 }
4907 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4908 ALOGE("%s(%d), type=%d, is not a usb output device",
4909 __func__, portId, deviceDescriptor->type());
4910 return BAD_VALUE;
4911 }
4912
4913 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4914 audio_flags_to_audio_output_flags(attr->flags, &flags);
4915 flags = (audio_output_flags_t) (flags |
4916 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4917 sp<IOProfile> profile = nullptr;
4918 DeviceVector devices(deviceDescriptor);
4919 for (const auto& hwModule : mHwModules) {
4920 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4921 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004922 && curProfile->getCompatibilityScore(
4923 devices,
4924 mixerAttributes->config.sample_rate,
4925 nullptr /*updatedSamplingRate*/,
4926 mixerAttributes->config.format,
4927 nullptr /*updatedFormat*/,
4928 mixerAttributes->config.channel_mask,
4929 nullptr /*updatedChannelMask*/,
4930 flags,
4931 false /*exactMatchRequiredForInputFlags*/)
4932 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004933 profile = curProfile;
4934 break;
4935 }
4936 }
4937 }
4938 if (profile == nullptr) {
4939 ALOGE("%s, there is no compatible profile found", __func__);
4940 return BAD_VALUE;
4941 }
4942
4943 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4944 sp<PreferredMixerAttributesInfo>::make(
4945 uid, portId, profile, flags, *mixerAttributes);
4946 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4947 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4948
4949 // If 1) there is any client from the preferred mixer configuration owner that is currently
4950 // active and matches the strategy and 2) current output is on the preferred device and the
4951 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4952 // configuration.
4953 std::vector<audio_io_handle_t> outputsToReopen;
4954 for (size_t i = 0; i < mOutputs.size(); i++) {
4955 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004956 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4957 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004958 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004959 } else {
4960 for (const auto &client: output->getActiveClients()) {
4961 if (client->uid() == uid && client->strategy() == strategy) {
4962 client->setIsInvalid();
4963 outputsToReopen.push_back(output->mIoHandle);
4964 }
jiabina84c3d32022-12-02 18:59:55 +00004965 }
4966 }
4967 }
4968 }
4969 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4970 config.sample_rate = mixerAttributes->config.sample_rate;
4971 config.channel_mask = mixerAttributes->config.channel_mask;
4972 config.format = mixerAttributes->config.format;
4973 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004974 sp<SwAudioOutputDescriptor> desc =
4975 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4976 if (desc == nullptr) {
4977 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4978 continue;
4979 }
jiabin220eea12024-05-17 17:55:20 +00004980 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004981 }
4982
4983 return NO_ERROR;
4984}
4985
4986sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004987 audio_port_handle_t devicePortId,
4988 product_strategy_t strategy,
4989 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004990 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4991 if (it == mPreferredMixerAttrInfos.end()) {
4992 return nullptr;
4993 }
jiabind9a58d32023-06-01 17:57:30 +00004994 if (activeBitPerfectPreferred) {
4995 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004996 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004997 return info;
4998 }
4999 }
jiabina84c3d32022-12-02 18:59:55 +00005000 }
jiabind9a58d32023-06-01 17:57:30 +00005001 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5002 return strategyMatchedMixerAttrInfoIt == it->second.end()
5003 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005004}
5005
5006status_t AudioPolicyManager::getPreferredMixerAttributes(
5007 const audio_attributes_t *attr,
5008 audio_port_handle_t portId,
5009 audio_mixer_attributes_t* mixerAttributes) {
5010 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5011 portId, mEngine->getProductStrategyForAttributes(*attr));
5012 if (info == nullptr) {
5013 return NAME_NOT_FOUND;
5014 }
5015 *mixerAttributes = info->getMixerAttributes();
5016 return NO_ERROR;
5017}
5018
5019status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5020 audio_port_handle_t portId,
5021 uid_t uid) {
5022 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5023 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5024 if (preferredMixerAttrInfo == nullptr) {
5025 return NAME_NOT_FOUND;
5026 }
5027 if (preferredMixerAttrInfo->getUid() != uid) {
5028 ALOGE("%s, requested uid=%d, owned uid=%d",
5029 __func__, uid, preferredMixerAttrInfo->getUid());
5030 return PERMISSION_DENIED;
5031 }
5032 mPreferredMixerAttrInfos[portId].erase(strategy);
5033 if (mPreferredMixerAttrInfos[portId].empty()) {
5034 mPreferredMixerAttrInfos.erase(portId);
5035 }
5036
5037 // Reconfig existing output
5038 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5039 for (size_t i = 0; i < mOutputs.size(); i++) {
5040 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5041 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5042 }
5043 }
5044 for (const auto output : potentialOutputsToReopen) {
5045 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5046 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5047 preferredMixerAttrInfo->getFlags())) {
5048 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5049 }
5050 }
5051 return NO_ERROR;
5052}
5053
Eric Laurent6a94d692014-05-20 11:18:06 -07005054status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5055 audio_port_type_t type,
5056 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005057 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005058 unsigned int *generation)
5059{
jiabin19cdba52020-11-24 11:28:58 -08005060 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5061 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005062 return BAD_VALUE;
5063 }
5064 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005065 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005066 *num_ports = 0;
5067 }
5068
5069 size_t portsWritten = 0;
5070 size_t portsMax = *num_ports;
5071 *num_ports = 0;
5072 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005073 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5074 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005076 for (const auto& dev : mAvailableOutputDevices) {
5077 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005078 continue;
5079 }
5080 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005081 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005082 }
5083 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005084 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005085 }
5086 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005087 for (const auto& dev : mAvailableInputDevices) {
5088 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005089 continue;
5090 }
5091 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005092 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005093 }
5094 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005095 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005096 }
5097 }
5098 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5099 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5100 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5101 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5102 }
5103 *num_ports += mInputs.size();
5104 }
5105 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005106 size_t numOutputs = 0;
5107 for (size_t i = 0; i < mOutputs.size(); i++) {
5108 if (!mOutputs[i]->isDuplicated()) {
5109 numOutputs++;
5110 if (portsWritten < portsMax) {
5111 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5112 }
5113 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005114 }
Eric Laurent84c70242014-06-23 08:46:27 -07005115 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005116 }
5117 }
jiabina84c3d32022-12-02 18:59:55 +00005118
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005120 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005121 return NO_ERROR;
5122}
5123
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005124status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5125 std::vector<media::AudioPortFw>* _aidl_return) {
5126 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5127 audio_port_v7 port;
5128 dev->toAudioPort(&port);
5129 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5130 _aidl_return->push_back(std::move(aidlPort));
5131 return OK;
5132 };
5133
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005134 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005135 for (const auto& dev : module->getDeclaredDevices()) {
5136 if (role == media::AudioPortRole::NONE ||
5137 ((role == media::AudioPortRole::SOURCE)
5138 == audio_is_input_device(dev->type()))) {
5139 RETURN_STATUS_IF_ERROR(pushPort(dev));
5140 }
5141 }
5142 }
5143 return OK;
5144}
5145
jiabin19cdba52020-11-24 11:28:58 -08005146status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005147{
Eric Laurent99fcae42018-05-17 16:59:18 -07005148 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5149 return BAD_VALUE;
5150 }
5151 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5152 if (dev != 0) {
5153 dev->toAudioPort(port);
5154 return NO_ERROR;
5155 }
5156 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5157 if (dev != 0) {
5158 dev->toAudioPort(port);
5159 return NO_ERROR;
5160 }
5161 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5162 if (out != 0) {
5163 out->toAudioPort(port);
5164 return NO_ERROR;
5165 }
5166 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5167 if (in != 0) {
5168 in->toAudioPort(port);
5169 return NO_ERROR;
5170 }
5171 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005172}
5173
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005174status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5175 audio_patch_handle_t *handle,
5176 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005177{
François Gaffieafd4cea2019-11-18 15:50:22 +01005178 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 if (handle == NULL || patch == NULL) {
5180 return BAD_VALUE;
5181 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005182 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005183 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005184 return BAD_VALUE;
5185 }
5186 // only one source per audio patch supported for now
5187 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 return INVALID_OPERATION;
5189 }
Eric Laurent874c42872014-08-08 15:13:39 -07005190 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 return INVALID_OPERATION;
5192 }
Eric Laurent874c42872014-08-08 15:13:39 -07005193 for (size_t i = 0; i < patch->num_sinks; i++) {
5194 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5195 return INVALID_OPERATION;
5196 }
5197 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005198
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005199 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5200 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5201 if (srcDevice == nullptr || sinkDevice == nullptr) {
5202 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5203 return BAD_VALUE;
5204 }
5205 ALOGV("%s between source %s and sink %s", __func__,
5206 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5207 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5208 // Default attributes, default volume priority, not to infer with non raw audio patches.
5209 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5210 const struct audio_port_config *source = &patch->sources[0];
5211 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005212 new SourceClientDescriptor(
5213 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5214 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005215 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005216 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005217
5218 status_t status =
5219 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5220
5221 if (status != NO_ERROR) {
5222 return INVALID_OPERATION;
5223 }
5224 mAudioSources.add(portId, sourceDesc);
5225 return NO_ERROR;
5226}
5227
5228status_t AudioPolicyManager::connectAudioSourceToSink(
5229 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5230 const struct audio_patch *patch,
5231 audio_patch_handle_t &handle,
5232 uid_t uid, uint32_t delayMs)
5233{
5234 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5235 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5236 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5237 return INVALID_OPERATION;
5238 }
5239 sourceDesc->connect(handle, sinkDevice);
5240 if (isMsdPatch(handle)) {
5241 return NO_ERROR;
5242 }
5243 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5244 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5245 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5246 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5247 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5248 goto FailurePatchAdded;
5249 }
5250 status = swOutput->start();
5251 if (status != NO_ERROR) {
5252 goto FailureSourceAdded;
5253 }
5254 swOutput->addClient(sourceDesc);
5255 status = startSource(swOutput, sourceDesc, &delayMs);
5256 if (status != NO_ERROR) {
5257 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5258 goto FailureSourceActive;
5259 }
5260 if (delayMs != 0) {
5261 usleep(delayMs * 1000);
5262 }
5263 return NO_ERROR;
5264
5265FailureSourceActive:
5266 swOutput->stop();
5267 releaseOutput(sourceDesc->portId());
5268FailureSourceAdded:
5269 sourceDesc->setSwOutput(nullptr);
5270FailurePatchAdded:
5271 releaseAudioPatchInternal(handle);
5272 return INVALID_OPERATION;
5273}
5274
5275status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5276 audio_patch_handle_t *handle,
5277 uid_t uid, uint32_t delayMs,
5278 const sp<SourceClientDescriptor>& sourceDesc)
5279{
5280 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005281 sp<AudioPatch> patchDesc;
5282 ssize_t index = mAudioPatches.indexOfKey(*handle);
5283
François Gaffieafd4cea2019-11-18 15:50:22 +01005284 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5285 patch->sources[0].role,
5286 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005287#if LOG_NDEBUG == 0
5288 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005289 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5290 patch->sinks[i].role,
5291 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005292 }
5293#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005294
5295 if (index >= 0) {
5296 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005297 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5298 __func__, mUidCached, patchDesc->getUid(), uid);
5299 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 return INVALID_OPERATION;
5301 }
5302 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005303 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005304 }
5305
5306 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005307 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005308 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005309 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005310 return BAD_VALUE;
5311 }
Eric Laurent84c70242014-06-23 08:46:27 -07005312 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5313 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 if (patchDesc != 0) {
5315 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005316 ALOGV("%s source id differs for patch current id %d new id %d",
5317 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 return BAD_VALUE;
5319 }
5320 }
Eric Laurent874c42872014-08-08 15:13:39 -07005321 DeviceVector devices;
5322 for (size_t i = 0; i < patch->num_sinks; i++) {
5323 // Only support mix to devices connection
5324 // TODO add support for mix to mix connection
5325 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005326 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005327 return INVALID_OPERATION;
5328 }
5329 sp<DeviceDescriptor> devDesc =
5330 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5331 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005332 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005333 return BAD_VALUE;
5334 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005335
jiabin66acc432024-02-06 00:57:36 +00005336 if (outputDesc->mProfile->getCompatibilityScore(
5337 DeviceVector(devDesc),
5338 patch->sources[0].sample_rate,
5339 nullptr, // updatedSamplingRate
5340 patch->sources[0].format,
5341 nullptr, // updatedFormat
5342 patch->sources[0].channel_mask,
5343 nullptr, // updatedChannelMask
5344 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005345 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005346 return INVALID_OPERATION;
5347 }
5348 devices.add(devDesc);
5349 }
5350 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005351 return INVALID_OPERATION;
5352 }
Eric Laurent874c42872014-08-08 15:13:39 -07005353
Eric Laurent6a94d692014-05-20 11:18:06 -07005354 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005355 ALOGV("%s setting device %s on output %d",
5356 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305357 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005358 index = mAudioPatches.indexOfKey(*handle);
5359 if (index >= 0) {
5360 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005361 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005362 }
5363 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005364 patchDesc->setUid(uid);
5365 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005367 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 return INVALID_OPERATION;
5369 }
5370 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5371 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5372 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005373 // only one sink supported when connecting an input device to a mix
5374 if (patch->num_sinks > 1) {
5375 return INVALID_OPERATION;
5376 }
François Gaffie53615e22015-03-19 09:24:12 +01005377 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005378 if (inputDesc == NULL) {
5379 return BAD_VALUE;
5380 }
5381 if (patchDesc != 0) {
5382 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5383 return BAD_VALUE;
5384 }
5385 }
François Gaffie11d30102018-11-02 16:09:09 +01005386 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005387 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005388 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005389 return BAD_VALUE;
5390 }
5391
jiabin66acc432024-02-06 00:57:36 +00005392 if (inputDesc->mProfile->getCompatibilityScore(
5393 DeviceVector(device),
5394 patch->sinks[0].sample_rate,
5395 nullptr, /*updatedSampleRate*/
5396 patch->sinks[0].format,
5397 nullptr, /*updatedFormat*/
5398 patch->sinks[0].channel_mask,
5399 nullptr, /*updatedChannelMask*/
5400 // FIXME for the parameter type,
5401 // and the NONE
5402 (audio_output_flags_t)
5403 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005404 return INVALID_OPERATION;
5405 }
5406 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005407 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005408 device->toString().c_str(), inputDesc->mIoHandle);
5409 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005410 index = mAudioPatches.indexOfKey(*handle);
5411 if (index >= 0) {
5412 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005413 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005414 }
5415 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005416 patchDesc->setUid(uid);
5417 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005418 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005419 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005420 return INVALID_OPERATION;
5421 }
5422 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5423 // device to device connection
5424 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005425 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005426 return BAD_VALUE;
5427 }
5428 }
François Gaffie11d30102018-11-02 16:09:09 +01005429 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005431 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005432 return BAD_VALUE;
5433 }
Eric Laurent874c42872014-08-08 15:13:39 -07005434
Eric Laurent6a94d692014-05-20 11:18:06 -07005435 //update source and sink with our own data as the data passed in the patch may
5436 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005437 PatchBuilder patchBuilder;
5438 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005439
5440 // if first sink is to MSD, establish single MSD patch
5441 if (getMsdAudioOutDevices().contains(
5442 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5443 ALOGV("%s patching to MSD", __FUNCTION__);
5444 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5445 goto installPatch;
5446 }
5447
François Gaffieafd4cea2019-11-18 15:50:22 +01005448 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5449 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005450
Eric Laurent874c42872014-08-08 15:13:39 -07005451 for (size_t i = 0; i < patch->num_sinks; i++) {
5452 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005453 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005454 return INVALID_OPERATION;
5455 }
François Gaffie11d30102018-11-02 16:09:09 +01005456 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005457 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005458 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005459 return BAD_VALUE;
5460 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005461 audio_port_config sinkPortConfig = {};
5462 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5463 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005464
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005465 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5466 // volume management purpose (tracking activity)
5467 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5468 // in config XML to reach the sink so that is can be declared as available.
5469 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005470 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005471 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005472 // take care of dynamic routing for SwOutput selection,
5473 audio_attributes_t attributes = sourceDesc->attributes();
5474 audio_stream_type_t stream = sourceDesc->stream();
5475 audio_attributes_t resultAttr;
5476 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5477 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005478 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5479 config.channel_mask =
5480 (audio_channel_mask_get_representation(sourceMask)
5481 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5482 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005483 config.format = sourceDesc->config().format;
5484 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5485 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5486 bool isRequestedDeviceForExclusiveUse = false;
5487 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005488 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005489 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005490 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5491 &stream, sourceDesc->uid(), &config, &flags,
5492 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005493 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005494 if (output == AUDIO_IO_HANDLE_NONE) {
5495 ALOGV("%s no output for device %s",
5496 __FUNCTION__, sinkDevice->toString().c_str());
5497 return INVALID_OPERATION;
5498 }
5499 outputDesc = mOutputs.valueFor(output);
5500 if (outputDesc->isDuplicated()) {
5501 ALOGE("%s output is duplicated", __func__);
5502 return INVALID_OPERATION;
5503 }
François Gaffie7e39df22022-04-26 12:48:49 +02005504 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5505 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005506 } else {
5507 // Same for "raw patches" aka created from createAudioPatch API
5508 SortedVector<audio_io_handle_t> outputs =
5509 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5510 // if the sink device is reachable via an opened output stream, request to
5511 // go via this output stream by adding a second source to the patch
5512 // description
5513 output = selectOutput(outputs);
5514 if (output == AUDIO_IO_HANDLE_NONE) {
5515 ALOGE("%s no output available for internal patch sink", __func__);
5516 return INVALID_OPERATION;
5517 }
5518 outputDesc = mOutputs.valueFor(output);
5519 if (outputDesc->isDuplicated()) {
5520 ALOGV("%s output for device %s is duplicated",
5521 __func__, sinkDevice->toString().c_str());
5522 return INVALID_OPERATION;
5523 }
François Gaffie7e39df22022-04-26 12:48:49 +02005524 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005525 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005526 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005527 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005528 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005529 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005530 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5531 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005532 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5533 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005534 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005535 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005536 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005537 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005538 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005539 return INVALID_OPERATION;
5540 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005541 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005542 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005543 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005544 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005545 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005546 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005547 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005548 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5549 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005550 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005551 }
Eric Laurent83b88082014-06-20 18:31:16 -07005552 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005553 }
5554 // TODO: check from routing capabilities in config file and other conflicting patches
5555
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005556installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005557 status_t status = installPatch(
5558 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005559 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005560 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005561 return INVALID_OPERATION;
5562 }
5563 } else {
5564 return BAD_VALUE;
5565 }
5566 } else {
5567 return BAD_VALUE;
5568 }
5569 return NO_ERROR;
5570}
5571
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005572status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005573{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005574 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005575 ssize_t index = mAudioPatches.indexOfKey(handle);
5576
5577 if (index < 0) {
5578 return BAD_VALUE;
5579 }
5580 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005581 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5582 __func__, mUidCached, patchDesc->getUid(), uid);
5583 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005584 return INVALID_OPERATION;
5585 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005586 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5587 for (size_t i = 0; i < mAudioSources.size(); i++) {
5588 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5589 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5590 portId = sourceDesc->portId();
5591 break;
5592 }
5593 }
5594 return portId != AUDIO_PORT_HANDLE_NONE ?
5595 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005596}
Eric Laurent6a94d692014-05-20 11:18:06 -07005597
François Gaffieafd4cea2019-11-18 15:50:22 +01005598status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005599 uint32_t delayMs,
5600 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005601{
5602 ALOGV("%s patch %d", __func__, handle);
5603 if (mAudioPatches.indexOfKey(handle) < 0) {
5604 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5605 return BAD_VALUE;
5606 }
5607 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005608 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005609 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005610 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005611 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005612 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005613 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005614 return BAD_VALUE;
5615 }
5616
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305617 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005618 getNewOutputDevices(outputDesc, true /*fromCache*/),
5619 true,
5620 0,
5621 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005622 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5623 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005624 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005625 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005626 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005627 return BAD_VALUE;
5628 }
5629 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005630 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005631 true,
5632 NULL);
5633 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005634 status_t status =
5635 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5636 ALOGV("%s patch panel returned %d patchHandle %d",
5637 __func__, status, patchDesc->getAfHandle());
5638 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005639 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005640 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005641 // SW or HW Bridge
5642 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5643 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005644 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005645 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5646 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5647 outputDesc = sourceDesc->swOutput().promote();
5648 }
5649 if (outputDesc == nullptr) {
5650 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5651 // releaseOutput has already called closeOutput in case of direct output
5652 return NO_ERROR;
5653 }
François Gaffie7e39df22022-04-26 12:48:49 +02005654 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005655 // While using a HwBridge, force reconsidering device only if not reusing an existing
5656 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005657 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005658 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5659 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5660 // Reconsider device only for cases:
5661 // 1 / Active Output
5662 // 2 / Inactive Output previously hosting HwBridge
5663 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5664 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5665 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305666 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005667 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5668 outputDesc->devices(),
5669 force,
5670 0,
5671 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005672 } else {
5673 return BAD_VALUE;
5674 }
5675 } else {
5676 return BAD_VALUE;
5677 }
5678 return NO_ERROR;
5679}
5680
5681status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5682 struct audio_patch *patches,
5683 unsigned int *generation)
5684{
François Gaffie53615e22015-03-19 09:24:12 +01005685 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005686 return BAD_VALUE;
5687 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005688 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005689 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005690}
5691
Eric Laurente1715a42014-05-20 11:30:42 -07005692status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005693{
Eric Laurente1715a42014-05-20 11:30:42 -07005694 ALOGV("setAudioPortConfig()");
5695
5696 if (config == NULL) {
5697 return BAD_VALUE;
5698 }
5699 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5700 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005701 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5702 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005703 }
5704
Eric Laurenta121f902014-06-03 13:32:54 -07005705 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005706 if (config->type == AUDIO_PORT_TYPE_MIX) {
5707 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005708 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005709 if (outputDesc == NULL) {
5710 return BAD_VALUE;
5711 }
Eric Laurent84c70242014-06-23 08:46:27 -07005712 ALOG_ASSERT(!outputDesc->isDuplicated(),
5713 "setAudioPortConfig() called on duplicated output %d",
5714 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005715 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005716 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005717 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005718 if (inputDesc == NULL) {
5719 return BAD_VALUE;
5720 }
Eric Laurenta121f902014-06-03 13:32:54 -07005721 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005722 } else {
5723 return BAD_VALUE;
5724 }
5725 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5726 sp<DeviceDescriptor> deviceDesc;
5727 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5728 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5729 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5730 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5731 } else {
5732 return BAD_VALUE;
5733 }
5734 if (deviceDesc == NULL) {
5735 return BAD_VALUE;
5736 }
Eric Laurenta121f902014-06-03 13:32:54 -07005737 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005738 } else {
5739 return BAD_VALUE;
5740 }
5741
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005742 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005743 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5744 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005745 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005746 audioPortConfig->toAudioPortConfig(&newConfig, config);
5747 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005748 }
Eric Laurenta121f902014-06-03 13:32:54 -07005749 if (status != NO_ERROR) {
5750 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005751 }
Eric Laurente1715a42014-05-20 11:30:42 -07005752
5753 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005754}
5755
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005756void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5757{
Eric Laurentd60560a2015-04-10 11:31:20 -07005758 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005759 clearAudioPatches(uid);
5760 clearSessionRoutes(uid);
5761}
5762
Eric Laurent6a94d692014-05-20 11:18:06 -07005763void AudioPolicyManager::clearAudioPatches(uid_t uid)
5764{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005765 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005766 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005767 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005768 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005769 }
5770 }
5771}
5772
François Gaffiec005e562018-11-06 15:04:49 +01005773void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005774{
François Gaffiec005e562018-11-06 15:04:49 +01005775 // Take the first attributes following the product strategy as it is used to retrieve the routed
5776 // device. All attributes wihin a strategy follows the same "routing strategy"
5777 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5778 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005779 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005780 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005781 for (size_t j = 0; j < mOutputs.size(); j++) {
5782 if (mOutputs.keyAt(j) == ouptutToSkip) {
5783 continue;
5784 }
5785 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005786 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005787 continue;
5788 }
5789 // If the default device for this strategy is on another output mix,
5790 // invalidate all tracks in this strategy to force re connection.
5791 // Otherwise select new device on the output mix.
5792 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005793 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005794 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005795 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005796 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005797 // If the device is using preferred mixer attributes, the output need to reopen
5798 // with default configuration when the new selected devices are different from
5799 // current routing devices.
5800 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5801 continue;
5802 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305803 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005804 }
5805 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005806 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005807}
5808
5809void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5810{
5811 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005812 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005813 for (size_t i = 0; i < mOutputs.size(); i++) {
5814 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005815 for (const auto& client : outputDesc->getClientIterable()) {
5816 if (client->hasPreferredDevice() && client->uid() == uid) {
5817 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005818 auto clientStrategy = client->strategy();
5819 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5820 end(affectedStrategies)) {
5821 continue;
5822 }
5823 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005824 }
5825 }
5826 }
5827 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005828 for (const auto& strategy : affectedStrategies) {
5829 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005830 }
5831
5832 // remove input routes associated with this uid
5833 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005834 for (size_t i = 0; i < mInputs.size(); i++) {
5835 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005836 for (const auto& client : inputDesc->getClientIterable()) {
5837 if (client->hasPreferredDevice() && client->uid() == uid) {
5838 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5839 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005840 }
5841 }
5842 }
5843 // reroute inputs if necessary
5844 SortedVector<audio_io_handle_t> inputsToClose;
5845 for (size_t i = 0; i < mInputs.size(); i++) {
5846 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005847 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005848 inputsToClose.add(inputDesc->mIoHandle);
5849 }
5850 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005851 for (const auto& input : inputsToClose) {
5852 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005853 }
5854}
5855
Eric Laurentd60560a2015-04-10 11:31:20 -07005856void AudioPolicyManager::clearAudioSources(uid_t uid)
5857{
5858 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005859 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5860 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005861 stopAudioSource(mAudioSources.keyAt(i));
5862 }
5863 }
5864}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005865
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005866status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5867 audio_io_handle_t *ioHandle,
5868 audio_devices_t *device)
5869{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005870 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5871 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005872 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005873 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5874 if (deviceDesc == nullptr) {
5875 return INVALID_OPERATION;
5876 }
5877 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005878
François Gaffiedf372692015-03-19 10:43:27 +01005879 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005880}
5881
Eric Laurentd60560a2015-04-10 11:31:20 -07005882status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005883 const audio_attributes_t *attributes,
5884 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005885 uid_t uid) {
5886 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005887 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005888}
5889
5890status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5891 const audio_attributes_t *attributes,
5892 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005893 uid_t uid, bool internal, bool isCallRx,
5894 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005895{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005896 ALOGV("%s", __FUNCTION__);
5897 *portId = AUDIO_PORT_HANDLE_NONE;
5898
5899 if (source == NULL || attributes == NULL || portId == NULL) {
5900 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5901 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005902 return BAD_VALUE;
5903 }
5904
Eric Laurentd60560a2015-04-10 11:31:20 -07005905 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5906 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005907 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5908 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005909 return INVALID_OPERATION;
5910 }
5911
François Gaffie11d30102018-11-02 16:09:09 +01005912 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005913 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005914 String8(source->ext.device.address),
5915 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005916 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005917 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005918 return BAD_VALUE;
5919 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005920
jiabin4ef93452019-09-10 14:29:54 -07005921 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005922
François Gaffieaaac0fd2018-11-22 17:56:39 +01005923 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005924 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005925 mEngine->getStreamTypeForAttributes(*attributes),
5926 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005927 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005928
David Lif85c5e32024-07-01 13:14:10 +00005929 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005930 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005931 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005932 }
5933 return status;
5934}
5935
David Lif85c5e32024-07-01 13:14:10 +00005936status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5937 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005938{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005939 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005940
5941 // make sure we only have one patch per source.
5942 disconnectAudioSource(sourceDesc);
5943
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005944 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005945 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5946 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5947 sourceDesc->srcDevice()->type(),
5948 String8(sourceDesc->srcDevice()->address().c_str()),
5949 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005950 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005951 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005952 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005953 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005954 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5955 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5956 return INVALID_OPERATION;
5957 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005958 PatchBuilder patchBuilder;
5959 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5960 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005961
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005962 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00005963 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005964}
5965
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005966status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005967{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005968 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5969 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005970 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005971 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005972 return BAD_VALUE;
5973 }
5974 status_t status = disconnectAudioSource(sourceDesc);
5975
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005976 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005977 return status;
5978}
5979
Andy Hung2ddee192015-12-18 17:34:44 -08005980status_t AudioPolicyManager::setMasterMono(bool mono)
5981{
5982 if (mMasterMono == mono) {
5983 return NO_ERROR;
5984 }
5985 mMasterMono = mono;
5986 // if enabling mono we close all offloaded devices, which will invalidate the
5987 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5988 // for recreating the new AudioTrack as non-offloaded PCM.
5989 //
5990 // If disabling mono, we leave all tracks as is: we don't know which clients
5991 // and tracks are able to be recreated as offloaded. The next "song" should
5992 // play back offloaded.
5993 if (mMasterMono) {
5994 Vector<audio_io_handle_t> offloaded;
5995 for (size_t i = 0; i < mOutputs.size(); ++i) {
5996 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5997 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5998 offloaded.push(desc->mIoHandle);
5999 }
6000 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006001 for (const auto& handle : offloaded) {
6002 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006003 }
6004 }
6005 // update master mono for all remaining outputs
6006 for (size_t i = 0; i < mOutputs.size(); ++i) {
6007 updateMono(mOutputs.keyAt(i));
6008 }
6009 return NO_ERROR;
6010}
6011
6012status_t AudioPolicyManager::getMasterMono(bool *mono)
6013{
6014 *mono = mMasterMono;
6015 return NO_ERROR;
6016}
6017
Eric Laurentac9cef52017-06-09 15:46:26 -07006018float AudioPolicyManager::getStreamVolumeDB(
6019 audio_stream_type_t stream, int index, audio_devices_t device)
6020{
Vlad Popa9d482762024-06-21 16:40:23 -07006021 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6022 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006023}
6024
jiabin81772902018-04-02 17:52:27 -07006025status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6026 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006027 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006028{
Kriti Dang6537def2021-03-02 13:46:59 +01006029 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6030 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006031 return BAD_VALUE;
6032 }
Kriti Dang6537def2021-03-02 13:46:59 +01006033 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6034 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006035
6036 size_t formatsWritten = 0;
6037 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006038
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006039 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006040 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6041 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006042 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006043 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006044 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006045 bool formatEnabled = true;
6046 switch (forceUse) {
6047 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006048 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006049 break;
6050 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6051 formatEnabled = false;
6052 break;
6053 default: // AUTO or ALWAYS => true
6054 break;
jiabin81772902018-04-02 17:52:27 -07006055 }
6056 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6057 }
jiabin81772902018-04-02 17:52:27 -07006058 }
6059 return NO_ERROR;
6060}
6061
Kriti Dang6537def2021-03-02 13:46:59 +01006062status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6063 audio_format_t *surroundFormats) {
6064 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6065 return BAD_VALUE;
6066 }
6067 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6068 __func__, *numSurroundFormats, surroundFormats);
6069
6070 size_t formatsWritten = 0;
6071 size_t formatsMax = *numSurroundFormats;
6072 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6073
6074 // Return formats from all device profiles that have already been resolved by
6075 // checkOutputsForDevice().
6076 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6077 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6078 audio_devices_t deviceType = device->type();
6079 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6080 // returns formats reported by HDMI devices.
6081 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6082 continue;
6083 }
6084 // Formats reported by sink devices
6085 std::unordered_set<audio_format_t> formatset;
6086 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6087 formatset.insert(it->second.begin(), it->second.end());
6088 }
6089
6090 // Formats hard-coded in the in policy configuration file (if any).
6091 FormatVector encodedFormats = device->encodedFormats();
6092 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6093 // Filter the formats which are supported by the vendor hardware.
6094 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006095 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006096 formats.insert(*it);
6097 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006098 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006099 if (pair.second.count(*it) != 0) {
6100 formats.insert(pair.first);
6101 break;
6102 }
6103 }
6104 }
6105 }
6106 }
6107 *numSurroundFormats = formats.size();
6108 for (const auto& format: formats) {
6109 if (formatsWritten < formatsMax) {
6110 surroundFormats[formatsWritten++] = format;
6111 }
6112 }
6113 return NO_ERROR;
6114}
6115
jiabin81772902018-04-02 17:52:27 -07006116status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6117{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006118 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006119 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6120 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006121 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006122 return BAD_VALUE;
6123 }
6124
Mikhail Naganov100f0122018-11-29 11:22:16 -08006125 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6126 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006127 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006128 return INVALID_OPERATION;
6129 }
6130
Mikhail Naganov100f0122018-11-29 11:22:16 -08006131 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006132 return NO_ERROR;
6133 }
6134
Mikhail Naganov100f0122018-11-29 11:22:16 -08006135 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006136 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006137 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006138 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006139 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006140 }
6141 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006142 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006143 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006144 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006145 }
6146 }
6147
6148 sp<SwAudioOutputDescriptor> outputDesc;
6149 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006150 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6151 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006152 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6153 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006154 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006155 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006156 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6157 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6158 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006159 name.c_str(),
6160 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006161 if (status != NO_ERROR) {
6162 continue;
6163 }
6164 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6165 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6166 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006167 name.c_str(),
6168 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006169 profileUpdated |= (status == NO_ERROR);
6170 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006171 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006172 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006173 AUDIO_DEVICE_IN_HDMI);
6174 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6175 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006176 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006177 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006178 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6179 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6180 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006181 name.c_str(),
6182 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006183 if (status != NO_ERROR) {
6184 continue;
6185 }
6186 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6187 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6188 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006189 name.c_str(),
6190 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006191 profileUpdated |= (status == NO_ERROR);
6192 }
6193
jiabin81772902018-04-02 17:52:27 -07006194 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006195 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006196 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006197 }
6198
6199 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6200}
6201
Eric Laurent5ada82e2019-08-29 17:53:54 -07006202void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006203{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006204 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006205 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006206 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006207 }
6208}
6209
jiabin6012f912018-11-02 17:06:30 -07006210bool AudioPolicyManager::isHapticPlaybackSupported()
6211{
6212 for (const auto& hwModule : mHwModules) {
6213 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6214 for (const auto &outProfile : outputProfiles) {
6215 struct audio_port audioPort;
6216 outProfile->toAudioPort(&audioPort);
6217 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6218 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6219 return true;
6220 }
6221 }
6222 }
6223 }
6224 return false;
6225}
6226
Carter Hsu325a8eb2022-01-19 19:56:51 +08006227bool AudioPolicyManager::isUltrasoundSupported()
6228{
6229 bool hasUltrasoundOutput = false;
6230 bool hasUltrasoundInput = false;
6231 for (const auto& hwModule : mHwModules) {
6232 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6233 if (!hasUltrasoundOutput) {
6234 for (const auto &outProfile : outputProfiles) {
6235 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6236 hasUltrasoundOutput = true;
6237 break;
6238 }
6239 }
6240 }
6241
6242 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6243 if (!hasUltrasoundInput) {
6244 for (const auto &inputProfile : inputProfiles) {
6245 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6246 hasUltrasoundInput = true;
6247 break;
6248 }
6249 }
6250 }
6251
6252 if (hasUltrasoundOutput && hasUltrasoundInput)
6253 return true;
6254 }
6255 return false;
6256}
6257
Atneya Nair698f5ef2022-12-15 16:15:09 -08006258bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6259{
6260 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6261 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6262 for (const auto& hwModule : mHwModules) {
6263 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6264 for (const auto &inputProfile : inputProfiles) {
6265 if ((inputProfile->getFlags() & mask) == mask) {
6266 return true;
6267 }
6268 }
6269 }
6270 return false;
6271}
6272
Eric Laurent8340e672019-11-06 11:01:08 -08006273bool AudioPolicyManager::isCallScreenModeSupported()
6274{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006275 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006276}
6277
6278
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006279status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006280{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006281 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006282 if (!sourceDesc->isConnected()) {
6283 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6284 return NO_ERROR;
6285 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006286 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6287 if (swOutput != 0) {
6288 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006289 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006290 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006291 }
jiabinbce0c1d2020-10-05 11:20:18 -07006292 if (releaseOutput(sourceDesc->portId())) {
6293 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6294 // no need to release audio patch here but just return NO_ERROR.
6295 return NO_ERROR;
6296 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006297 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006298 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006299 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006300 // close Hwoutput and remove from mHwOutputs
6301 } else {
6302 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6303 }
6304 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006305 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006306 sourceDesc->disconnect();
6307 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006308}
6309
François Gaffiec005e562018-11-06 15:04:49 +01006310sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6311 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006312{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006313 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006314 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006315 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006316 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006317 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6318 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006319 source = sourceDesc;
6320 break;
6321 }
6322 }
6323 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006324}
6325
Eric Laurentb4f42a92022-01-17 17:37:31 +01006326bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006327 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006328 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006329{
6330 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6331 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006332 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006333 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006334 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6335 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6336 return false;
6337 }
6338 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6339 return false;
6340 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006341 }
6342
Eric Laurentd332bc82023-08-04 11:45:23 +02006343 // The caller can have the audio config criteria ignored by either passing a null ptr or
6344 // the AUDIO_CONFIG_INITIALIZER value.
6345 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006346 // some positional channel masks and PCM format and for stereo if low latency performance
6347 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006348
6349 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006350 static const bool stereo_spatialization_enabled =
6351 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006352 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006353 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006354 ? audio_channel_mask_contains_stereo(config->channel_mask)
6355 : audio_is_channel_mask_spatialized(config->channel_mask);
6356 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006357 return false;
6358 }
6359 if (!audio_is_linear_pcm(config->format)) {
6360 return false;
6361 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006362 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6363 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6364 return false;
6365 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006366 }
6367
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006368 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006369 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006370 if (profile == nullptr) {
6371 return false;
6372 }
6373
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006374 return true;
6375}
6376
Shunkai Yao4c3af932024-04-26 04:12:21 +00006377// The Spatializer output is compatible with Haptic use cases if:
6378// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6379// with client if client haptic channel bits were set, or
6380// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6381// including the haptic bits or creating the HapticGenerator effect for same session.
6382bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6383 const audio_config_t* config, audio_session_t sessionId) const {
6384 const auto clientHapticChannel =
6385 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6386 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6387 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6388
6389 if (threadOutputHapticChannel) {
6390 // check format and sampleRate match if client haptic channel mask exist
6391 if (clientHapticChannel) {
6392 return mSpatializerOutput->getFormat() == config->format &&
6393 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6394 }
6395 return true;
6396 } else {
6397 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6398 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6399 // HapticGenerator effect for this session) are not supported.
6400 return clientHapticChannel == 0 &&
6401 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6402 }
6403}
6404
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006405void AudioPolicyManager::checkVirtualizerClientRoutes() {
6406 std::set<audio_stream_type_t> streamsToInvalidate;
6407 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006408 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6409 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006410 audio_attributes_t attr = client->attributes();
6411 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6412 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6413 audio_config_base_t clientConfig = client->config();
6414 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006415 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006416 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006417 streamsToInvalidate.insert(client->stream());
6418 }
6419 }
6420 }
6421
jiabinc44b3462022-12-08 12:52:31 -08006422 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006423}
6424
Eric Laurente191d1b2022-04-15 11:59:25 +02006425
6426bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6427 const sp<SwAudioOutputDescriptor>& outputDesc) {
6428 if (outputDesc->isDuplicated()) {
6429 return false;
6430 }
6431 DeviceVector devices = outputDesc->supportedDevices();
6432 for (size_t i = 0; i < mOutputs.size(); i++) {
6433 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6434 if (desc == outputDesc || desc->isDuplicated()) {
6435 continue;
6436 }
6437 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6438 if (!sharedDevices.isEmpty()
6439 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6440 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6441 return false;
6442 }
6443 }
6444 return true;
6445}
6446
6447
Eric Laurentfa0f6742021-08-17 18:39:44 +02006448status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006449 const audio_attributes_t *attr,
6450 audio_io_handle_t *output) {
6451 *output = AUDIO_IO_HANDLE_NONE;
6452
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006453 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6454 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6455 audio_config_t *configPtr = nullptr;
6456 audio_config_t config;
6457 if (mixerConfig != nullptr) {
6458 config = audio_config_initializer(mixerConfig);
6459 configPtr = &config;
6460 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006461 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006462 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006463 return BAD_VALUE;
6464 }
6465
6466 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006467 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006468 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006469 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006470 return BAD_VALUE;
6471 }
6472
Eric Laurente191d1b2022-04-15 11:59:25 +02006473 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006474 for (size_t i = 0; i < mOutputs.size(); i++) {
6475 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006476 if (!desc->isDuplicated()
6477 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6478 spatializerOutputs.push_back(desc);
6479 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006480 }
6481 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006482 mSpatializerOutput.clear();
6483 bool outputsChanged = false;
6484 for (const auto& desc : spatializerOutputs) {
6485 if (desc->mProfile == profile
6486 && (configPtr == nullptr
6487 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6488 mSpatializerOutput = desc;
6489 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6490 } else {
6491 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6492 " and devices %s", __func__, desc->mIoHandle,
6493 configPtr != nullptr ? configPtr->channel_mask : 0,
6494 devices.toString().c_str());
6495 closeOutput(desc->mIoHandle);
6496 outputsChanged = true;
6497 }
Eric Laurent39095982021-08-24 18:29:27 +02006498 }
6499
Eric Laurente191d1b2022-04-15 11:59:25 +02006500 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006501 sp<SwAudioOutputDescriptor> desc =
6502 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006503 if (desc != nullptr) {
6504 mSpatializerOutput = desc;
6505 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006506 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006507 }
6508
6509 checkVirtualizerClientRoutes();
6510
Eric Laurente191d1b2022-04-15 11:59:25 +02006511 if (outputsChanged) {
6512 mPreviousOutputs = mOutputs;
6513 mpClientInterface->onAudioPortListUpdate();
6514 }
6515
6516 if (mSpatializerOutput == nullptr) {
6517 ALOGV("%s could not open spatializer output with requested config", __func__);
6518 return BAD_VALUE;
6519 }
Eric Laurent39095982021-08-24 18:29:27 +02006520 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006521 ALOGV("%s returning new spatializer output %d", __func__, *output);
6522 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006523}
6524
Eric Laurentfa0f6742021-08-17 18:39:44 +02006525status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6526 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006527 return INVALID_OPERATION;
6528 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006529 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006530 return BAD_VALUE;
6531 }
Eric Laurent39095982021-08-24 18:29:27 +02006532
Eric Laurente191d1b2022-04-15 11:59:25 +02006533 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6534 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6535 closeOutput(mSpatializerOutput->mIoHandle);
6536 //from now on mSpatializerOutput is null
6537 checkVirtualizerClientRoutes();
6538 }
Eric Laurent39095982021-08-24 18:29:27 +02006539
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006540 return NO_ERROR;
6541}
6542
Eric Laurente552edb2014-03-10 17:42:56 -07006543// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006544// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006545// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006546uint32_t AudioPolicyManager::nextAudioPortGeneration()
6547{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006548 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006549}
6550
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006551AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006552 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006553 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006554 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006555 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006556 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006557 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006558 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006559 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006560 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006561 mAudioPortGeneration(1),
6562 mBeaconMuteRefCount(0),
6563 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006564 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006565 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006566 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006567 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006568{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006569}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006570
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006571status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006572 if (mEngine == nullptr) {
6573 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006574 }
6575 mEngine->setObserver(this);
6576 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006577 if (status != NO_ERROR) {
6578 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6579 return status;
6580 }
François Gaffie2110e042015-03-24 08:41:51 +01006581
jiabin29230182023-04-04 21:02:36 +00006582 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6583 // at the end of this function.
6584 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006585 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6586 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6587
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006588 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006589 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006590 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006591
Eric Laurent3a4311c2014-03-17 12:00:47 -07006592 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006593 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6594 defaultOutputDevice == nullptr ||
6595 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6596 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6597 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006598 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006599 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006600 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006601
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006602 // Silence ALOGV statements
6603 property_set("log.tag." LOG_TAG, "D");
6604
Eric Laurente552edb2014-03-10 17:42:56 -07006605 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006606 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006607}
6608
Eric Laurente0720872014-03-11 09:30:41 -07006609AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006610{
Eric Laurente552edb2014-03-10 17:42:56 -07006611 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006612 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006613 }
6614 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006615 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006616 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006617 mAvailableOutputDevices.clear();
6618 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006619 mOutputs.clear();
6620 mInputs.clear();
6621 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006622 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006623 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006624}
6625
Eric Laurente0720872014-03-11 09:30:41 -07006626status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006627{
Eric Laurent87ffa392015-05-22 10:32:38 -07006628 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006629}
6630
Eric Laurente552edb2014-03-10 17:42:56 -07006631// ---
6632
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006633void AudioPolicyManager::onNewAudioModulesAvailable()
6634{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006635 DeviceVector newDevices;
6636 onNewAudioModulesAvailableInt(&newDevices);
6637 if (!newDevices.empty()) {
6638 nextAudioPortGeneration();
6639 mpClientInterface->onAudioPortListUpdate();
6640 }
6641}
6642
6643void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6644{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006645 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006646 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6647 continue;
6648 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006649 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006650 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6651 handle != AUDIO_MODULE_HANDLE_NONE) {
6652 hwModule->setHandle(handle);
6653 } else {
6654 ALOGW("could not load HW module %s", hwModule->getName());
6655 continue;
6656 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006657 }
6658 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006659 // open all output streams needed to access attached devices.
6660 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006661 // This also validates mAvailableOutputDevices list
6662 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6663 if (!outProfile->canOpenNewIo()) {
6664 ALOGE("Invalid Output profile max open count %u for profile %s",
6665 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6666 continue;
6667 }
6668 if (!outProfile->hasSupportedDevices()) {
6669 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6670 continue;
6671 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006672 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6673 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006674 mTtsOutputAvailable = true;
6675 }
6676
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006677 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006678 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006679 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006680 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6681 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006682 } else {
6683 // choose first device present in profile's SupportedDevices also part of
6684 // mAvailableOutputDevices.
6685 if (availProfileDevices.isEmpty()) {
6686 continue;
6687 }
6688 supportedDevice = availProfileDevices.itemAt(0);
6689 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006690 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006691 continue;
6692 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306693
6694 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6695 && availProfileDevices.areAllDevicesAttached()) {
6696 ALOGV("%s skip opening output for mmap profile %s", __func__,
6697 outProfile->getTagName().c_str());
6698 continue;
6699 }
6700
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006701 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6702 mpClientInterface);
6703 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006704 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6705 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006706 AUDIO_STREAM_DEFAULT,
6707 AUDIO_OUTPUT_FLAG_NONE, &output);
6708 if (status != NO_ERROR) {
6709 ALOGW("Cannot open output stream for devices %s on hw module %s",
6710 supportedDevice->toString().c_str(), hwModule->getName());
6711 continue;
6712 }
6713 for (const auto &device : availProfileDevices) {
6714 // give a valid ID to an attached device once confirmed it is reachable
6715 if (!device->isAttached()) {
6716 device->attach(hwModule);
6717 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006718 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006719 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006720 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6721 }
6722 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006723 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006724 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6725 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006726 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006727 }
Eric Laurent39095982021-08-24 18:29:27 +02006728 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006729 outputDesc->close();
6730 } else {
6731 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306732 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006733 DeviceVector(supportedDevice),
6734 true,
6735 0,
6736 NULL);
6737 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006738 }
6739 // open input streams needed to access attached devices to validate
6740 // mAvailableInputDevices list
6741 for (const auto& inProfile : hwModule->getInputProfiles()) {
6742 if (!inProfile->canOpenNewIo()) {
6743 ALOGE("Invalid Input profile max open count %u for profile %s",
6744 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6745 continue;
6746 }
6747 if (!inProfile->hasSupportedDevices()) {
6748 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6749 continue;
6750 }
6751 // chose first device present in profile's SupportedDevices also part of
6752 // available input devices
6753 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006754 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006755 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006756 ALOGV("%s: Input device list is empty! for profile %s",
6757 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006758 continue;
6759 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306760
6761 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6762 && availProfileDevices.areAllDevicesAttached()) {
6763 ALOGV("%s skip opening input for mmap profile %s", __func__,
6764 inProfile->getTagName().c_str());
6765 continue;
6766 }
6767
Eric Laurentc71b11b2024-06-03 12:54:53 +00006768 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6769 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006770
6771 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6772 status_t status = inputDesc->open(nullptr,
6773 availProfileDevices.itemAt(0),
6774 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306775 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006776 &input);
6777 if (status != NO_ERROR) {
6778 ALOGW("Cannot open input stream for device %s on hw module %s",
6779 availProfileDevices.toString().c_str(),
6780 hwModule->getName());
6781 continue;
6782 }
6783 for (const auto &device : availProfileDevices) {
6784 // give a valid ID to an attached device once confirmed it is reachable
6785 if (!device->isAttached()) {
6786 device->attach(hwModule);
6787 device->importAudioPortAndPickAudioProfile(inProfile, true);
6788 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006789 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006790 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6791 }
6792 }
6793 inputDesc->close();
6794 }
6795 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006796
6797 // Check if spatializer outputs can be closed until used.
6798 // mOutputs vector never contains duplicated outputs at this point.
6799 std::vector<audio_io_handle_t> outputsClosed;
6800 for (size_t i = 0; i < mOutputs.size(); i++) {
6801 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6802 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6803 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6804 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006805 nextAudioPortGeneration();
6806 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6807 if (index >= 0) {
6808 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6809 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6810 patchDesc->getAfHandle(), 0);
6811 mAudioPatches.removeItemsAt(index);
6812 mpClientInterface->onAudioPatchListUpdate();
6813 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006814 desc->close();
6815 }
6816 }
6817 for (auto output : outputsClosed) {
6818 removeOutput(output);
6819 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006820}
6821
Eric Laurent98e38192018-02-15 18:31:53 -08006822void AudioPolicyManager::addOutput(audio_io_handle_t output,
6823 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006824{
Eric Laurent1c333e22014-05-20 10:48:17 -07006825 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006826 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006827 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006828 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006829 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006830}
6831
François Gaffie53615e22015-03-19 09:24:12 +01006832void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6833{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006834 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6835 ALOGV("%s: removing primary output", __func__);
6836 mPrimaryOutput = nullptr;
6837 }
François Gaffie53615e22015-03-19 09:24:12 +01006838 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006839 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006840}
6841
Eric Laurent98e38192018-02-15 18:31:53 -08006842void AudioPolicyManager::addInput(audio_io_handle_t input,
6843 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006844{
Eric Laurent1c333e22014-05-20 10:48:17 -07006845 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006846 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006847}
Eric Laurente552edb2014-03-10 17:42:56 -07006848
François Gaffie11d30102018-11-02 16:09:09 +01006849status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006850 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006851 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006852{
François Gaffie11d30102018-11-02 16:09:09 +01006853 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006854 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006855 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006856
François Gaffie11d30102018-11-02 16:09:09 +01006857 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006858 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006859 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006860 }
Eric Laurente552edb2014-03-10 17:42:56 -07006861
Eric Laurent3b73df72014-03-11 09:06:29 -07006862 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006863 // first call getAudioPort to get the supported attributes from the HAL
6864 struct audio_port_v7 port = {};
6865 device->toAudioPort(&port);
6866 status_t status = mpClientInterface->getAudioPort(&port);
6867 if (status == NO_ERROR) {
6868 device->importAudioPort(port);
6869 }
6870
6871 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006872 for (size_t i = 0; i < mOutputs.size(); i++) {
6873 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006874 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006875 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006876 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6877 mOutputs.keyAt(i), device->toString().c_str());
6878 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006879 }
6880 }
6881 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006882 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006883 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006884 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6885 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006886 if (profile->supportsDevice(device)) {
6887 profiles.add(profile);
6888 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6889 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006890 }
6891 }
6892 }
6893
Eric Laurent7b279bb2015-12-14 10:18:23 -08006894 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006895
Eric Laurente552edb2014-03-10 17:42:56 -07006896 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006897 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006898 return BAD_VALUE;
6899 }
6900
6901 // open outputs for matching profiles if needed. Direct outputs are also opened to
6902 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6903 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006904 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006905
6906 // nothing to do if one output is already opened for this profile
6907 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006908 for (j = 0; j < outputs.size(); j++) {
6909 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006910 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006911 // matching profile: save the sample rates, format and channel masks supported
6912 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006913 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006914 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006915 }
Eric Laurente552edb2014-03-10 17:42:56 -07006916 break;
6917 }
6918 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006919 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006920 continue;
6921 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306922 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6923 ALOGV("%s skip opening output for mmap profile %s",
6924 __func__, profile->getTagName().c_str());
6925 continue;
6926 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006927 if (!profile->canOpenNewIo()) {
6928 ALOGW("Max Output number %u already opened for this profile %s",
6929 profile->maxOpenCount, profile->getTagName().c_str());
6930 continue;
6931 }
6932
Eric Laurent83efe1c2017-07-09 16:51:08 -07006933 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006934 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006935 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6936 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006937 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006938 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006939 profiles.removeAt(profile_index);
6940 profile_index--;
6941 } else {
6942 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006943 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006944 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006945 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6946 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006947 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006948 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006949
François Gaffie11d30102018-11-02 16:09:09 +01006950 if (device_distinguishes_on_address(deviceType)) {
6951 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6952 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306953 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6954 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006955 }
Eric Laurente552edb2014-03-10 17:42:56 -07006956 ALOGV("checkOutputsForDevice(): adding output %d", output);
6957 }
6958 }
6959
6960 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006961 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006962 return BAD_VALUE;
6963 }
Eric Laurentd4692962014-05-05 18:13:44 -07006964 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006965 // check if one opened output is not needed any more after disconnecting one device
6966 for (size_t i = 0; i < mOutputs.size(); i++) {
6967 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006968 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006969 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006970 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006971 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006972 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006973 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006974 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6975 mOutputs.keyAt(i));
6976 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006977 }
Eric Laurente552edb2014-03-10 17:42:56 -07006978 }
6979 }
Eric Laurentd4692962014-05-05 18:13:44 -07006980 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006981 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006982 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6983 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006984 if (!profile->supportsDevice(device)) {
6985 continue;
6986 }
6987 ALOGV("checkOutputsForDevice(): "
6988 "clearing direct output profile %zu on module %s",
6989 j, hwModule->getName());
6990 profile->clearAudioProfiles();
6991 if (!profile->hasDynamicAudioProfile()) {
6992 continue;
6993 }
6994 // When a device is disconnected, if there is an IOProfile that contains dynamic
6995 // profiles and supports the disconnected device, call getAudioPort to repopulate
6996 // the capabilities of the devices that is supported by the IOProfile.
6997 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6998 if (supportedDevice == device ||
6999 !mAvailableOutputDevices.contains(supportedDevice)) {
7000 continue;
7001 }
7002 struct audio_port_v7 port;
7003 supportedDevice->toAudioPort(&port);
7004 status_t status = mpClientInterface->getAudioPort(&port);
7005 if (status == NO_ERROR) {
7006 supportedDevice->importAudioPort(port);
7007 }
Eric Laurente552edb2014-03-10 17:42:56 -07007008 }
7009 }
7010 }
7011 }
7012 return NO_ERROR;
7013}
7014
François Gaffie11d30102018-11-02 16:09:09 +01007015status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007016 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007017{
François Gaffie11d30102018-11-02 16:09:09 +01007018 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007019 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007020 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007021 }
7022
Eric Laurentd4692962014-05-05 18:13:44 -07007023 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007024 sp<AudioInputDescriptor> desc;
7025
jiabinbf5f4262023-04-12 21:48:34 +00007026 // first call getAudioPort to get the supported attributes from the HAL
7027 struct audio_port_v7 port = {};
7028 device->toAudioPort(&port);
7029 status_t status = mpClientInterface->getAudioPort(&port);
7030 if (status == NO_ERROR) {
7031 device->importAudioPort(port);
7032 }
7033
Eric Laurent0dd51852019-04-19 18:18:58 -07007034 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007035 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007036 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007037 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007038 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007039 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007040 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007041
François Gaffie11d30102018-11-02 16:09:09 +01007042 if (profile->supportsDevice(device)) {
7043 profiles.add(profile);
7044 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
7045 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007046 }
7047 }
7048 }
7049
Eric Laurent0dd51852019-04-19 18:18:58 -07007050 if (profiles.isEmpty()) {
7051 ALOGW("%s: No input profile available for device %s",
7052 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007053 return BAD_VALUE;
7054 }
7055
7056 // open inputs for matching profiles if needed. Direct inputs are also opened to
7057 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7058 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7059
Eric Laurent1c333e22014-05-20 10:48:17 -07007060 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007061
Eric Laurentd4692962014-05-05 18:13:44 -07007062 // nothing to do if one input is already opened for this profile
7063 size_t input_index;
7064 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7065 desc = mInputs.valueAt(input_index);
7066 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007067 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007068 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007069 }
Eric Laurentd4692962014-05-05 18:13:44 -07007070 break;
7071 }
7072 }
7073 if (input_index != mInputs.size()) {
7074 continue;
7075 }
7076
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307077 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7078 ALOGV("%s skip opening input for mmap profile %s",
7079 __func__, profile->getTagName().c_str());
7080 continue;
7081 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007082 if (!profile->canOpenNewIo()) {
7083 ALOGW("Max Input number %u already opened for this profile %s",
7084 profile->maxOpenCount, profile->getTagName().c_str());
7085 continue;
7086 }
7087
Eric Laurentc71b11b2024-06-03 12:54:53 +00007088 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007089 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307090 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7091 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007092
Eric Laurentcf2c0212014-07-25 16:20:43 -07007093 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007094 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007095 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007096 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007097 mpClientInterface->setParameters(input, String8(param));
7098 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007099 }
jiabin12537fc2023-10-12 17:56:08 +00007100 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007101 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007102 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08007103 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007104 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007105 }
7106
Eric Laurent0dd51852019-04-19 18:18:58 -07007107 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007108 addInput(input, desc);
7109 }
7110 } // endif input != 0
7111
Eric Laurentcf2c0212014-07-25 16:20:43 -07007112 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08007113 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01007114 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007115 profiles.removeAt(profile_index);
7116 profile_index--;
7117 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007118 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007119 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007120 }
Eric Laurentd4692962014-05-05 18:13:44 -07007121 ALOGV("checkInputsForDevice(): adding input %d", input);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007122
7123 if (checkCloseInput(desc)) {
7124 ALOGV("%s closing input %d", __func__, input);
7125 closeInput(input);
7126 }
Eric Laurentd4692962014-05-05 18:13:44 -07007127 }
7128 } // end scan profiles
7129
7130 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007131 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007132 return BAD_VALUE;
7133 }
7134 } else {
7135 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007136 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007137 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007138 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007139 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007140 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007141 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007142 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08007143 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
7144 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007145 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007146 }
7147 }
7148 }
7149 } // end disconnect
7150
7151 return NO_ERROR;
7152}
7153
7154
Eric Laurente0720872014-03-11 09:30:41 -07007155void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007156{
7157 ALOGV("closeOutput(%d)", output);
7158
François Gaffie1c878552018-11-22 16:53:21 +01007159 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7160 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007161 ALOGW("closeOutput() unknown output %d", output);
7162 return;
7163 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007164 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007165 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007166
Eric Laurente552edb2014-03-10 17:42:56 -07007167 // look for duplicated outputs connected to the output being removed.
7168 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007169 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7170 if (dupOutput->isDuplicated() &&
7171 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7172 sp<SwAudioOutputDescriptor> remainingOutput =
7173 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007174 // As all active tracks on duplicated output will be deleted,
7175 // and as they were also referenced on the other output, the reference
7176 // count for their stream type must be adjusted accordingly on
7177 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007178 const bool wasActive = remainingOutput->isActive();
7179 // Note: no-op on the closing output where all clients has already been set inactive
7180 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007181 // stop() will be a no op if the output is still active but is needed in case all
7182 // active streams refcounts where cleared above
7183 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007184 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007185 }
Eric Laurente552edb2014-03-10 17:42:56 -07007186 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7187 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7188
7189 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007190 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007191 }
7192 }
7193
Eric Laurent05b90f82014-08-27 15:32:29 -07007194 nextAudioPortGeneration();
7195
François Gaffie1c878552018-11-22 16:53:21 +01007196 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007197 if (index >= 0) {
7198 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007199 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7200 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007201 mAudioPatches.removeItemsAt(index);
7202 mpClientInterface->onAudioPatchListUpdate();
7203 }
7204
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007205 if (closingOutputWasActive) {
7206 closingOutput->stop();
7207 }
François Gaffie1c878552018-11-22 16:53:21 +01007208 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007209 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007210 for (const auto device : closingOutput->devices()) {
7211 device->setPreferredConfig(nullptr);
7212 }
7213 }
Eric Laurente552edb2014-03-10 17:42:56 -07007214
François Gaffie53615e22015-03-19 09:24:12 +01007215 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007216 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007217 if (closingOutput == mSpatializerOutput) {
7218 mSpatializerOutput.clear();
7219 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007220
7221 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7222 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007223 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007224 bool directOutputOpen = false;
7225 for (size_t i = 0; i < mOutputs.size(); i++) {
7226 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7227 directOutputOpen = true;
7228 break;
7229 }
7230 }
7231 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007232 ALOGV("no direct outputs open, reset MSD patches");
7233 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7234 // how output devices for patching are resolved. Avoid by caching and reusing the
7235 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7236 // devices to patch to. This may be complicated by the fact that devices may become
7237 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007238 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007239 }
7240 }
jiabin220eea12024-05-17 17:55:20 +00007241
7242 if (closingOutput->mPreferredAttrInfo != nullptr) {
7243 closingOutput->mPreferredAttrInfo->resetActiveClient();
7244 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007245}
7246
7247void AudioPolicyManager::closeInput(audio_io_handle_t input)
7248{
7249 ALOGV("closeInput(%d)", input);
7250
7251 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7252 if (inputDesc == NULL) {
7253 ALOGW("closeInput() unknown input %d", input);
7254 return;
7255 }
7256
Eric Laurent6a94d692014-05-20 11:18:06 -07007257 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007258
François Gaffie11d30102018-11-02 16:09:09 +01007259 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007260 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007261 if (index >= 0) {
7262 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007263 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7264 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007265 mAudioPatches.removeItemsAt(index);
7266 mpClientInterface->onAudioPatchListUpdate();
7267 }
7268
François Gaffie6ebbce02023-07-19 13:27:53 +02007269 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007270 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007271 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007272
François Gaffie11d30102018-11-02 16:09:09 +01007273 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7274 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007275 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007276 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007277 }
Eric Laurente552edb2014-03-10 17:42:56 -07007278}
7279
François Gaffie11d30102018-11-02 16:09:09 +01007280SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7281 const DeviceVector &devices,
7282 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007283{
7284 SortedVector<audio_io_handle_t> outputs;
7285
François Gaffie11d30102018-11-02 16:09:09 +01007286 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007287 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007288 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007289 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007290 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007291 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007292 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007293 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007294 outputs.add(openOutputs.keyAt(i));
7295 }
7296 }
7297 return outputs;
7298}
7299
Mikhail Naganov37977152018-07-11 15:54:44 -07007300void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7301{
7302 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7303 // output is suspended before any tracks are moved to it
7304 checkA2dpSuspend();
7305 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007306 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007307 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007308 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007309 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007310 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7311 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7312 // configuration changes will ultimately be rerouted correctly. We can still avoid
7313 // unnecessary rerouting by caching and reusing the arguments to
7314 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7315 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007316 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007317 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007318 // an event that changed routing likely occurred, inform upper layers
7319 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007320}
7321
François Gaffiec005e562018-11-06 15:04:49 +01007322bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7323 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007324{
François Gaffiec005e562018-11-06 15:04:49 +01007325 return mEngine->getProductStrategyForAttributes(lAttr) ==
7326 mEngine->getProductStrategyForAttributes(rAttr);
7327}
7328
Francois Gaffieff1eb522020-05-06 18:37:04 +02007329void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7330{
7331 for (size_t i = 0; i < mAudioSources.size(); i++) {
7332 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7333 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007334 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007335 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007336 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007337 }
7338 }
7339}
7340
7341void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7342{
7343 for (size_t i = 0; i < mAudioSources.size(); i++) {
7344 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7345 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7346 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7347 disconnectAudioSource(sourceDesc);
7348 }
7349 }
7350}
7351
François Gaffiec005e562018-11-06 15:04:49 +01007352void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7353{
7354 auto psId = mEngine->getProductStrategyForAttributes(attr);
7355
7356 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7357 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007358
François Gaffie11d30102018-11-02 16:09:09 +01007359 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7360 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007361
Eric Laurentc209fe42020-06-05 18:11:23 -07007362 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007363 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007364 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007365 // take into account dynamic audio policies related changes: if a client is now associated
7366 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007367 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007368 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7369 if (desc->isDuplicated()) {
7370 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007371 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007372 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7373 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7374 continue;
7375 }
7376 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007377 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007378 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7379 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7380 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007381 if (status != OK) {
7382 continue;
7383 }
yucliuf4de36d2020-09-14 14:57:56 -07007384 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007385 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007386 maxLatency = desc->latency();
7387 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007388 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007389 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007390 }
7391 }
7392
Eric Laurent56ed8842022-11-15 16:04:41 +01007393 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007394 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7395 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007396 for (audio_io_handle_t srcOut : srcOutputs) {
7397 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007398 if (desc == nullptr) continue;
7399
7400 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007401 maxLatency = desc->latency();
7402 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007403
Eric Laurent56ed8842022-11-15 16:04:41 +01007404 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007405 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007406 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007407 // a client on a non direct outputs has necessarily a linear PCM format
7408 // so we can call selectOutput() safely
7409 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7410 client->flags(),
7411 client->config().format,
7412 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007413 client->config().sample_rate,
7414 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007415 if (newOutput != srcOut) {
7416 invalidate = true;
7417 break;
7418 }
7419 } else {
7420 sp<IOProfile> profile = getProfileForOutput(newDevices,
7421 client->config().sample_rate,
7422 client->config().format,
7423 client->config().channel_mask,
7424 client->flags(),
7425 true /* directOnly */);
7426 if (profile != desc->mProfile) {
7427 invalidate = true;
7428 break;
7429 }
7430 }
7431 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007432 // mute strategy while moving tracks from one output to another
7433 if (invalidate) {
7434 invalidatedOutputs.push_back(desc);
7435 if (desc->isStrategyActive(psId)) {
7436 setStrategyMute(psId, true, desc);
7437 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7438 newDevices.types());
7439 }
Eric Laurente552edb2014-03-10 17:42:56 -07007440 }
François Gaffiec005e562018-11-06 15:04:49 +01007441 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007442 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007443 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007444 }
Eric Laurente552edb2014-03-10 17:42:56 -07007445 }
7446
Eric Laurent56ed8842022-11-15 16:04:41 +01007447 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7448 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7449 std::to_string(srcOutputs[0]).c_str(),
7450 std::to_string(dstOutputs[0]).c_str());
7451
François Gaffiec005e562018-11-06 15:04:49 +01007452 // Move effects associated to this stream from previous output to new output
7453 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007454 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007455 }
François Gaffiec005e562018-11-06 15:04:49 +01007456 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007457 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007458 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007459 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007460 desc->setTracksInvalidatedStatusByStrategy(psId);
7461 }
Eric Laurente552edb2014-03-10 17:42:56 -07007462 }
7463 }
7464}
7465
Eric Laurente0720872014-03-11 09:30:41 -07007466void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007467{
François Gaffiec005e562018-11-06 15:04:49 +01007468 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7469 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7470 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007471 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007472 }
Eric Laurente552edb2014-03-10 17:42:56 -07007473}
7474
Kevin Rocard153f92d2018-12-18 18:33:28 -08007475void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007476 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007477 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007478 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007479 for (size_t i = 0; i < mOutputs.size(); i++) {
7480 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7481 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007482 sp<AudioPolicyMix> primaryMix;
7483 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007484 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007485 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7486 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7487 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007488 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7489 for (auto &secondaryMix : secondaryMixes) {
7490 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7491 if (outputDesc != nullptr &&
7492 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7493 secondaryDescs.push_back(outputDesc);
7494 }
7495 }
7496
jiabinc44b3462022-12-08 12:52:31 -08007497 if (status != OK &&
7498 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7499 // When it failed to query secondary output, only invalidate the client that is not
7500 // MMAP. The reason is that MMAP stream will not support secondary output.
7501 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007502 } else if (!std::equal(
7503 client->getSecondaryOutputs().begin(),
7504 client->getSecondaryOutputs().end(),
7505 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007506 if (!audio_is_linear_pcm(client->config().format)) {
7507 // If the format is not PCM, the tracks should be invalidated to get correct
7508 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007509 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007510 } else {
7511 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7512 std::vector<audio_io_handle_t> secondaryOutputIds;
7513 for (const auto &secondaryDesc: secondaryDescs) {
7514 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7515 weakSecondaryDescs.push_back(secondaryDesc);
7516 }
7517 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7518 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007519 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007520 }
7521 }
7522 }
jiabin10a03f12021-05-07 23:46:28 +00007523 if (!trackSecondaryOutputs.empty()) {
7524 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7525 }
jiabinc44b3462022-12-08 12:52:31 -08007526 if (!clientsToInvalidate.empty()) {
7527 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7528 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007529 }
7530}
7531
Eric Laurent2517af32020-11-25 15:31:27 +01007532bool AudioPolicyManager::isScoRequestedForComm() const {
7533 AudioDeviceTypeAddrVector devices;
7534 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7535 for (const auto &device : devices) {
7536 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7537 return true;
7538 }
7539 }
7540 return false;
7541}
7542
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007543bool AudioPolicyManager::isHearingAidUsedForComm() const {
7544 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7545 true /*fromCache*/);
7546 for (const auto &device : devices) {
7547 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7548 return true;
7549 }
7550 }
7551 return false;
7552}
7553
7554
Eric Laurente0720872014-03-11 09:30:41 -07007555void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007556{
François Gaffie53615e22015-03-19 09:24:12 +01007557 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007558 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007559 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007560 return;
7561 }
7562
Eric Laurent3a4311c2014-03-17 12:00:47 -07007563 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007564 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7565 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007566 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007567
7568 // if suspended, restore A2DP output if:
7569 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007570 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007571 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007572 //
Eric Laurentf732e072016-08-03 19:30:28 -07007573 // if not suspended, suspend A2DP output if:
7574 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007575 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007576 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007577 //
7578 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007579 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007580 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007581 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007582 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007583
7584 mpClientInterface->restoreOutput(a2dpOutput);
7585 mA2dpSuspended = false;
7586 }
7587 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007588 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007589 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007590 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007591 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007592
7593 mpClientInterface->suspendOutput(a2dpOutput);
7594 mA2dpSuspended = true;
7595 }
7596 }
7597}
7598
François Gaffie11d30102018-11-02 16:09:09 +01007599DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7600 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007601{
François Gaffiedb1755b2023-09-01 11:50:35 +02007602 if (outputDesc == nullptr) {
7603 return DeviceVector{};
7604 }
François Gaffie11d30102018-11-02 16:09:09 +01007605
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007606 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007607 if (index >= 0) {
7608 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007609 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007610 ALOGV("%s device %s forced by patch %d", __func__,
7611 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7612 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007613 }
7614 }
7615
Dean Wheatley514b4312020-06-17 21:45:00 +10007616 // Do not retrieve engine device for outputs through MSD
7617 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7618 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7619 return outputDesc->devices();
7620 }
7621
Eric Laurent97ac8712018-07-27 18:59:02 -07007622 // Honor explicit routing requests only if no client using default routing is active on this
7623 // input: a specific app can not force routing for other apps by setting a preferred device.
7624 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007625 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007626 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007627 if (device != nullptr) {
7628 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007629 }
7630
François Gaffiea807ef92018-11-05 10:44:33 +01007631 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7632 // of setForceUse / Default Bus device here
7633 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7634 if (device != nullptr) {
7635 return DeviceVector(device);
7636 }
7637
François Gaffiedb1755b2023-09-01 11:50:35 +02007638 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007639 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7640 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307641 auto hasStreamActive = [&](auto stream) {
7642 return hasStream(streams, stream) && isStreamActive(stream, 0);
7643 };
Eric Laurent484e9272018-06-07 17:29:23 -07007644
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307645 auto doGetOutputDevicesForVoice = [&]() {
7646 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007647 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307648 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007649 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7650 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307651 };
7652
7653 // With low-latency playing on speaker, music on WFD, when the first low-latency
7654 // output is stopped, getNewOutputDevices checks for a product strategy
7655 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007656 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307657 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7658 // stream is associated to the output descriptor.
7659 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7660 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7661 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7662 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007663 // Retrieval of devices for voice DL is done on primary output profile, cannot
7664 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007665 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007666 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7667 break;
7668 }
Eric Laurente552edb2014-03-10 17:42:56 -07007669 }
François Gaffiec005e562018-11-06 15:04:49 +01007670 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007671 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007672}
7673
François Gaffie11d30102018-11-02 16:09:09 +01007674sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7675 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007676{
François Gaffie11d30102018-11-02 16:09:09 +01007677 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007678
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007679 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007680 if (index >= 0) {
7681 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007682 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007683 ALOGV("getNewInputDevice() device %s forced by patch %d",
7684 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7685 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007686 }
7687 }
7688
Eric Laurent97ac8712018-07-27 18:59:02 -07007689 // Honor explicit routing requests only if no client using default routing is active on this
7690 // input: a specific app can not force routing for other apps by setting a preferred device.
7691 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007692 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7693 if (device != nullptr) {
7694 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007695 }
7696
Eric Laurentdc95a252018-04-12 12:46:56 -07007697 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007698 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007699 audio_attributes_t attributes;
7700 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007701 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007702 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7703 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007704 attributes = topClient->attributes();
7705 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007706 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007707 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007708 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7709 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007710 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007711 }
7712
Francois Gaffie716e1432019-01-14 16:58:59 +01007713 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7714 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007715 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007716 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007717 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007718 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007719
Eric Laurente552edb2014-03-10 17:42:56 -07007720 return device;
7721}
7722
Eric Laurent794fde22016-03-11 09:50:45 -08007723bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7724 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007725 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007726}
7727
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007728status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007729 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007730 if (devices == nullptr) {
7731 return BAD_VALUE;
7732 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007733
Andy Hung6d23c0f2022-02-16 09:37:15 -08007734 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007735 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7736 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007737 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007738 for (const auto& device : curDevices) {
7739 devices->push_back(device->getDeviceTypeAddr());
7740 }
7741 return NO_ERROR;
7742}
7743
Eric Laurente0720872014-03-11 09:30:41 -07007744void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007745 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007746 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007747 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007748 updateDevicesAndOutputs();
7749 break;
7750 default:
7751 break;
7752 }
7753}
7754
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007755uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007756
7757 // skip beacon mute management if a dedicated TTS output is available
7758 if (mTtsOutputAvailable) {
7759 return 0;
7760 }
7761
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007762 switch(event) {
7763 case STARTING_OUTPUT:
7764 mBeaconMuteRefCount++;
7765 break;
7766 case STOPPING_OUTPUT:
7767 if (mBeaconMuteRefCount > 0) {
7768 mBeaconMuteRefCount--;
7769 }
7770 break;
7771 case STARTING_BEACON:
7772 mBeaconPlayingRefCount++;
7773 break;
7774 case STOPPING_BEACON:
7775 if (mBeaconPlayingRefCount > 0) {
7776 mBeaconPlayingRefCount--;
7777 }
7778 break;
7779 }
7780
7781 if (mBeaconMuteRefCount > 0) {
7782 // any playback causes beacon to be muted
7783 return setBeaconMute(true);
7784 } else {
7785 // no other playback: unmute when beacon starts playing, mute when it stops
7786 return setBeaconMute(mBeaconPlayingRefCount == 0);
7787 }
7788}
7789
7790uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7791 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7792 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7793 // keep track of muted state to avoid repeating mute/unmute operations
7794 if (mBeaconMuted != mute) {
7795 // mute/unmute AUDIO_STREAM_TTS on all outputs
7796 ALOGV("\t muting %d", mute);
7797 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007798 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7799 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7800 ALOGV("\t no tts volume source available");
7801 return 0;
7802 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007803 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007804 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007805 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007806 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007807 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007808 maxLatency = latency;
7809 }
7810 }
7811 mBeaconMuted = mute;
7812 return maxLatency;
7813 }
7814 return 0;
7815}
7816
Eric Laurente0720872014-03-11 09:30:41 -07007817void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007818{
François Gaffiec005e562018-11-06 15:04:49 +01007819 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007820 mPreviousOutputs = mOutputs;
7821}
7822
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007823uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007824 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007825 uint32_t delayMs)
7826{
7827 // mute/unmute strategies using an incompatible device combination
7828 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7829 // if unmuting, unmute only after the specified delay
7830 if (outputDesc->isDuplicated()) {
7831 return 0;
7832 }
7833
7834 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007835 DeviceVector devices = outputDesc->devices();
7836 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007837
François Gaffiec005e562018-11-06 15:04:49 +01007838 auto productStrategies = mEngine->getOrderedProductStrategies();
7839 for (const auto &productStrategy : productStrategies) {
7840 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7841 DeviceVector curDevices =
7842 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7843 curDevices = curDevices.filter(outputDesc->supportedDevices());
7844 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007845 bool doMute = false;
7846
François Gaffiec005e562018-11-06 15:04:49 +01007847 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007848 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007849 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7850 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007851 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007852 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007853 }
Eric Laurent99401132014-05-07 19:48:15 -07007854 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007855 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007856 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007857 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007858 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007859 continue;
7860 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307861 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007862 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7863 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7864 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007865 if (mute) {
7866 // FIXME: should not need to double latency if volume could be applied
7867 // immediately by the audioflinger mixer. We must account for the delay
7868 // between now and the next time the audioflinger thread for this output
7869 // will process a buffer (which corresponds to one buffer size,
7870 // usually 1/2 or 1/4 of the latency).
7871 if (muteWaitMs < desc->latency() * 2) {
7872 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007873 }
7874 }
7875 }
7876 }
7877 }
7878 }
7879
Eric Laurent99401132014-05-07 19:48:15 -07007880 // temporary mute output if device selection changes to avoid volume bursts due to
7881 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007882 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007883 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007884
Eric Laurentdc462862016-07-19 12:29:53 -07007885 if (muteWaitMs < tempMuteWaitMs) {
7886 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007887 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007888
7889 // If recommended duration is defined, replace temporary mute duration to avoid
7890 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7891 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7892 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7893 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7894 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7895
François Gaffieaaac0fd2018-11-22 17:56:39 +01007896 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7897 // make sure that we do not start the temporary mute period too early in case of
7898 // delayed device change
7899 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7900 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007901 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007902 }
7903 }
7904
Eric Laurente552edb2014-03-10 17:42:56 -07007905 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7906 if (muteWaitMs > delayMs) {
7907 muteWaitMs -= delayMs;
7908 usleep(muteWaitMs * 1000);
7909 return muteWaitMs;
7910 }
7911 return 0;
7912}
7913
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307914uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7915 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007916 const DeviceVector &devices,
7917 bool force,
7918 int delayMs,
7919 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007920 bool requiresMuteCheck, bool requiresVolumeCheck,
7921 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007922{
jiabin3ff8d7d2022-12-13 06:27:44 +00007923 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307924 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7925 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7926 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007927 uint32_t muteWaitMs;
7928
7929 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307930 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007931 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307932 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007933 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007934 return muteWaitMs;
7935 }
Eric Laurente552edb2014-03-10 17:42:56 -07007936
7937 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007938 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007939 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007940 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007941
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307942 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7943 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007944
7945 if (!filteredDevices.isEmpty()) {
7946 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007947 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007948
7949 // if the outputs are not materially active, there is no need to mute.
7950 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007951 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007952 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307953 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7954 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007955 muteWaitMs = 0;
7956 }
Eric Laurente552edb2014-03-10 17:42:56 -07007957
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007958 bool outputRouted = outputDesc->isRouted();
7959
Eric Laurent79ea9582020-06-11 18:49:24 -07007960 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7961 // output profile or if new device is not supported AND previous device(s) is(are) still
7962 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007963 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307964 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7965 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007966 // restore previous device after evaluating strategy mute state
7967 outputDesc->setDevices(prevDevices);
7968 return muteWaitMs;
7969 }
7970
Eric Laurente552edb2014-03-10 17:42:56 -07007971 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007972 // the requested device is AUDIO_DEVICE_NONE
7973 // OR the requested device is the same as current device
7974 // AND force is not specified
7975 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007976 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007977 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307978 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7979 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7980 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007981 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307982 ALOGV("%s %s setting same device on routed output, force apply volumes",
7983 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007984 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7985 }
Eric Laurente552edb2014-03-10 17:42:56 -07007986 return muteWaitMs;
7987 }
7988
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307989 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7990 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007991
Eric Laurente552edb2014-03-10 17:42:56 -07007992 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007993 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007994 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007995 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007996 PatchBuilder patchBuilder;
7997 patchBuilder.addSource(outputDesc);
7998 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7999 for (const auto &filteredDevice : filteredDevices) {
8000 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008001 }
8002
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008003 // Add half reported latency to delayMs when muteWaitMs is null in order
8004 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008005 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8006 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8007 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008008 }
Eric Laurente552edb2014-03-10 17:42:56 -07008009
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008010 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8011 if (!skipMuteDelay) {
8012 // update stream volumes according to new device
8013 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8014 }
Eric Laurente552edb2014-03-10 17:42:56 -07008015
8016 return muteWaitMs;
8017}
8018
Eric Laurentc75307b2015-03-17 15:29:32 -07008019status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008020 int delayMs,
8021 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008022{
Eric Laurent6a94d692014-05-20 11:18:06 -07008023 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008024 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8025 return INVALID_OPERATION;
8026 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008027 if (patchHandle) {
8028 index = mAudioPatches.indexOfKey(*patchHandle);
8029 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008030 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008031 }
8032 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008033 return INVALID_OPERATION;
8034 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008035 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008036 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008037 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008038 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008039 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008040 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008041 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008042 return status;
8043}
8044
8045status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008046 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008047 bool force,
8048 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008049{
8050 status_t status = NO_ERROR;
8051
Eric Laurent1f2f2232014-06-02 12:01:23 -07008052 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008053 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8054 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008055
François Gaffie11d30102018-11-02 16:09:09 +01008056 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008057 PatchBuilder patchBuilder;
8058 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008059 // AUDIO_SOURCE_HOTWORD is for internal use only:
8060 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008061 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8062 auto result = usecase;
8063 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8064 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8065 }
8066 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07008067 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01008068 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008069 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008070 }
8071 }
8072 return status;
8073}
8074
Eric Laurent6a94d692014-05-20 11:18:06 -07008075status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8076 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008077{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008078 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008079 ssize_t index;
8080 if (patchHandle) {
8081 index = mAudioPatches.indexOfKey(*patchHandle);
8082 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008083 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008084 }
8085 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008086 return INVALID_OPERATION;
8087 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008088 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008089 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008090 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008091 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008092 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008093 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008094 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008095 return status;
8096}
8097
François Gaffie11d30102018-11-02 16:09:09 +01008098sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008099 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008100 audio_format_t& format,
8101 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008102 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008103{
8104 // Choose an input profile based on the requested capture parameters: select the first available
8105 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008106 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008107
Atneya Nair0f0a8032022-12-12 16:20:12 -08008108 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8109 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8110 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8111
8112 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008113
jiabin2fd710d2022-05-02 23:20:22 +00008114 for (;;) {
8115 sp<IOProfile> firstInexact = nullptr;
8116 uint32_t updatedSamplingRate = 0;
8117 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8118 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8119 for (const auto& hwModule : mHwModules) {
8120 for (const auto& profile : hwModule->getInputProfiles()) {
8121 // profile->log();
8122 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008123 if (profile->getCompatibilityScore(
8124 DeviceVector(device),
8125 samplingRate,
8126 &updatedSamplingRate,
8127 format,
8128 &updatedFormat,
8129 channelMask,
8130 &updatedChannelMask,
8131 // FIXME ugly cast
8132 (audio_output_flags_t) flags,
8133 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8134 samplingRate = updatedSamplingRate;
8135 format = updatedFormat;
8136 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008137 return profile;
8138 }
jiabin66acc432024-02-06 00:57:36 +00008139 if (firstInexact == nullptr
8140 && profile->getCompatibilityScore(
8141 DeviceVector(device),
8142 samplingRate,
8143 &updatedSamplingRate,
8144 format,
8145 &updatedFormat,
8146 channelMask,
8147 &updatedChannelMask,
8148 // FIXME ugly cast
8149 (audio_output_flags_t) flags,
8150 false /*exactMatchRequiredForInputFlags*/)
8151 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008152 firstInexact = profile;
8153 }
8154 }
8155 }
8156
8157 if (firstInexact != nullptr) {
8158 samplingRate = updatedSamplingRate;
8159 format = updatedFormat;
8160 channelMask = updatedChannelMask;
8161 return firstInexact;
8162 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8163 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8164 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8165 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8166 flags = AUDIO_INPUT_FLAG_NONE;
8167 } else { // fail
8168 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8169 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8170 samplingRate, format, channelMask, oriFlags);
8171 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008172 }
8173 }
jiabin2fd710d2022-05-02 23:20:22 +00008174
8175 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008176}
8177
Vlad Popa87e0e582024-05-20 18:49:20 -07008178float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8179 VolumeSource volumeSource,
8180 int index,
8181 const DeviceTypeSet &deviceTypes)
8182{
8183 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8184 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8185 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8186
8187 if (com_android_media_audio_abs_volume_index_fix()) {
8188 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8189 mAbsoluteVolumeDrivingStreams.end()) {
8190 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8191 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8192 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8193 ALOGD("%s: no group matching with %s", __FUNCTION__,
8194 toString(attributesToDriveAbs).c_str());
8195 return volumeDb;
8196 }
8197
8198 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8199 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8200 if (vsToDriveAbs == volumeSource) {
8201 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008202 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008203 } else {
8204 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8205 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8206 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8207 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8208 curvesAbs.getVolumeIndexMax());
8209 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8210 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8211 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8212 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8213 return newVolumeDb;
8214 }
8215 }
8216 return volumeDb;
8217 } else {
8218 return volumeDb;
8219 }
8220}
8221
François Gaffieaaac0fd2018-11-22 17:56:39 +01008222float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8223 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008224 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008225 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008226 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008227 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008228{
Vlad Popa9d482762024-06-21 16:40:23 -07008229 float volumeDb;
8230 if (adjustAttenuation) {
8231 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8232 } else {
8233 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8234 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008235 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8236 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8237
8238 if (!computeInternalInteraction) {
8239 return volumeDb;
8240 }
8241
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008242 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8243 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8244 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8245 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008246 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8247 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8248 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8249 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8250 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008251 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008252 mOutputs.isActive(ringVolumeSrc, 0)) {
8253 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008254 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008255 adjustAttenuation,
8256 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008257 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008258 }
8259
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008260 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008261 if ((volumeSource != callVolumeSrc && (isInCall() ||
8262 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008263 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008264 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8265 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008266 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8267 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8268 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008269 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008270 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008271 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008272 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008273 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008274 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008275 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008276 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8277 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8278 // programmatically muted.
8279 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8280 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8281 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008282 bool exemptFromCapping =
8283 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8284 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008285 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8286 volumeSource, volumeDb);
8287 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008288 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8289 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8290 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008291 }
8292 }
Eric Laurente552edb2014-03-10 17:42:56 -07008293 // if a headset is connected, apply the following rules to ring tones and notifications
8294 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008295 // - always attenuate notifications volume by 6dB
8296 // - attenuate ring tones volume by 6dB unless music is not playing and
8297 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008298 // - if music is playing, always limit the volume to current music volume,
8299 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008300 if (!Intersection(deviceTypes,
8301 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8302 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008303 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8304 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008305 ((volumeSource == alarmVolumeSrc ||
8306 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008307 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8308 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8309 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008310 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8311 curves.canBeMuted()) {
8312
Eric Laurente552edb2014-03-10 17:42:56 -07008313 // when the phone is ringing we must consider that music could have been paused just before
8314 // by the music application and behave as if music was active if the last music track was
8315 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008316 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8317 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008318 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008319 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008320 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8321 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008322 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008323 float musicVolDb = computeVolume(musicCurves,
8324 musicVolumeSrc,
8325 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008326 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008327 adjustAttenuation,
8328 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008329 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8330 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8331 if (volumeDb > minVolDb) {
8332 volumeDb = minVolDb;
8333 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008334 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008335 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8336 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008337 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8338 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8339 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8340 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008341 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008342 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008343 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8344 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008345 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8346 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008347 }
8348 }
jiabin9a3361e2019-10-01 09:38:30 -07008349 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008350 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008351 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008352 }
8353 }
8354
François Gaffie43c73442018-11-08 08:21:55 +01008355 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008356}
8357
Eric Laurent3839bc02018-07-10 18:33:34 -07008358int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008359 VolumeSource fromVolumeSource,
8360 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008361{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008362 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008363 return srcIndex;
8364 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008365 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8366 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008367 float minSrc = (float)srcCurves.getVolumeIndexMin();
8368 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8369 float minDst = (float)dstCurves.getVolumeIndexMin();
8370 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008371
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008372 // preserve mute request or correct range
8373 if (srcIndex < minSrc) {
8374 if (srcIndex == 0) {
8375 return 0;
8376 }
8377 srcIndex = minSrc;
8378 } else if (srcIndex > maxSrc) {
8379 srcIndex = maxSrc;
8380 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008381 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8382}
8383
François Gaffieaaac0fd2018-11-22 17:56:39 +01008384status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8385 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008386 int index,
8387 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008388 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008389 int delayMs,
8390 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008391{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008392 // do not change actual attributes volume if the attributes is muted
8393 if (outputDesc->isMuted(volumeSource)) {
8394 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8395 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008396 return NO_ERROR;
8397 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008398
Eric Laurentae6e88c2024-01-10 14:42:57 +01008399 bool isVoiceVolSrc;
8400 bool isBtScoVolSrc;
8401 if (!isVolumeConsistentForCalls(
8402 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008403 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008404 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008405 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008406 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008407
jiabin9a3361e2019-10-01 09:38:30 -07008408 if (deviceTypes.empty()) {
8409 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008410 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008411 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008412 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008413 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008414
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008415 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8416 ALOGE("invalid volume index range");
8417 return BAD_VALUE;
8418 }
8419
jiabin9a3361e2019-10-01 09:38:30 -07008420 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8421 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008422 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008423 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008424 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8425 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008426 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008427 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008428 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008429 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8430 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008431
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008432 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008433 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8434 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8435 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008436 }
Eric Laurente552edb2014-03-10 17:42:56 -07008437 return NO_ERROR;
8438}
8439
Eric Laurentae6e88c2024-01-10 14:42:57 +01008440void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008441 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008442 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008443 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008444 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008445 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008446 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8447 } else {
8448 voiceVolume = index == 0 ? 0.0 : 1.0;
8449 }
8450 if (voiceVolume != mLastVoiceVolume) {
8451 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8452 mLastVoiceVolume = voiceVolume;
8453 }
8454}
8455
8456bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8457 const DeviceTypeSet& deviceTypes,
8458 bool& isVoiceVolSrc,
8459 bool& isBtScoVolSrc,
8460 const char* caller) {
8461 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8462 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8463 const bool isScoRequested = isScoRequestedForComm();
8464 const bool isHAUsed = isHearingAidUsedForComm();
8465
8466 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8467 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8468
8469 if ((callVolSrc != btScoVolSrc) &&
8470 ((isVoiceVolSrc && isScoRequested) ||
8471 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8472 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8473 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8474 volumeSource, isScoRequested ? " " : " not ");
8475 return false;
8476 }
8477 return true;
8478}
8479
Eric Laurentc75307b2015-03-17 15:29:32 -07008480void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008481 const DeviceTypeSet& deviceTypes,
8482 int delayMs,
8483 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008484{
jiabincd510522020-01-22 09:40:55 -08008485 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008486 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8487 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8488 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008489 curves.getVolumeIndex(deviceTypes),
8490 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008491 }
8492}
8493
François Gaffiec005e562018-11-06 15:04:49 +01008494void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8495 bool on,
8496 const sp<AudioOutputDescriptor>& outputDesc,
8497 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008498 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008499{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008500 std::vector<VolumeSource> sourcesToMute;
8501 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8502 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8503 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008504 VolumeSource source = toVolumeSource(attributes, false);
8505 if ((source != VOLUME_SOURCE_NONE) &&
8506 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8507 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008508 sourcesToMute.push_back(source);
8509 }
Eric Laurente552edb2014-03-10 17:42:56 -07008510 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008511 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008512 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008513 }
8514
Eric Laurente552edb2014-03-10 17:42:56 -07008515}
8516
François Gaffieaaac0fd2018-11-22 17:56:39 +01008517void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8518 bool on,
8519 const sp<AudioOutputDescriptor>& outputDesc,
8520 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008521 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008522{
jiabin9a3361e2019-10-01 09:38:30 -07008523 if (deviceTypes.empty()) {
8524 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008525 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008526 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008527 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008528 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008529 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008530 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008531 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8532 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008533 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008534 }
8535 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008536 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8537 // ignored
8538 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008539 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008540 if (!outputDesc->isMuted(volumeSource)) {
8541 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008542 return;
8543 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008544 if (outputDesc->decMuteCount(volumeSource) == 0) {
8545 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008546 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008547 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008548 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008549 delayMs);
8550 }
8551 }
8552}
8553
François Gaffie53615e22015-03-19 09:24:12 +01008554bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8555{
François Gaffiec005e562018-11-06 15:04:49 +01008556 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008557 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8558 return true;
8559 }
8560
8561 // has known usage?
8562 switch (paa->usage) {
8563 case AUDIO_USAGE_UNKNOWN:
8564 case AUDIO_USAGE_MEDIA:
8565 case AUDIO_USAGE_VOICE_COMMUNICATION:
8566 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8567 case AUDIO_USAGE_ALARM:
8568 case AUDIO_USAGE_NOTIFICATION:
8569 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8570 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8571 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8572 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8573 case AUDIO_USAGE_NOTIFICATION_EVENT:
8574 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8575 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8576 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8577 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008578 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008579 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008580 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008581 case AUDIO_USAGE_EMERGENCY:
8582 case AUDIO_USAGE_SAFETY:
8583 case AUDIO_USAGE_VEHICLE_STATUS:
8584 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008585 break;
8586 default:
8587 return false;
8588 }
8589 return true;
8590}
8591
François Gaffie2110e042015-03-24 08:41:51 +01008592audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8593{
8594 return mEngine->getForceUse(usage);
8595}
8596
Eric Laurent96d1dda2022-03-14 17:14:19 +01008597bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008598 return isStateInCall(mEngine->getPhoneState());
8599}
8600
Eric Laurent96d1dda2022-03-14 17:14:19 +01008601bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008602 return is_state_in_call(state);
8603}
8604
Eric Laurentf9cccec2022-11-16 19:12:00 +01008605bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008606 audio_mode_t mode = mEngine->getPhoneState();
8607 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008608 || (mode == AUDIO_MODE_CALL_SCREEN)
8609 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008610}
8611
Eric Laurentf9cccec2022-11-16 19:12:00 +01008612bool AudioPolicyManager::isInCallOrScreening() const {
8613 audio_mode_t mode = mEngine->getPhoneState();
8614 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8615}
8616
Eric Laurentd60560a2015-04-10 11:31:20 -07008617void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8618{
8619 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008620 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008621 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008622 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008623 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008624 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008625 }
8626 }
8627
8628 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8629 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8630 bool release = false;
8631 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8632 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8633 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8634 source->ext.device.type == deviceDesc->type()) {
8635 release = true;
8636 }
8637 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008638 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008639 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8640 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8641 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008642 sink->ext.device.type == deviceDesc->type() &&
8643 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8644 || strncmp(sink->ext.device.address, address,
8645 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008646 release = true;
8647 }
8648 }
8649 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008650 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8651 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008652 }
8653 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008654
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008655 mInputs.clearSessionRoutesForDevice(deviceDesc);
8656
Francois Gaffie716e1432019-01-14 16:58:59 +01008657 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008658}
8659
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008660void AudioPolicyManager::modifySurroundFormats(
8661 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008662 std::unordered_set<audio_format_t> enforcedSurround(
8663 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008664 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008665 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008666 allSurround.insert(pair.first);
8667 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8668 }
Phil Burk09bc4612016-02-24 15:58:15 -08008669
8670 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8671 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008672 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008673 // This is the resulting set of formats depending on the surround mode:
8674 // 'all surround' = allSurround
8675 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8676 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8677 // 'manual surround' = mManualSurroundFormats
8678 // AUTO: formats v 'enforced surround'
8679 // ALWAYS: formats v 'all surround' v 'enforced surround'
8680 // NEVER: formats ^ 'non-surround'
8681 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008682
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008683 std::unordered_set<audio_format_t> formatSet;
8684 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8685 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008686 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008687 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008688 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008689 formatSet.insert(*formatIter);
8690 }
8691 }
8692 } else {
8693 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8694 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008695 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008696
jiabin81772902018-04-02 17:52:27 -07008697 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008698 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008699 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8700 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8701 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008702 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008703 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8704 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8705 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008706 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008707 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008708 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008709 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008710 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008711 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008712}
8713
jiabin06e4bab2019-07-29 10:13:34 -07008714void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8715 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008716 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8717 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8718
8719 // If NEVER, then remove support for channelMasks > stereo.
8720 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008721 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8722 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008723 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008724 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008725 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008726 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008727 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008728 }
8729 }
jiabin81772902018-04-02 17:52:27 -07008730 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8731 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8732 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008733 bool supports5dot1 = false;
8734 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008735 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008736 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8737 supports5dot1 = true;
8738 break;
8739 }
8740 }
8741 // If not then add 5.1 support.
8742 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008743 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008744 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008745 }
Phil Burk09bc4612016-02-24 15:58:15 -08008746 }
8747}
8748
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008749void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008750 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008751 const sp<IOProfile>& profile) {
8752 if (!profile->hasDynamicAudioProfile()) {
8753 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008754 }
François Gaffie112b0af2015-11-19 16:13:25 +01008755
jiabin12537fc2023-10-12 17:56:08 +00008756 audio_port_v7 devicePort;
8757 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008758
jiabin12537fc2023-10-12 17:56:08 +00008759 audio_port_v7 mixPort;
8760 profile->toAudioPort(&mixPort);
8761 mixPort.ext.mix.handle = ioHandle;
8762
8763 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8764 if (status != NO_ERROR) {
8765 ALOGE("%s failed to query the attributes of the mix port", __func__);
8766 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008767 }
jiabin12537fc2023-10-12 17:56:08 +00008768
8769 std::set<audio_format_t> supportedFormats;
8770 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8771 supportedFormats.insert(mixPort.audio_profiles[i].format);
8772 }
8773 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8774 mReportedFormatsMap[devDesc] = formats;
8775
8776 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8777 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8778 modifySurroundFormats(devDesc, &formats);
8779 size_t modifiedNumProfiles = 0;
8780 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8781 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8782 formats.end()) {
8783 // Skip the format that is not present after modifying surround formats.
8784 continue;
8785 }
8786 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8787 sizeof(struct audio_profile));
8788 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8789 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8790 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8791 modifySurroundChannelMasks(&channels);
8792 std::copy(channels.begin(), channels.end(),
8793 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8794 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8795 }
8796 mixPort.num_audio_profiles = modifiedNumProfiles;
8797 }
8798 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008799}
Eric Laurentd60560a2015-04-10 11:31:20 -07008800
Mikhail Naganovdc769682018-05-04 15:34:08 -07008801status_t AudioPolicyManager::installPatch(const char *caller,
8802 audio_patch_handle_t *patchHandle,
8803 AudioIODescriptorInterface *ioDescriptor,
8804 const struct audio_patch *patch,
8805 int delayMs)
8806{
8807 ssize_t index = mAudioPatches.indexOfKey(
8808 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8809 *patchHandle : ioDescriptor->getPatchHandle());
8810 sp<AudioPatch> patchDesc;
8811 status_t status = installPatch(
8812 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8813 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008814 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008815 }
8816 return status;
8817}
8818
8819status_t AudioPolicyManager::installPatch(const char *caller,
8820 ssize_t index,
8821 audio_patch_handle_t *patchHandle,
8822 const struct audio_patch *patch,
8823 int delayMs,
8824 uid_t uid,
8825 sp<AudioPatch> *patchDescPtr)
8826{
8827 sp<AudioPatch> patchDesc;
8828 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8829 if (index >= 0) {
8830 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008831 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008832 }
8833
8834 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8835 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8836 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8837 if (status == NO_ERROR) {
8838 if (index < 0) {
8839 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008840 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008841 } else {
8842 patchDesc->mPatch = *patch;
8843 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008844 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008845 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008846 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008847 }
8848 nextAudioPortGeneration();
8849 mpClientInterface->onAudioPatchListUpdate();
8850 }
8851 if (patchDescPtr) *patchDescPtr = patchDesc;
8852 return status;
8853}
8854
jiabinbce0c1d2020-10-05 11:20:18 -07008855bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8856{
8857 const TrackClientVector activeClients = output->getActiveClients();
8858 if (activeClients.empty()) {
8859 return true;
8860 }
8861 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8862 if (index < 0) {
8863 ALOGE("%s, no audio patch found while there are active clients on output %d",
8864 __func__, output->getId());
8865 return false;
8866 }
8867 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8868 DeviceVector routedDevices;
8869 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8870 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8871 patchDesc->mPatch.sinks[i].id);
8872 if (device == nullptr) {
8873 ALOGE("%s, no audio device found with id(%d)",
8874 __func__, patchDesc->mPatch.sinks[i].id);
8875 return false;
8876 }
8877 routedDevices.add(device);
8878 }
8879 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008880 if (client->isInvalid()) {
8881 // No need to take care about invalidated clients.
8882 continue;
8883 }
jiabinbce0c1d2020-10-05 11:20:18 -07008884 sp<DeviceDescriptor> preferredDevice =
8885 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8886 if (mEngine->getOutputDevicesForAttributes(
8887 client->attributes(), preferredDevice, false) == routedDevices) {
8888 return false;
8889 }
8890 }
8891 return true;
8892}
8893
8894sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008895 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008896 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8897 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008898{
8899 for (const auto& device : devices) {
8900 // TODO: This should be checking if the profile supports the device combo.
8901 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008902 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8903 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008904 return nullptr;
8905 }
8906 }
8907 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8908 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008909 status_t status = desc->open(halConfig, mixerConfig, devices,
8910 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008911 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008912 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008913 return nullptr;
8914 }
jiabin14b50cc2023-12-13 19:01:52 +00008915 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8916 auto portConfig = desc->getConfig();
8917 for (const auto& device : devices) {
8918 device->setPreferredConfig(&portConfig);
8919 }
8920 }
jiabinbce0c1d2020-10-05 11:20:18 -07008921
8922 // Here is where the out_set_parameters() for card & device gets called
8923 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8924 const audio_devices_t deviceType = device->type();
8925 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008926 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008927 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8928 mpClientInterface->setParameters(output, String8(param));
8929 free(param);
8930 }
jiabin12537fc2023-10-12 17:56:08 +00008931 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008932 if (!profile->hasValidAudioProfile()) {
8933 ALOGW("%s() missing param", __func__);
8934 desc->close();
8935 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008936 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8937 // Reopen the output with the best audio profile picked by APM when the profile supports
8938 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008939 desc->close();
8940 output = AUDIO_IO_HANDLE_NONE;
8941 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8942 profile->pickAudioProfile(
8943 config.sample_rate, config.channel_mask, config.format);
8944 config.offload_info.sample_rate = config.sample_rate;
8945 config.offload_info.channel_mask = config.channel_mask;
8946 config.offload_info.format = config.format;
8947
jiabina84c3d32022-12-02 18:59:55 +00008948 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008949 if (status != NO_ERROR) {
8950 return nullptr;
8951 }
8952 }
8953
8954 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008955 setOutputDevices(__func__, desc,
8956 devices,
8957 true,
8958 0,
8959 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008960 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8961 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8962
jiabinbce0c1d2020-10-05 11:20:18 -07008963 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8964 sp<AudioPolicyMix> policyMix;
8965 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8966 policyMix->setOutput(desc);
8967 desc->mPolicyMix = policyMix;
8968 } else {
8969 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008970 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008971 }
8972
baek.kim -61c20122022-07-27 10:05:32 +00008973 } else if (hasPrimaryOutput() && speaker != nullptr
8974 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008975 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8976 // no duplicated output for:
8977 // - direct outputs
8978 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008979 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008980 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8981
8982 //TODO: configure audio effect output stage here
8983
8984 // open a duplicating output thread for the new output and the primary output
8985 sp<SwAudioOutputDescriptor> dupOutputDesc =
8986 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8987 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8988 if (status == NO_ERROR) {
8989 // add duplicated output descriptor
8990 addOutput(duplicatedOutput, dupOutputDesc);
8991 } else {
8992 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8993 mPrimaryOutput->mIoHandle, output);
8994 desc->close();
8995 removeOutput(output);
8996 nextAudioPortGeneration();
8997 return nullptr;
8998 }
8999 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009000 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9001 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9002 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009003 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009004 }
jiabinbce0c1d2020-10-05 11:20:18 -07009005 return desc;
9006}
9007
jiabinf1c73972022-04-14 16:28:52 -07009008status_t AudioPolicyManager::getDevicesForAttributes(
9009 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
9010 // Devices are determined in the following precedence:
9011 //
9012 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9013 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9014 //
9015 // If no such dynamic policy then
9016 // 2) Devices containing an active client using setPreferredDevice
9017 // with same strategy as the attributes.
9018 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9019 //
9020 // If no corresponding active client with setPreferredDevice then
9021 // 3) Devices associated with the strategy determined by the attributes
9022 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9023 //
9024 // See related getOutputForAttrInt().
9025
9026 // check dynamic policies but only for primary descriptors (secondary not used for audible
9027 // audio routing, only used for duplication for playback capture)
9028 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009029 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009030 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009031 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9032 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9033 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009034 if (status != OK) {
9035 return status;
9036 }
9037
9038 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9039 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9040 // as they are unaffected by device/stream volume
9041 // (per SwAudioOutputDescriptor::isFixedVolume()).
9042 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9043 ) {
9044 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9045 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9046 devices.add(deviceDesc);
9047 } else {
9048 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9049 // which selects setPreferredDevice if active. This means forVolume call
9050 // will take an active setPreferredDevice, if such exists.
9051
9052 devices = mEngine->getOutputDevicesForAttributes(
9053 attr, nullptr /* preferredDevice */, false /* fromCache */);
9054 }
9055
9056 if (forVolume) {
9057 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9058 // for single volume control in AudioService (such relationship should exist if
9059 // SPEAKER_SAFE is present).
9060 //
9061 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9062 DeviceVector speakerSafeDevices =
9063 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9064 if (!speakerSafeDevices.isEmpty()) {
9065 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9066 devices.remove(speakerSafeDevices);
9067 }
9068 }
9069
9070 return NO_ERROR;
9071}
9072
9073status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9074 AudioProfileVector& audioProfiles,
9075 uint32_t flags,
9076 bool isInput) {
9077 for (const auto& hwModule : mHwModules) {
9078 // the MSD module checks for different conditions
9079 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9080 continue;
9081 }
9082 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9083 : hwModule->getOutputProfiles();
9084 for (const auto& profile : ioProfiles) {
9085 if (!profile->areAllDevicesSupported(devices) ||
9086 !profile->isCompatibleProfileForFlags(
9087 flags, false /*exactMatchRequiredForInputFlags*/)) {
9088 continue;
9089 }
9090 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9091 }
9092 }
9093
9094 if (!isInput) {
9095 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9096 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9097 if (msdModule != nullptr) {
9098 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9099 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9100 for (const auto &profile: msdModule->getOutputProfiles()) {
9101 if (!profile->asAudioPort()->isDirectOutput()) {
9102 continue;
9103 }
9104 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9105 }
9106 } else {
9107 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9108 }
9109 }
9110 }
9111
9112 return NO_ERROR;
9113}
9114
jiabin3ff8d7d2022-12-13 06:27:44 +00009115sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9116 const audio_config_t *config,
9117 audio_output_flags_t flags,
9118 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009119 closeOutput(outputDesc->mIoHandle);
9120 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9121 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9122 if (preferredOutput == nullptr) {
9123 ALOGE("%s failed to reopen output device=%d, caller=%s",
9124 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009125 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009126 return preferredOutput;
9127}
9128
9129void AudioPolicyManager::reopenOutputsWithDevices(
9130 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9131 for (const auto& [output, devices] : outputsToReopen) {
9132 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9133 closeOutput(output);
9134 openOutputWithProfileAndDevice(desc->mProfile, devices);
9135 }
jiabina84c3d32022-12-02 18:59:55 +00009136}
9137
jiabinc44b3462022-12-08 12:52:31 -08009138PortHandleVector AudioPolicyManager::getClientsForStream(
9139 audio_stream_type_t streamType) const {
9140 PortHandleVector clients;
9141 for (size_t i = 0; i < mOutputs.size(); ++i) {
9142 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9143 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9144 }
9145 return clients;
9146}
9147
9148void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9149 PortHandleVector clients;
9150 for (auto stream : streams) {
9151 PortHandleVector clientsForStream = getClientsForStream(stream);
9152 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9153 }
9154 mpClientInterface->invalidateTracks(clients);
9155}
9156
jiabin220eea12024-05-17 17:55:20 +00009157void AudioPolicyManager::updateClientsInternalMute(
9158 const sp<android::SwAudioOutputDescriptor> &desc) {
9159 if (!desc->isBitPerfect() ||
9160 !com::android::media::audioserver::
9161 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9162 // This is only used for bit perfect output now.
9163 return;
9164 }
9165 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9166 bool bitPerfectClientInternalMute = false;
9167 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9168 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9169 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9170 bitPerfectClient = client;
9171 continue;
9172 }
9173 bool muted = false;
9174 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9175 // System sound is muted.
9176 muted = true;
9177 } else {
9178 bitPerfectClientInternalMute = true;
9179 }
9180 if (client->setInternalMute(muted)) {
9181 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9182 if (!result.ok()) {
9183 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9184 continue;
9185 }
9186 media::TrackInternalMuteInfo info;
9187 info.portId = result.value();
9188 info.muted = client->getInternalMute();
9189 clientsInternalMute.push_back(std::move(info));
9190 }
9191 }
9192 if (bitPerfectClient != nullptr &&
9193 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9194 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9195 if (result.ok()) {
9196 media::TrackInternalMuteInfo info;
9197 info.portId = result.value();
9198 info.muted = bitPerfectClient->getInternalMute();
9199 clientsInternalMute.push_back(std::move(info));
9200 } else {
9201 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9202 __func__, bitPerfectClient->portId());
9203 }
9204 }
9205 if (!clientsInternalMute.empty()) {
9206 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9207 status != NO_ERROR) {
9208 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9209 }
9210 }
9211}
9212
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009213} // namespace android