blob: d7d5e402a865104d62b687091eedf89926ce0016 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Eric Laurentb2fb4102024-06-21 12:25:26 +000069using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000070using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070071
Eric Laurentdc462862016-07-19 12:29:53 -070072//FIXME: workaround for truncated touch sounds
73// to be removed when the problem is handled by system UI
74#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070075
76// Largest difference in dB on earpiece in call between the voice volume and another
77// media / notification / system volume.
78constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
79
jiabin06e4bab2019-07-29 10:13:34 -070080template <typename T>
81bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
82{
83 if (left.size() != right.size()) {
84 return false;
85 }
86 for (size_t index = 0; index < right.size(); index++) {
87 if (left[index] != right[index]) {
88 return false;
89 }
90 }
91 return true;
92}
93
94template <typename T>
95bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
96{
97 return !(left == right);
98}
99
Eric Laurente552edb2014-03-10 17:42:56 -0700100// ----------------------------------------------------------------------------
101// AudioPolicyInterface implementation
102// ----------------------------------------------------------------------------
103
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100104status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
105 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
106 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800107 nextAudioPortGeneration();
108 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800109}
110
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100111status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
112 audio_policy_dev_state_t state,
113 const char* device_address,
114 const char* device_name,
115 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800116 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100117 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
118 status == OK) {
119 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
120 } else {
121 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
122 return status;
123 }
124}
125
François Gaffie11d30102018-11-02 16:09:09 +0100126void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000127 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200128{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000129 audio_port_v7 devicePort;
130 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000131 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000132 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700133 ALOGE("Error %d while setting connected state %d for device %s",
134 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000135 device->getDeviceTypeAddr().toString(false).c_str());
136 }
François Gaffie44481e72016-04-20 07:49:57 +0200137}
138
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100139status_t AudioPolicyManager::setDeviceConnectionStateInt(
140 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
141 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100142 if (port.ext.getTag() != AudioPortExt::device) {
143 return BAD_VALUE;
144 }
145 audio_devices_t device_type;
146 std::string device_address;
147 if (status_t status = aidl2legacy_AudioDevice_audio_device(
148 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
149 status != OK) {
150 return status;
151 };
152 const char* device_name = port.name.c_str();
153 // connect/disconnect only 1 device at a time
154 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
155 return BAD_VALUE;
156
157 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
158 device_type, device_address.c_str(), device_name, encodedFormat,
159 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000160 if (device == nullptr) {
161 return INVALID_OPERATION;
162 }
163 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
164 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
165 }
166 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167}
168
François Gaffie11d30102018-11-02 16:09:09 +0100169status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800170 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100171 const char* device_address,
172 const char* device_name,
173 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800174 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100175 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
176 status == OK) {
177 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
178 } else {
179 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
180 return status;
181 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182}
Paul McLeane743a472015-01-28 11:07:31 -0800183
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700184status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
185 audio_policy_dev_state_t state)
186{
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700188 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700189 SortedVector <audio_io_handle_t> outputs;
190
François Gaffie11d30102018-11-02 16:09:09 +0100191 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192
Eric Laurente552edb2014-03-10 17:42:56 -0700193 // save a copy of the opened output descriptors before any output is opened or closed
194 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
195 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100196
197 bool wasLeUnicastActive = isLeUnicastActive();
198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 switch (state)
200 {
201 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800202 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100204 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700205 return INVALID_OPERATION;
206 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800207 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700208 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700209
Eric Laurente552edb2014-03-10 17:42:56 -0700210 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200211 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700212 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700213 }
214
François Gaffie44481e72016-04-20 07:49:57 +0200215 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
216 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000217 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200218
François Gaffie11d30102018-11-02 16:09:09 +0100219 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
220 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200221
jiabinc0048632023-04-27 22:04:31 +0000222 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700223
224 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 return INVALID_OPERATION;
226 }
François Gaffie2110e042015-03-24 08:41:51 +0100227
jiabin1c4794b2020-05-05 10:08:05 -0700228 // Populate encapsulation information when a output device is connected.
229 device->setEncapsulationInfoFromHal(mpClientInterface);
230
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700231 // outputs should never be empty here
232 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
233 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700237 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700238 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700239 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100240 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700241 return INVALID_OPERATION;
242 }
243
François Gaffie11d30102018-11-02 16:09:09 +0100244 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700245
jiabinc0048632023-04-27 22:04:31 +0000246 // Notify the HAL to prepare to disconnect device
247 broadcastDeviceConnectionState(
248 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700249
Eric Laurente552edb2014-03-10 17:42:56 -0700250 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100251 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700252
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100253 mOutputs.clearSessionRoutesForDevice(device);
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100256
jiabinc0048632023-04-27 22:04:31 +0000257 // Send Disconnect to HALs
258 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
259
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800260 // Reset active device codec
261 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
262
Kriti Dangef6be8f2020-11-05 11:58:19 +0100263 // remove device from mReportedFormatsMap cache
264 mReportedFormatsMap.erase(device);
265
jiabina84c3d32022-12-02 18:59:55 +0000266 // remove preferred mixer configurations
267 mPreferredMixerAttrInfos.erase(device->getId());
268
Eric Laurente552edb2014-03-10 17:42:56 -0700269 } break;
270
271 default:
François Gaffie11d30102018-11-02 16:09:09 +0100272 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700273 return BAD_VALUE;
274 }
275
Eric Laurent736a1022019-03-27 18:28:46 -0700276 // Propagate device availability to Engine
277 setEngineDeviceConnectionState(device, state);
278
Eric Laurentae970022019-01-29 14:25:04 -0800279 // No need to evaluate playback routing when connecting a remote submix
280 // output device used by a dynamic policy of type recorder as no
281 // playback use case is affected.
282 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700283 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800284 for (audio_io_handle_t output : outputs) {
285 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800286 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
287 if (policyMix != nullptr
288 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000289 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800290 doCheckForDeviceAndOutputChanges = false;
291 break;
292 }
293 }
294 }
295
296 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // outputs must be closed after checkOutputForAllStrategies() is executed
298 if (!outputs.isEmpty()) {
299 for (audio_io_handle_t output : outputs) {
300 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100301 // close unused outputs after device disconnection or direct outputs that have
302 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200303 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200304 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
305 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200306 (desc->mDirectOpenCount == 0))
307 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
308 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200309 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 closeOutput(output);
311 }
Eric Laurente552edb2014-03-10 17:42:56 -0700312 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700313 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
314 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700315 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700316 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800317 };
318
319 if (doCheckForDeviceAndOutputChanges) {
320 checkForDeviceAndOutputChanges(checkCloseOutputs);
321 } else {
322 checkCloseOutputs();
323 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100324 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100325 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700326 const DeviceVector activeMediaDevices =
327 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000328 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700329 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700330 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530331 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
332 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100333 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 // do not force device change on duplicated output because if device is 0, it will
335 // also force a device 0 for the two outputs it is duplicated to which may override
336 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100337 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100338 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700339 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700340 // always force when disconnecting (a non-duplicated device)
341 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000342 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000343 // If the device is using preferred mixer attributes, the output need to reopen
344 // with default configuration when the new selected devices are different from
345 // current routing devices
346 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
347 continue;
348 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530349 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700350 }
jiabinbce0c1d2020-10-05 11:20:18 -0700351 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000352 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700353 desc->supportsDevicesForPlayback(activeMediaDevices)) {
354 // Reopen the output to query the dynamic profiles when there is not active
355 // clients or all active clients will be rerouted. Otherwise, set the flag
356 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
357 // can be reopened to query dynamic profiles when all clients are inactive.
358 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000359 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700360 } else {
361 desc->mPendingReopenToQueryProfiles = true;
362 }
363 }
364 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
365 // Clear the flag that previously set for re-querying profiles.
366 desc->mPendingReopenToQueryProfiles = false;
367 }
368 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000369 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700370
Eric Laurentd60560a2015-04-10 11:31:20 -0700371 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100372 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700373 }
374
Eric Laurent96d1dda2022-03-14 17:14:19 +0100375 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
376
Eric Laurent72aa32f2014-05-30 18:51:48 -0700377 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530378 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700379 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700380 } // end if is output device
381
Eric Laurente552edb2014-03-10 17:42:56 -0700382 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700383 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100384 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700385 switch (state)
386 {
387 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700388 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700389 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100390 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700391 return INVALID_OPERATION;
392 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700393
Jaideep Sharma33173202024-06-18 17:46:45 +0530394 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
395
Eric Laurent0dd51852019-04-19 18:18:58 -0700396 if (mAvailableInputDevices.add(device) < 0) {
397 return NO_MEMORY;
398 }
399
François Gaffie44481e72016-04-20 07:49:57 +0200400 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
401 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000402 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700403 // Propagate device availability to Engine
404 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200405
Eric Laurent0dd51852019-04-19 18:18:58 -0700406 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700407 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
408
Eric Laurent0dd51852019-04-19 18:18:58 -0700409 mAvailableInputDevices.remove(device);
410
jiabinc0048632023-04-27 22:04:31 +0000411 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100412
413 mHwModules.cleanUpForDevice(device);
414
Eric Laurentd4692962014-05-05 18:13:44 -0700415 return INVALID_OPERATION;
416 }
417
Eric Laurentd4692962014-05-05 18:13:44 -0700418 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700419
420 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700421 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700422 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100423 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700424 return INVALID_OPERATION;
425 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700426
François Gaffie11d30102018-11-02 16:09:09 +0100427 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700428
jiabinc0048632023-04-27 22:04:31 +0000429 // Notify the HAL to prepare to disconnect device
430 broadcastDeviceConnectionState(
431 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700432
François Gaffie11d30102018-11-02 16:09:09 +0100433 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700434
435 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100436
jiabinc0048632023-04-27 22:04:31 +0000437 // Set Disconnect to HALs
438 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
439
Kriti Dangef6be8f2020-11-05 11:58:19 +0100440 // remove device from mReportedFormatsMap cache
441 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700442
443 // Propagate device availability to Engine
444 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700445 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700446
447 default:
François Gaffie11d30102018-11-02 16:09:09 +0100448 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700449 return BAD_VALUE;
450 }
451
Eric Laurent0dd51852019-04-19 18:18:58 -0700452 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700453 // As the input device list can impact the output device selection, update
454 // getDeviceForStrategy() cache
455 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700456
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100457 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200458 // Reconnect Audio Source
459 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
460 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
461 checkAudioSourceForAttributes(attributes);
462 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700463 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100464 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700465 }
466
Eric Laurentb52c1522014-05-20 11:27:36 -0700467 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530468 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700469 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700470 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700471
François Gaffie11d30102018-11-02 16:09:09 +0100472 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700473 return BAD_VALUE;
474}
475
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100476status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
477 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800478 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700479 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
480 devDescr->setName(device_name);
481 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100482}
483
Eric Laurent736a1022019-03-27 18:28:46 -0700484void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
485 audio_policy_dev_state_t state) {
486
487 // the Engine does not have to know about remote submix devices used by dynamic audio policies
488 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
489 return;
490 }
491 mEngine->setDeviceConnectionState(device, state);
492}
493
494
Eric Laurente0720872014-03-11 09:30:41 -0700495audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100496 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700497{
Eric Laurent634b7142016-04-20 13:48:02 -0700498 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800499 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
500 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700501 (strlen(device_address) != 0)/*matchAddress*/);
502
503 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100504 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700505 device, device_address);
506 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
507 }
François Gaffie53615e22015-03-19 09:24:12 +0100508
Eric Laurent3a4311c2014-03-17 12:00:47 -0700509 DeviceVector *deviceVector;
510
Eric Laurente552edb2014-03-10 17:42:56 -0700511 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700512 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700513 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700514 deviceVector = &mAvailableInputDevices;
515 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100516 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700517 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700518 }
Eric Laurent634b7142016-04-20 13:48:02 -0700519
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800520 return (deviceVector->getDevice(
521 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700522 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800523}
524
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
526 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 const char *device_name,
528 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800529{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800530 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
531 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800533 // connect/disconnect only 1 device at a time
534 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
535
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800536 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700537 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800539 // Nothing to do: device is not connected
540 return NO_ERROR;
541 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800543
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700544 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800545 // configure codecs.
546 // Handle two specific cases by sending a set parameter to
547 // configure A2DP codecs. No need to toggle device state.
548 // Case 1: A2DP active device switches from primary to primary
549 // module
550 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100551 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700552 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800553 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
554 if (availablePrimaryOutputDevices().contains(devDesc) &&
555 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100556 bool isA2dp = audio_is_a2dp_out_device(device);
557 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
558 : String8(AudioParameter::keyReconfigLeSupported);
559 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800560 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100561 int isReconfigSupported;
562 repliedParameters.getInt(supportKey, isReconfigSupported);
563 if (isReconfigSupported) {
564 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
565 : String8(AudioParameter::keyReconfigLe);
566 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800567 param.add(key, String8("true"));
568 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
569 devDesc->setEncodedFormat(encodedFormat);
570 return NO_ERROR;
571 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700572 }
573 }
cnx421bd2dcc42020-07-11 14:58:44 +0800574 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000575 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800576 for (size_t i = 0; i < mOutputs.size(); i++) {
577 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000578 // mute media strategies to avoid sending the music tail into
579 // the earpiece or headset.
580 if (desc->isStrategyActive(musicStrategy)) {
581 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
582 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
583 tempRecommendedMuteDuration : desc->latency() * 4;
584 if (muteWaitMs < tempMuteDurationMs) {
585 muteWaitMs = tempMuteDurationMs;
586 }
587 }
cnx421bd2dcc42020-07-11 14:58:44 +0800588 setStrategyMute(musicStrategy, true, desc);
589 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
590 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
591 nullptr, true /*fromCache*/).types());
592 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000593 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
594 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
595 // happens after the actual device switch.
596 if (muteWaitMs > 0) {
597 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
598 usleep(muteWaitMs * 1000);
599 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800600 // Toggle the device state: UNAVAILABLE -> AVAILABLE
601 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100602 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800603 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800604 device_address, device_name,
605 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800606 if (status != NO_ERROR) {
607 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
608 status);
609 return status;
610 }
611
612 status = setDeviceConnectionState(device,
613 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800614 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800615 if (status != NO_ERROR) {
616 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
617 status);
618 return status;
619 }
620
621 return NO_ERROR;
622}
623
Pattydd807582021-11-04 21:01:03 +0800624status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
625 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800626{
Pattydd807582021-11-04 21:01:03 +0800627 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 std::unordered_set<audio_format_t> formatSet;
630 sp<HwModule> primaryModule =
631 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700632 if (primaryModule == nullptr) {
633 ALOGE("%s() unable to get primary module", __func__);
634 return NO_INIT;
635 }
Pattydd807582021-11-04 21:01:03 +0800636
637 DeviceTypeSet audioDeviceSet;
638
639 switch(device) {
640 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
641 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
642 break;
643 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800644 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
645 break;
646 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
647 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800648 break;
649 default:
650 ALOGE("%s() device type 0x%08x not supported", __func__, device);
651 return BAD_VALUE;
652 }
653
jiabin9a3361e2019-10-01 09:38:30 -0700654 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800655 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800656 for (const auto& device : declaredDevices) {
657 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800658 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800659 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800660 return status;
661}
662
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100663DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
664{
665 DeviceVector rxSinkdevices{};
666 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
667 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
668 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
669 auto rxSinkDevice = rxSinkdevices.itemAt(0);
670 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
671 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
672 // retrieve Rx Source device descriptor
673 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
674 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
675
676 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
677 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
678 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
679 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
680 return DeviceVector(rxSinkDevice);
681 }
682 }
683 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
684 // the device returned is not necessarily reachable via this output
685 // (filter later by setOutputDevices())
686 return getNewOutputDevices(mPrimaryOutput, fromCache);
687}
688
689status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
690{
François Gaffiedb1755b2023-09-01 11:50:35 +0200691 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100692 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
693 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
694 }
695 return INVALID_OPERATION;
696}
697
698status_t AudioPolicyManager::updateCallRoutingInternal(
699 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700700{
701 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100702 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700703 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200704 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700705 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100706 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700707 }
François Gaffie11d30102018-11-02 16:09:09 +0100708
Francois Gaffie716e1432019-01-14 16:58:59 +0100709 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100710 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200711
Eric Laurentb2fb4102024-06-21 12:25:26 +0000712 if (!fix_call_audio_patch()) {
713 disconnectTelephonyAudioSource(mCallRxSourceClient);
714 disconnectTelephonyAudioSource(mCallTxSourceClient);
715 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200716
717 if (rxDevices.isEmpty()) {
718 ALOGW("%s() no selected output device", __func__);
719 return INVALID_OPERATION;
720 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000721 if (txSourceDevice == nullptr) {
722 ALOGE("%s() selected input device not available", __func__);
723 return INVALID_OPERATION;
724 }
François Gaffiec005e562018-11-06 15:04:49 +0100725
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100726 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100727 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728
François Gaffie9eb18552018-11-05 10:33:26 +0100729 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700730 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100731 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700732 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100733 // retrieve Rx Source and Tx Sink device descriptors
734 sp<DeviceDescriptor> rxSourceDevice =
735 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
736 String8(),
737 AUDIO_FORMAT_DEFAULT);
738 sp<DeviceDescriptor> txSinkDevice =
739 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
740 String8(),
741 AUDIO_FORMAT_DEFAULT);
742
743 // RX and TX Telephony device are declared by Primary Audio HAL
744 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
745 (telephonyRxModule->getHalVersionMajor() >= 3)) {
746 if (rxSourceDevice == 0 || txSinkDevice == 0) {
747 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100748 ALOGE("%s() no telephony Tx and/or RX device", __func__);
749 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100750 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100751 // createAudioPatchInternal now supports both HW / SW bridging
752 createRxPatch = true;
753 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100754 } else {
755 // If the RX device is on the primary HW module, then use legacy routing method for
756 // voice calls via setOutputDevice() on primary output.
757 // Otherwise, create two audio patches for TX and RX path.
758 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
759 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700760 // If the TX device is also on the primary HW module, setOutputDevice() will take care
761 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100762 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
763 (txSinkDevice != 0);
764 }
765 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
766 // Otherwise, create two audio patches for TX and RX path.
767 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000768 if (fix_call_audio_patch()) {
769 disconnectTelephonyAudioSource(mCallRxSourceClient);
770 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200771 if (!hasPrimaryOutput()) {
772 ALOGW("%s() no primary output available", __func__);
773 return INVALID_OPERATION;
774 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530775 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700776 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000777 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800778 // If the TX device is on the primary HW module but RX device is
779 // on other HW module, SinkMetaData of telephony input should handle it
780 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700781 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700782 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100783 // terminate active capture if on the same HW module as the call TX source device
784 // FIXME: would be better to refine to only inputs whose profile connects to the
785 // call TX device but this information is not in the audio patch and logic here must be
786 // symmetric to the one in startInput()
787 for (const auto& activeDesc : mInputs.getActiveInputs()) {
788 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
789 closeActiveClients(activeDesc);
790 }
791 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200792 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000793 } else if (fix_call_audio_patch()) {
794 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800795 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100796 if (waitMs != nullptr) {
797 *waitMs = muteWaitMs;
798 }
799 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800800}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700801
Mikhail Naganov100f0122018-11-29 11:22:16 -0800802bool AudioPolicyManager::isDeviceOfModule(
803 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
804 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
805 if (module != 0) {
806 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
807 .indexOf(devDesc) != NAME_NOT_FOUND
808 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
809 .indexOf(devDesc) != NAME_NOT_FOUND;
810 }
811 return false;
812}
813
David Lif85c5e32024-07-01 13:14:10 +0000814void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200815{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000816 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
817
818 if (fix_call_audio_patch()) {
819 if (mCallRxSourceClient != nullptr) {
820 DeviceVector rxDevices =
821 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
822 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
823 "connectTelephonyRxAudioSource(): no device found for call RX source");
824 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
825 if (mCallRxSourceClient->isConnected()
826 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
827 return;
828 }
829 disconnectTelephonyAudioSource(mCallRxSourceClient);
830 }
831 } else {
832 disconnectTelephonyAudioSource(mCallRxSourceClient);
833 }
834
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200835 const struct audio_port_config source = {
836 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
837 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
838 };
Eric Laurent541a2002024-01-15 18:11:42 +0100839 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000840
Eric Laurentccbd7872024-06-20 12:34:15 +0000841 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000842 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100843 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
844 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000845 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
846 mCallRxSourceClient->srcDevice()->toString().c_str(),
847 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200848 ALOGE_IF(mCallRxSourceClient == nullptr,
849 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200850}
851
Francois Gaffie601801d2021-06-22 13:27:39 +0200852void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200853{
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 if (clientDesc == nullptr) {
855 return;
856 }
857 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
858 "%s error stopping audio source", __func__);
859 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200860}
861
862void AudioPolicyManager::connectTelephonyTxAudioSource(
863 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
864 uint32_t delayMs)
865{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200866 if (srcDevice == nullptr || sinkDevice == nullptr) {
867 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
868 return;
869 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000870
871 if (fix_call_audio_patch()) {
872 if (mCallTxSourceClient != nullptr) {
873 if (mCallTxSourceClient->isConnected()
874 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
875 return;
876 }
877 disconnectTelephonyAudioSource(mCallTxSourceClient);
878 }
879 } else {
880 disconnectTelephonyAudioSource(mCallTxSourceClient);
881 }
882
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200883 PatchBuilder patchBuilder;
884 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000885
Francois Gaffie601801d2021-06-22 13:27:39 +0200886 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200887 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
888
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200889 struct audio_port_config source = {};
890 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100891 mCallTxSourceClient = new SourceClientDescriptor(
892 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000893 mCommunnicationStrategy, toVolumeSource(aa), true,
894 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100895 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
896
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200897 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
898 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200899 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
900 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200901 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000902 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
903 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200904 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200905 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200906 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200907}
908
Eric Laurente0720872014-03-11 09:30:41 -0700909void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700910{
911 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100912 // store previous phone state for management of sonification strategy below
913 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100914 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100915
916 if (mEngine->setPhoneState(state) != NO_ERROR) {
917 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700918 return;
919 }
François Gaffie2110e042015-03-24 08:41:51 +0100920 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700921 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700922 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700923 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800924 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
926
François Gaffie2110e042015-03-24 08:41:51 +0100927 /**
928 * Switching to or from incall state or switching between telephony and VoIP lead to force
929 * routing command.
930 */
Eric Laurent74b71512019-11-06 17:21:57 -0800931 bool force = ((isStateInCall(oldState) != isStateInCall(state))
932 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700933
934 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700935 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700936
Eric Laurente552edb2014-03-10 17:42:56 -0700937 int delayMs = 0;
938 if (isStateInCall(state)) {
939 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100940 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
941 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700942 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700943 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700944 // mute media and sonification strategies and delay device switch by the largest
945 // latency of any output where either strategy is active.
946 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100947 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
948 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
949 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700950 (delayMs < (int)desc->latency()*2)) {
951 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700952 }
François Gaffiec005e562018-11-06 15:04:49 +0100953 setStrategyMute(musicStrategy, true, desc);
954 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
955 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
956 nullptr, true /*fromCache*/).types());
957 setStrategyMute(sonificationStrategy, true, desc);
958 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
959 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
960 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962 }
963
François Gaffiedb1755b2023-09-01 11:50:35 +0200964 if (state == AUDIO_MODE_IN_CALL) {
965 (void)updateCallRouting(false /*fromCache*/, delayMs);
966 } else {
967 if (oldState == AUDIO_MODE_IN_CALL) {
968 disconnectTelephonyAudioSource(mCallRxSourceClient);
969 disconnectTelephonyAudioSource(mCallTxSourceClient);
970 }
971 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100972 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
973 // force routing command to audio hardware when ending call
974 // even if no device change is needed
975 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
976 rxDevices = mPrimaryOutput->devices();
977 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530978 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700979 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700980 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700981
jiabin3ff8d7d2022-12-13 06:27:44 +0000982 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700983 // reevaluate routing on all outputs in case tracks have been started during the call
984 for (size_t i = 0; i < mOutputs.size(); i++) {
985 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100986 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000987 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
988 && desc->mPreferredAttrInfo != nullptr) {
989 // If the output is using preferred mixer attributes and the audio mode is not normal,
990 // the output need to reopen with default configuration.
991 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
992 continue;
993 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200994 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
995 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530996 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200997 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700998 }
999 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001000 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001001
Eric Laurent96d1dda2022-03-14 17:14:19 +01001002 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1003
Eric Laurente552edb2014-03-10 17:42:56 -07001004 if (isStateInCall(state)) {
1005 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001006 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001007 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001008 }
1009
1010 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001011 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1012 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001013}
1014
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001015audio_mode_t AudioPolicyManager::getPhoneState() {
1016 return mEngine->getPhoneState();
1017}
1018
Eric Laurente0720872014-03-11 09:30:41 -07001019void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001020 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001021{
François Gaffie2110e042015-03-24 08:41:51 +01001022 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001023 if (config == mEngine->getForceUse(usage)) {
1024 return;
1025 }
Eric Laurente552edb2014-03-10 17:42:56 -07001026
François Gaffie2110e042015-03-24 08:41:51 +01001027 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1028 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1029 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001030 }
François Gaffie2110e042015-03-24 08:41:51 +01001031 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1032 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1033 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001034
1035 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001036 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001037
Eric Laurent22fcda22019-05-17 16:28:47 -07001038 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1039 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001040 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001041 }
1042
Eric Laurentdc462862016-07-19 12:29:53 -07001043 //FIXME: workaround for truncated touch sounds
1044 // to be removed when the problem is handled by system UI
1045 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001046 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1047 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1048 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001049
1050 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001051 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001052}
1053
Eric Laurente0720872014-03-11 09:30:41 -07001054void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001055{
1056 ALOGV("setSystemProperty() property %s, value %s", property, value);
1057}
1058
Dorin Drimusecc9f422022-03-09 17:57:40 +01001059// Find an MSD output profile compatible with the parameters passed.
1060// When "directOnly" is set, restrict search to profiles for direct outputs.
1061sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1062 const DeviceVector& devices,
1063 uint32_t samplingRate,
1064 audio_format_t format,
1065 audio_channel_mask_t channelMask,
1066 audio_output_flags_t flags,
1067 bool directOnly)
1068{
1069 flags = getRelevantFlags(flags, directOnly);
1070
1071 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1072 if (msdModule != nullptr) {
1073 // for the msd module check if there are patches to the output devices
1074 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1075 HwModuleCollection modules;
1076 modules.add(msdModule);
1077 return searchCompatibleProfileHwModules(
1078 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1079 flags, directOnly);
1080 }
1081 }
1082 return nullptr;
1083}
1084
Michael Chana94fbb22018-04-24 14:31:19 +10001085// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1086// search to profiles for direct outputs.
1087sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001088 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001089 uint32_t samplingRate,
1090 audio_format_t format,
1091 audio_channel_mask_t channelMask,
1092 audio_output_flags_t flags,
1093 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001094{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001095 flags = getRelevantFlags(flags, directOnly);
1096
1097 return searchCompatibleProfileHwModules(
1098 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1099}
1100
1101audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1102 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001103 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001104 // only retain flags that will drive the direct output profile selection
1105 // if explicitly requested
1106 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001107 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001108 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1109 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001110 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001111 return flags;
1112}
Eric Laurent861a6282015-05-18 15:40:16 -07001113
Dorin Drimusecc9f422022-03-09 17:57:40 +01001114sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1115 const HwModuleCollection& hwModules,
1116 const DeviceVector& devices,
1117 uint32_t samplingRate,
1118 audio_format_t format,
1119 audio_channel_mask_t channelMask,
1120 audio_output_flags_t flags,
1121 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001122 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001123 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001124 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001125 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 samplingRate, NULL /*updatedSamplingRate*/,
1127 format, NULL /*updatedFormat*/,
1128 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001129 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001130 continue;
1131 }
1132 // reject profiles not corresponding to a device currently available
1133 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1134 continue;
1135 }
1136 // reject profiles if connected device does not support codec
1137 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1138 continue;
1139 }
1140 if (!directOnly) {
1141 return curProfile;
1142 }
1143
1144 // when searching for direct outputs, if several profiles are compatible, give priority
1145 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001146 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001147 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001148 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001149 }
1150 profile = curProfile;
1151 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1152 break;
1153 }
Eric Laurente552edb2014-03-10 17:42:56 -07001154 }
1155 }
Eric Laurent861a6282015-05-18 15:40:16 -07001156 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001157}
1158
Eric Laurentfa0f6742021-08-17 18:39:44 +02001159sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001160 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001161{
1162 for (const auto& hwModule : mHwModules) {
1163 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001164 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001165 continue;
1166 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001167 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001168 // reject profiles not corresponding to a device currently available
1169 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1170 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1171 continue;
1172 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001173 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1174 != devices.size()) {
1175 continue;
1176 }
1177 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001178 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1179 return curProfile;
1180 }
1181 }
1182 return nullptr;
1183}
1184
Eric Laurentf4e63452017-11-06 19:31:46 +00001185audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001186{
François Gaffiec005e562018-11-06 15:04:49 +01001187 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001188
1189 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1190 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1191 // format, flags, etc. This may result in some discrepancy for functions that utilize
1192 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1193 // and AudioSystem::getOutputSamplingRate().
1194
François Gaffie11d30102018-11-02 16:09:09 +01001195 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001196 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1197 if (stream == AUDIO_STREAM_MUSIC &&
1198 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1199 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1200 }
1201 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001202
François Gaffie11d30102018-11-02 16:09:09 +01001203 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1204 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001205 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001206}
1207
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001208status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1209 const audio_attributes_t *srcAttr,
1210 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001211{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001212 if (srcAttr != NULL) {
1213 if (!isValidAttributes(srcAttr)) {
1214 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1215 __func__,
1216 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1217 srcAttr->tags);
1218 return BAD_VALUE;
1219 }
1220 *dstAttr = *srcAttr;
1221 } else {
1222 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1223 ALOGE("%s: invalid stream type", __func__);
1224 return BAD_VALUE;
1225 }
François Gaffiec005e562018-11-06 15:04:49 +01001226 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001227 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001228
1229 // Only honor audibility enforced when required. The client will be
1230 // forced to reconnect if the forced usage changes.
1231 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001232 dstAttr->flags = static_cast<audio_flags_mask_t>(
1233 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001234 }
1235
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001236 return NO_ERROR;
1237}
1238
Kevin Rocard153f92d2018-12-18 18:33:28 -08001239status_t AudioPolicyManager::getOutputForAttrInt(
1240 audio_attributes_t *resultAttr,
1241 audio_io_handle_t *output,
1242 audio_session_t session,
1243 const audio_attributes_t *attr,
1244 audio_stream_type_t *stream,
1245 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001246 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001247 audio_output_flags_t *flags,
1248 audio_port_handle_t *selectedDeviceId,
1249 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001251 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001252 bool *isSpatialized,
1253 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001254{
François Gaffiec005e562018-11-06 15:04:49 +01001255 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001256 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001257 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001258 const sp<DeviceDescriptor> requestedDevice =
1259 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1260
Eric Laurent8a1095a2019-11-08 14:44:16 -08001261 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001262 *isSpatialized = false;
1263
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001264 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1265 if (status != NO_ERROR) {
1266 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001267 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001268 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001269 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001270 }
François Gaffiec005e562018-11-06 15:04:49 +01001271 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001272
François Gaffiec005e562018-11-06 15:04:49 +01001273 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1274 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001275
Oscar Azucena873d10f2023-01-12 18:34:42 -08001276 bool usePrimaryOutputFromPolicyMixes = false;
1277
Kevin Rocard153f92d2018-12-18 18:33:28 -08001278 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1279 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1280 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001281 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001282 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1283 .channel_mask = config->channel_mask,
1284 .format = config->format,
1285 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001286 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001287 mAvailableOutputDevices, requestedDevice, primaryMix,
1288 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001289 if (status != OK) {
1290 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001291 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001292
Kevin Rocard153f92d2018-12-18 18:33:28 -08001293 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001294 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001295 && (!audio_is_linear_pcm(config->format) ||
1296 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001297 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001298 return BAD_VALUE;
1299 }
1300 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001301 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001302 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1303 primaryMix->mDeviceAddress,
1304 AUDIO_FORMAT_DEFAULT);
1305 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001306 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001307 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1308 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001309 // if a direct output can be opened to deliver the track's multi-channel content to the
1310 // output rather than being downmixed by the primary output, then use this direct
1311 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1312 // mix.
1313 bool tryDirectForChannelMask = policyDesc != nullptr
1314 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1315 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001316 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001317 audio_io_handle_t newOutput;
1318 status = openDirectOutput(
1319 *stream, session, config,
1320 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001321 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001322 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001323 policyDesc = mOutputs.valueFor(newOutput);
1324 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001325 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001326 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001327 policyDesc = nullptr;
1328 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001329 }
1330 if (policyDesc != nullptr) {
1331 policyDesc->mPolicyMix = primaryMix;
1332 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001333 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1334 : AUDIO_PORT_HANDLE_NONE;
1335 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1336 // Remove direct flag as it is not on a direct output.
1337 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1338 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001339
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001340 ALOGV("getOutputForAttr() returns output %d", *output);
1341 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1342 *outputType = API_OUT_MIX_PLAYBACK;
1343 } else {
1344 *outputType = API_OUTPUT_LEGACY;
1345 }
1346 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001347 } else {
1348 if (policyMixDevice != nullptr) {
1349 ALOGE("%s, try to use primary mix but no output found", __func__);
1350 return INVALID_OPERATION;
1351 }
1352 // Fallback to default engine selection as the selected primary mix device is not
1353 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001354 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001355 }
François Gaffiec005e562018-11-06 15:04:49 +01001356 // Virtual sources must always be dynamicaly or explicitly routed
1357 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1358 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1359 return BAD_VALUE;
1360 }
1361 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1362 // in order to let the choice of the order to future vendor engine
1363 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001364
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001365 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001366 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001367 }
1368
Nadav Barb2f18162018-07-18 13:01:53 +03001369 // Set incall music only if device was explicitly set, and fallback to the device which is
1370 // chosen by the engine if not.
1371 // FIXME: provide a more generic approach which is not device specific and move this back
1372 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001373 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001374 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001375 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001376 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001377 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001378 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001379 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001380 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001381 }
1382 }
1383
François Gaffiec005e562018-11-06 15:04:49 +01001384 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1385 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1386 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001387
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001388 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001389 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001390 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001391 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001392 ALOGV("%s() Using MSD devices %s instead of devices %s",
1393 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001394 } else {
1395 *output = AUDIO_IO_HANDLE_NONE;
1396 }
1397 }
1398 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001399 sp<PreferredMixerAttributesInfo> info = nullptr;
1400 if (outputDevices.size() == 1) {
1401 info = getPreferredMixerAttributesInfo(
1402 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001403 mEngine->getProductStrategyForAttributes(*resultAttr),
1404 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001405 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1406 // and it is currently active.
1407 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001408 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001409 info = nullptr;
1410 }
jiabin220eea12024-05-17 17:55:20 +00001411 if (com::android::media::audioserver::
1412 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1413 if (info != nullptr && info->getUid() == uid &&
1414 info->configMatches(*config) &&
1415 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1416 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1417 [this, &outputDevices](audio_usage_t usage) {
1418 return mOutputs.isUsageActiveOnDevice(
1419 usage, outputDevices[0]); }))) {
1420 // Bit-perfect request is not allowed when the phone mode is not normal or
1421 // there is any higher priority user case active.
1422 return INVALID_OPERATION;
1423 }
1424 }
jiabina84c3d32022-12-02 18:59:55 +00001425 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001426 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001427 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001428 // The client will be active if the client is currently preferred mixer owner and the
1429 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001430 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001431 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001432 && info->getUid() == uid
1433 && *output != AUDIO_IO_HANDLE_NONE
1434 // When bit-perfect output is selected for the preferred mixer attributes owner,
1435 // only need to consider the config matches.
1436 && mOutputs.valueFor(*output)->isConfigurationMatched(
1437 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001438
1439 if (*isBitPerfect) {
1440 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1441 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001442 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001443 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001444 AudioProfileVector profiles;
1445 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1446 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001447 const auto channels = profiles[0]->getChannels();
1448 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1449 config->channel_mask = *channels.begin();
1450 }
1451 const auto sampleRates = profiles[0]->getSampleRates();
1452 if (!sampleRates.empty() &&
1453 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1454 config->sample_rate = *sampleRates.begin();
1455 }
jiabinf1c73972022-04-14 16:28:52 -07001456 config->format = profiles[0]->getFormat();
1457 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001458 return INVALID_OPERATION;
1459 }
Paul McLeanaa981192015-03-21 09:55:15 -07001460
François Gaffiec005e562018-11-06 15:04:49 +01001461 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001462 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001463 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001464 *selectedDeviceId = outputDevice->getId();
1465 break;
1466 }
1467 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001468
Eric Laurent8a1095a2019-11-08 14:44:16 -08001469 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1470 *outputType = API_OUTPUT_TELEPHONY_TX;
1471 } else {
1472 *outputType = API_OUTPUT_LEGACY;
1473 }
1474
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001475 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1476
1477 return NO_ERROR;
1478}
1479
1480status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1481 audio_io_handle_t *output,
1482 audio_session_t session,
1483 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001484 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001485 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001486 audio_output_flags_t *flags,
1487 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001488 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001489 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001490 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001491 bool *isSpatialized,
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00001492 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001493{
1494 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1495 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1496 return INVALID_OPERATION;
1497 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001498 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001499 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001500 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001501 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001502 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001503 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001504 const sp<DeviceDescriptor> requestedDevice =
1505 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1506
1507 // Prevent from storing invalid requested device id in clients
1508 const audio_port_handle_t sanitizedRequestedPortId =
1509 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1510 *selectedDeviceId = sanitizedRequestedPortId;
1511
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001512 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001513 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001514 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1515 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001516 if (status != NO_ERROR) {
1517 return status;
1518 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001519 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001520 if (secondaryOutputs != nullptr) {
1521 for (auto &secondaryMix : secondaryMixes) {
1522 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1523 if (outputDesc != nullptr &&
1524 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1525 secondaryOutputs->push_back(outputDesc->mIoHandle);
1526 weakSecondaryOutputDescs.push_back(outputDesc);
1527 }
1528 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001529 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001530
Eric Laurent8fc147b2018-07-22 19:13:55 -07001531 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001532 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001533 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001534 };
jiabin4ef93452019-09-10 14:29:54 -07001535 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001536
Eric Laurentc209fe42020-06-05 18:11:23 -07001537 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001538 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001539 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001540 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001541 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001542 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001543 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001544 std::move(weakSecondaryOutputDescs),
1545 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001546 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001547
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001548 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1549 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001550
Eric Laurente83b55d2014-11-14 10:06:21 -08001551 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001552}
1553
Eric Laurentc529cf62020-04-17 18:19:10 -07001554status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1555 audio_session_t session,
1556 const audio_config_t *config,
1557 audio_output_flags_t flags,
1558 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001559 audio_io_handle_t *output,
1560 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001561
1562 *output = AUDIO_IO_HANDLE_NONE;
1563
1564 // skip direct output selection if the request can obviously be attached to a mixed output
1565 // and not explicitly requested
1566 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1567 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1568 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1569 return NAME_NOT_FOUND;
1570 }
1571
1572 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1573 // This prevents creating an offloaded track and tearing it down immediately after start
1574 // when audioflinger detects there is an active non offloadable effect.
1575 // FIXME: We should check the audio session here but we do not have it in this context.
1576 // This may prevent offloading in rare situations where effects are left active by apps
1577 // in the background.
1578 sp<IOProfile> profile;
1579 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1580 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1581 profile = getProfileForOutput(
1582 devices, config->sample_rate, config->format, config->channel_mask,
1583 flags, true /* directOnly */);
1584 }
1585
1586 if (profile == nullptr) {
1587 return NAME_NOT_FOUND;
1588 }
1589
1590 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1591 for (size_t i = 0; i < mOutputs.size(); i++) {
1592 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1593 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1594 // reuse direct output if currently open by the same client
1595 // and configured with same parameters
1596 if ((config->sample_rate == desc->getSamplingRate()) &&
1597 (config->format == desc->getFormat()) &&
1598 (config->channel_mask == desc->getChannelMask()) &&
1599 (session == desc->mDirectClientSession)) {
1600 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301601 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001602 mOutputs.keyAt(i), session);
1603 *output = mOutputs.keyAt(i);
1604 return NO_ERROR;
1605 }
1606 }
1607 }
1608
1609 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001610 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301611 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1612 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001613 return NAME_NOT_FOUND;
1614 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1615 // MMAP gracefully handles lack of an exclusive track resource by mixing
1616 // above the audio framework. For AAudio to know that the limit is reached,
1617 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301618 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1619 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001620 return NAME_NOT_FOUND;
1621 } else {
1622 // Close outputs on this profile, if available, to free resources for this request
1623 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1624 const auto desc = mOutputs.valueAt(i);
1625 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301626 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1627 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001628 closeOutput(desc->mIoHandle);
1629 }
1630 }
1631 }
1632 }
1633
1634 // Unable to close streams to find free resources for this request
1635 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301636 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1637 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001638 return NAME_NOT_FOUND;
1639 }
1640
Atneya Nairb16666a2023-12-11 20:18:33 -08001641 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001642
Michael Chan6fb34492020-12-08 15:44:49 +11001643 // An MSD patch may be using the only output stream that can service this request. Release
1644 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001645 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001646
Eric Laurentf1f22e72021-07-13 14:04:14 +02001647 status_t status =
Haofan Wangf6e304f2024-07-09 23:06:58 -07001648 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1649 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001650
1651 // only accept an output with the requested parameters
1652 if (status != NO_ERROR ||
1653 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1654 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1655 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1656 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1657 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1658 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1659 config->channel_mask, outputDesc->getChannelMask());
1660 if (*output != AUDIO_IO_HANDLE_NONE) {
1661 outputDesc->close();
1662 }
1663 // fall back to mixer output if possible when the direct output could not be open
1664 if (audio_is_linear_pcm(config->format) &&
1665 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1666 return NAME_NOT_FOUND;
1667 }
1668 *output = AUDIO_IO_HANDLE_NONE;
1669 return BAD_VALUE;
1670 }
1671 outputDesc->mDirectOpenCount = 1;
1672 outputDesc->mDirectClientSession = session;
1673
1674 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001675 setOutputDevices(__func__, outputDesc,
1676 devices,
1677 true,
1678 0,
1679 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001680 mPreviousOutputs = mOutputs;
1681 ALOGV("%s returns new direct output %d", __func__, *output);
1682 mpClientInterface->onAudioPortListUpdate();
1683 return NO_ERROR;
1684}
1685
François Gaffie11d30102018-11-02 16:09:09 +01001686audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1687 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001688 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001689 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001690 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001691 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001692 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001693 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001694 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001695{
Andy Hungc88b0642018-04-27 15:42:35 -07001696 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001697
jiabine375d412019-02-26 12:54:53 -08001698 // Discard haptic channel mask when forcing muting haptic channels.
1699 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001700 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1701 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001702
Eric Laurente552edb2014-03-10 17:42:56 -07001703 // open a direct output if required by specified parameters
1704 //force direct flag if offload flag is set: offloading implies a direct output stream
1705 // and all common behaviors are driven by checking only the direct flag
1706 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001707 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1708 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001709 }
Nadav Bar766fb022018-01-07 12:18:03 +02001710 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1711 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001712 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001713
1714 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1715
Eric Laurente83b55d2014-11-14 10:06:21 -08001716 // only allow deep buffering for music stream type
1717 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001718 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001719 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001720 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001721 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1722 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001723 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001724 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001725 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001726 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001727 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001728 audio_is_linear_pcm(config->format) &&
1729 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001730 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001731 AUDIO_OUTPUT_FLAG_DIRECT);
1732 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001733 }
Eric Laurente552edb2014-03-10 17:42:56 -07001734
Carter Hsua3abb402021-10-26 11:11:20 +08001735 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1736 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1737 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1738 }
1739
Eric Laurentf9230d52024-01-26 18:49:09 +01001740 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001741 // was specified and offload or direct playback is not explicitly requested, and there is no
1742 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001743 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001744 if (mSpatializerOutput != nullptr &&
1745 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1746 prefMixerConfigInfo == nullptr &&
1747 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1748 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001749 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001750 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001751 }
1752
Eric Laurentc529cf62020-04-17 18:19:10 -07001753 audio_config_t directConfig = *config;
1754 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001755
1756 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1757 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001758 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001759 return output;
1760 }
1761
Eric Laurent14cbfca2016-03-17 09:42:16 -07001762 // A request for HW A/V sync cannot fallback to a mixed output because time
1763 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001764 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001765 return AUDIO_IO_HANDLE_NONE;
1766 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001767 // A request for Tuner cannot fallback to a mixed output
1768 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1769 return AUDIO_IO_HANDLE_NONE;
1770 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001771
Eric Laurente552edb2014-03-10 17:42:56 -07001772 // ignoring channel mask due to downmix capability in mixer
1773
1774 // open a non direct output
1775
1776 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001777 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001778 // get which output is suitable for the specified stream. The actual
1779 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001780 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001781 if (prefMixerConfigInfo != nullptr) {
1782 for (audio_io_handle_t outputHandle : outputs) {
1783 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1784 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1785 output = outputHandle;
1786 break;
1787 }
1788 }
1789 if (output == AUDIO_IO_HANDLE_NONE) {
1790 // No output open with the preferred profile. Open a new one.
1791 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1792 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1793 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1794 config.format = prefMixerConfigInfo->getConfigBase().format;
1795 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1796 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1797 &config, prefMixerConfigInfo->getFlags());
1798 if (preferredOutput == nullptr) {
1799 ALOGE("%s failed to open output with preferred mixer config", __func__);
1800 } else {
1801 output = preferredOutput->mIoHandle;
1802 }
1803 }
1804 } else {
1805 // at this stage we should ignore the DIRECT flag as no direct output could be
1806 // found earlier
1807 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001808 if (com::android::media::audioserver::
1809 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1810 // If the preferred mixer attributes is null, do not select the bit-perfect output
1811 // unless the bit-perfect output is the only output.
1812 // The bit-perfect output can exist while the passed in preferred mixer attributes
1813 // info is null when it is a high priority client. The high priority clients are
1814 // ringtone or alarm, which is not a bit-perfect use case.
1815 size_t i = 0;
1816 while (i < outputs.size() && outputs.size() > 1) {
1817 auto desc = mOutputs.valueFor(outputs[i]);
1818 // The output descriptor must not be null here.
1819 if (desc->isBitPerfect()) {
1820 outputs.removeItemsAt(i);
1821 } else {
1822 i += 1;
1823 }
1824 }
1825 }
jiabina84c3d32022-12-02 18:59:55 +00001826 output = selectOutput(
1827 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1828 }
Eric Laurente552edb2014-03-10 17:42:56 -07001829 }
François Gaffie11d30102018-11-02 16:09:09 +01001830 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001831 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001832 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001833
Eric Laurente552edb2014-03-10 17:42:56 -07001834 return output;
1835}
1836
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001837sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001838 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1839 mAvailableInputDevices);
1840 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1841}
1842
1843DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1844 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1845 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001846}
1847
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001848const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001849 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001850 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1851 if (msdModule != 0) {
1852 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1853 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1854 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1855 const struct audio_port_config *source = &patch->mPatch.sources[j];
1856 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1857 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001858 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001859 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001860 }
1861 }
1862 }
1863 return msdPatches;
1864}
1865
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001866bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1867 ssize_t index = mAudioPatches.indexOfKey(handle);
1868 if (index < 0) {
1869 return false;
1870 }
1871 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1872 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1873 if (msdModule == nullptr) {
1874 return false;
1875 }
1876 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1877 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1878 return true;
1879 }
1880 index = getMsdOutputPatches().indexOfKey(handle);
1881 if (index < 0) {
1882 return false;
1883 }
1884 return true;
1885}
1886
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001887status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1888 const InputProfileCollection &inputProfiles,
1889 const OutputProfileCollection &outputProfiles,
1890 const sp<DeviceDescriptor> &sourceDevice,
1891 const sp<DeviceDescriptor> &sinkDevice,
1892 AudioProfileVector& sourceProfiles,
1893 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001894 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001895 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001896 return NO_INIT;
1897 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001898 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001899 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001900 return NO_INIT;
1901 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001902 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001903 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1904 inProfile->supportsDevice(sourceDevice)) {
1905 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001906 }
1907 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001908 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001909 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001910 outProfile->supportsDevice(sinkDevice)) {
1911 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001912 }
1913 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001914 return NO_ERROR;
1915}
1916
1917status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1918 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1919 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1920{
Dean Wheatley16809da2022-12-09 14:55:46 +11001921 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1922 static const std::vector<audio_format_t> formatsOrder = {{
1923 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001924 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1925 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001926 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1927 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1928 // preferred).
1929 std::vector<audio_channel_mask_t> masks = {{
1930 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1931 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1932 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1933 // insert index masks (higher counts most preferred) as preferred over position masks
1934 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1935 masks.insert(
1936 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1937 }
1938 return masks;
1939 }();
1940
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001941 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001942 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1943 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001944 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001945 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1946 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001947 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001948 }
1949 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1950 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1951 sinkConfig->format = bestSinkConfig.format;
1952 // For encoded streams force direct flag to prevent downstream mixing.
1953 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1954 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001955 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1956 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001957 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001958 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1959 // raw and IEC61937 framed streams.
1960 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1961 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1962 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001963 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1964 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001965 sourceConfig->channel_mask =
1966 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1967 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1968 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001969 sourceConfig->format = bestSinkConfig.format;
1970 // Copy input stream directly without any processing (e.g. resampling).
1971 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1972 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1973 if (hwAvSync) {
1974 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1975 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1976 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1977 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1978 }
1979 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1980 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1981 sinkConfig->config_mask |= config_mask;
1982 sourceConfig->config_mask |= config_mask;
1983 return NO_ERROR;
1984}
1985
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001986PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1987 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001988{
1989 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001990 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1991 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1992 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1993 if (deviceModule == nullptr) {
1994 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1995 return patchBuilder;
1996 }
1997 const InputProfileCollection inputProfiles = msdIsSource ?
1998 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1999 const OutputProfileCollection outputProfiles = msdIsSource ?
2000 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2001
2002 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2003 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2004 device : getMsdAudioOutDevices().itemAt(0);
2005 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2006
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002007 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2008 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002009 AudioProfileVector sourceProfiles;
2010 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002011 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2012 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002013 for (auto hwAvSync : { true, false }) {
2014 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2015 sourceProfiles, sinkProfiles) != NO_ERROR) {
2016 continue;
2017 }
2018 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2019 &sinkConfig) == NO_ERROR) {
2020 // Found a matching config. Re-create PatchBuilder with this config.
2021 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2022 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002023 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002024 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002025 " supporting PCM format conversion.", __func__);
2026 return patchBuilder;
2027}
2028
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002029status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002030 DeviceVector devices;
2031 if (outputDevices != nullptr && outputDevices->size() > 0) {
2032 devices.add(*outputDevices);
2033 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002034 // Use media strategy for unspecified output device. This should only
2035 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2036 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002037 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002038 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002039 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002040 }
Michael Chan6fb34492020-12-08 15:44:49 +11002041 std::vector<PatchBuilder> patchesToCreate;
2042 for (auto i = 0u; i < devices.size(); ++i) {
2043 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002044 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002045 }
2046 // Retain only the MSD patches associated with outputDevices request.
2047 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002048 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002049 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2050 auto retainedPatch = false;
2051 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2052 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2053 patchesToRemove.removeItemsAt(i);
2054 retainedPatch = true;
2055 break;
2056 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002057 }
Michael Chan6fb34492020-12-08 15:44:49 +11002058 if (retainedPatch) {
2059 it = patchesToCreate.erase(it);
2060 continue;
2061 }
2062 ++it;
2063 }
2064 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2065 return NO_ERROR;
2066 }
2067 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2068 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002069 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002070 }
Michael Chan6fb34492020-12-08 15:44:49 +11002071 status_t status = NO_ERROR;
2072 for (const auto &p : patchesToCreate) {
2073 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2074 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2075 char message[256];
2076 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2077 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2078 currStatus == NO_ERROR ? "Success" : "Error",
2079 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2080 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2081 if (currStatus == NO_ERROR) {
2082 ALOGD("%s", message);
2083 } else {
2084 ALOGE("%s", message);
2085 if (status == NO_ERROR) {
2086 status = currStatus;
2087 }
2088 }
2089 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002090 return status;
2091}
2092
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002093void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2094 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002095 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 && devices.getDevice(sink->ext.device.type,
2100 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2101 releaseAudioPatch(patch->getHandle(), mUidCached);
2102 break;
2103 }
2104 }
2105 }
2106}
2107
Dorin Drimus94d94412022-02-02 09:05:02 +01002108bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002109 DeviceVector devicesToCheck =
2110 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002111 AudioPatchCollection msdPatches = getMsdOutputPatches();
2112 for (size_t i = 0; i < msdPatches.size(); i++) {
2113 const auto& patch = msdPatches[i];
2114 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2115 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2116 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2117 const auto& foundDevice = devicesToCheck.getDevice(
2118 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2119 if (foundDevice != nullptr) {
2120 devicesToCheck.remove(foundDevice);
2121 if (devicesToCheck.isEmpty()) {
2122 return true;
2123 }
2124 }
2125 }
2126 }
2127 }
2128 return false;
2129}
2130
Eric Laurente0720872014-03-11 09:30:41 -07002131audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002132 audio_output_flags_t flags,
2133 audio_format_t format,
2134 audio_channel_mask_t channelMask,
2135 uint32_t samplingRate,
2136 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002137{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002138 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2139 "%s called with format %#x", __func__, format);
2140
jiabinebb6af42020-06-09 17:31:17 -07002141 // Return the output that haptic-generating attached to when 1) session id is specified,
2142 // 2) haptic-generating effect exists for given session id and 3) the output that
2143 // haptic-generating effect attached to is in given outputs.
2144 if (sessionId != AUDIO_SESSION_NONE) {
2145 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2146 sessionId, FX_IID_HAPTICGENERATOR);
2147 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2148 return hapticGeneratingOutput;
2149 }
2150 }
2151
Eric Laurent16c66dd2019-05-01 17:54:10 -07002152 // Flags disqualifying an output: the match must happen before calling selectOutput()
2153 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2154 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2155
2156 // Flags expressing a functional request: must be honored in priority over
2157 // other criteria
2158 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2159 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002160 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2161 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002162 // Flags expressing a performance request: have lower priority than serving
2163 // requested sampling rate or channel mask
2164 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2165 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2166 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2167
2168 const audio_output_flags_t functionalFlags =
2169 (audio_output_flags_t)(flags & kFunctionalFlags);
2170 const audio_output_flags_t performanceFlags =
2171 (audio_output_flags_t)(flags & kPerformanceFlags);
2172
2173 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2174
Eric Laurente552edb2014-03-10 17:42:56 -07002175 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002176 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002177 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002178 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002179 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002180 // with tiebreak preferring the minimum number of extra functional flags
2181 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002182 // 3: the output supporting the exact channel mask
2183 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002184 // 5: the output with the highest sampling rate if the requested sample rate is
2185 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002186 // 6: the output with the highest number of requested performance flags
2187 // 7: the output with the bit depth the closest to the requested one
2188 // 8: the primary output
2189 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002190
Eric Laurent16c66dd2019-05-01 17:54:10 -07002191 // matching criteria values in priority order for best matching output so far
2192 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002193
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002194 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002195 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2196 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2197 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002198
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002199 for (audio_io_handle_t output : outputs) {
2200 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002201 // matching criteria values in priority order for current output
2202 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002203
Eric Laurent16c66dd2019-05-01 17:54:10 -07002204 if (outputDesc->isDuplicated()) {
2205 continue;
2206 }
2207 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2208 continue;
2209 }
Eric Laurent8838a382014-09-08 16:44:28 -07002210
Eric Laurent16c66dd2019-05-01 17:54:10 -07002211 // If haptic channel is specified, use the haptic output if present.
2212 // When using haptic output, same audio format and sample rate are required.
2213 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002214 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002215 // skip if haptic channel specified but output does not support it, or output support haptic
2216 // but there is no haptic channel requested AND no orphan haptic effect exist
2217 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2218 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002219 continue;
2220 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002221 // In the case of audio-coupled-haptic playback, there is no format conversion and
2222 // resampling in the framework, same format/channel/sampleRate for client and the output
2223 // thread is required. In the case of HapticGenerator effect, do not require format
2224 // matching.
2225 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2226 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002227 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002228 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002229 }
2230
2231 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002232 const int matchingFunctionalFlags =
2233 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2234 const int totalFunctionalFlags =
2235 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2236 // Prefer matching functional flags, but subtract unnecessary functional flags.
2237 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002238
2239 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002240 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2241 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002242 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2243 channelCount <= outputChannelCount) {
2244 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002245 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2246 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002247 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002248 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002249 currentMatchCriteria[3] = outputChannelCount;
2250 }
2251
2252 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002253 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002254 int diff; // avoid unsigned integer overflow.
2255 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2256
2257 // prefer the closest output sampling rate greater than or equal to target
2258 // if none exists, prefer the closest output sampling rate less than target.
2259 //
2260 // criteria is offset to make non-negative.
2261 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002262 }
2263
2264 // performance flags match
2265 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2266
2267 // format match
2268 if (format != AUDIO_FORMAT_INVALID) {
2269 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002270 PolicyAudioPort::kFormatDistanceMax -
2271 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002272 }
2273
2274 // primary output match
2275 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2276
2277 // compare match criteria by priority then value
2278 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2279 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2280 bestMatchCriteria = currentMatchCriteria;
2281 bestOutput = output;
2282
2283 std::stringstream result;
2284 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2285 std::ostream_iterator<int>(result, " "));
2286 ALOGV("%s new bestOutput %d criteria %s",
2287 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002288 }
2289 }
2290
Eric Laurent16c66dd2019-05-01 17:54:10 -07002291 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002292}
2293
Eric Laurent8fc147b2018-07-22 19:13:55 -07002294status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002295{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002296 ALOGV("%s portId %d", __FUNCTION__, portId);
2297
2298 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2299 if (outputDesc == 0) {
2300 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002301 return BAD_VALUE;
2302 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002303 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002304
Eric Laurent8fc147b2018-07-22 19:13:55 -07002305 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002306 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002307
jiabin220eea12024-05-17 17:55:20 +00002308 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2309 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2310 && outputDesc->isBitPerfect()) {
2311 // Usually, APM selects bit-perfect output for high priority use cases only when
2312 // bit-perfect output is the only output that can be routed to the selected device.
2313 // However, here is no need to play high priority use cases such as ringtone and alarm
2314 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2315 // can attach to new output.
2316 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2317 __func__, client->stream());
2318 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2319 return DEAD_OBJECT;
2320 }
2321
Eric Laurent733ce942017-12-07 12:18:25 -08002322 status_t status = outputDesc->start();
2323 if (status != NO_ERROR) {
2324 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002325 }
2326
Eric Laurent97ac8712018-07-27 18:59:02 -07002327 uint32_t delayMs;
2328 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002329
2330 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002331 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002332 if (status == DEAD_OBJECT) {
2333 sp<SwAudioOutputDescriptor> desc =
2334 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2335 if (desc == nullptr) {
2336 // This is not common, it may indicate something wrong with the HAL.
2337 ALOGE("%s unable to open output with default config", __func__);
2338 return status;
2339 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002340 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002341 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002342 }
jiabina84c3d32022-12-02 18:59:55 +00002343
2344 // If the client is the first one active on preferred mixer parameters, reopen the output
2345 // if the current mixer parameters doesn't match the preferred one.
2346 if (outputDesc->devices().size() == 1) {
2347 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2348 outputDesc->devices()[0]->getId(), client->strategy());
2349 if (info != nullptr && info->getUid() == client->uid()) {
2350 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2351 info->getConfigBase(), info->getFlags())) {
2352 stopSource(outputDesc, client);
2353 outputDesc->stop();
2354 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2355 config.channel_mask = info->getConfigBase().channel_mask;
2356 config.sample_rate = info->getConfigBase().sample_rate;
2357 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002358 sp<SwAudioOutputDescriptor> desc =
2359 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2360 if (desc == nullptr) {
2361 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002362 }
jiabin220eea12024-05-17 17:55:20 +00002363 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002364 // Intentionally return error to let the client side resending request for
2365 // creating and starting.
2366 return DEAD_OBJECT;
2367 }
2368 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002369 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002370 // If it is first bit-perfect client, reroute all clients that will be routed to
2371 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2372 PortHandleVector clientsToInvalidate;
2373 for (size_t i = 0; i < mOutputs.size(); i++) {
2374 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002375 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002376 continue;
2377 }
2378 for (const auto& c : mOutputs[i]->getClientIterable()) {
2379 clientsToInvalidate.push_back(c->portId());
2380 }
2381 }
2382 if (!clientsToInvalidate.empty()) {
2383 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2384 __func__);
2385 mpClientInterface->invalidateTracks(clientsToInvalidate);
2386 }
2387 }
jiabina84c3d32022-12-02 18:59:55 +00002388 }
2389 }
2390
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002391 if (client->hasPreferredDevice()) {
2392 // playback activity with preferred device impacts routing occurred, inform upper layers
2393 mpClientInterface->onRoutingUpdated();
2394 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002395 if (delayMs != 0) {
2396 usleep(delayMs * 1000);
2397 }
2398
jiabin220eea12024-05-17 17:55:20 +00002399 if (status == NO_ERROR &&
2400 outputDesc->mPreferredAttrInfo != nullptr &&
2401 outputDesc->isBitPerfect() &&
2402 com::android::media::audioserver::
2403 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2404 // A new client is started on bit-perfect output, update all clients internal mute.
2405 updateClientsInternalMute(outputDesc);
2406 }
2407
Eric Laurentc75307b2015-03-17 15:29:32 -07002408 return status;
2409}
2410
Eric Laurent96d1dda2022-03-14 17:14:19 +01002411bool AudioPolicyManager::isLeUnicastActive() const {
2412 if (isInCall()) {
2413 return true;
2414 }
2415 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2416}
2417
2418bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2419 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2420 return false;
2421 }
2422 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2423 ALOGV("%s active %d", __func__, active);
2424 return active;
2425}
2426
Eric Laurent97ac8712018-07-27 18:59:02 -07002427status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2428 const sp<TrackClientDescriptor>& client,
2429 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002430{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002431 // cannot start playback of STREAM_TTS if any other output is being used
2432 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002433
2434 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002435 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002436 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002437 auto clientStrategy = client->strategy();
2438 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002439 if (stream == AUDIO_STREAM_TTS) {
2440 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002441 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002442 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002443 return INVALID_OPERATION;
2444 } else {
2445 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2446 }
2447 } else {
2448 // some playback other than beacon starts
2449 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2450 }
2451
Eric Laurent77305a62016-07-25 16:39:22 -07002452 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002453 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002454 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002455
François Gaffie11d30102018-11-02 16:09:09 +01002456 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002457 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002458 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002459 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002460 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002461 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002462 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002463 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002464 } else {
2465 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002466 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002467 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2468 AUDIO_FORMAT_DEFAULT);
2469 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2470 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002471 }
2472
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002473 // requiresMuteCheck is false when we can bypass mute strategy.
2474 // It covers a common case when there is no materially active audio
2475 // and muting would result in unnecessary delay and dropped audio.
2476 const uint32_t outputLatencyMs = outputDesc->latency();
2477 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002478 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002479
Eric Laurente552edb2014-03-10 17:42:56 -07002480 // increment usage count for this stream on the requested output:
2481 // NOTE that the usage count is the same for duplicated output and hardware output which is
2482 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002483 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002484
2485 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002486 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002487 // Preferred device may be exclusive, use only if no other active clients on this output
2488 devices = DeviceVector(
2489 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2490 } else {
2491 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2492 }
François Gaffie11d30102018-11-02 16:09:09 +01002493 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002494 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002495 }
2496 }
Eric Laurente552edb2014-03-10 17:42:56 -07002497
François Gaffiec005e562018-11-06 15:04:49 +01002498 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002499 selectOutputForMusicEffects();
2500 }
2501
François Gaffie1c878552018-11-22 16:53:21 +01002502 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002503 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002504 if (devices.isEmpty()) {
2505 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002506 }
François Gaffiec005e562018-11-06 15:04:49 +01002507 bool shouldWait =
2508 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2509 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2510 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002511 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002512 const bool needToCloseBitPerfectOutput =
2513 (com::android::media::audioserver::
2514 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2515 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2516 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002517 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002518 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002519 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002520 // An output has a shared device if
2521 // - managed by the same hw module
2522 // - supports the currently selected device
2523 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002524 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002525
Eric Laurent77305a62016-07-25 16:39:22 -07002526 // force a device change if any other output is:
2527 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002528 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002529 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002530 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002531 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002532 // change the device currently selected by the other output.
2533 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002534 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002535 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002536 force = true;
2537 }
2538 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002539 // a notification so that audio focus effect can propagate, or that a mute/unmute
2540 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002541 const uint32_t latencyMs = desc->latency();
2542 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2543
2544 if (shouldWait && isActive && (waitMs < latencyMs)) {
2545 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002546 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002547
2548 // Require mute check if another output is on a shared device
2549 // and currently active to have proper drain and avoid pops.
2550 // Note restoring AudioTracks onto this output needs to invoke
2551 // a volume ramp if there is no mute.
2552 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002553
2554 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2555 outputsToReopen.push_back(desc);
2556 }
Eric Laurente552edb2014-03-10 17:42:56 -07002557 }
2558 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002559
jiabin220eea12024-05-17 17:55:20 +00002560 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002561 // If the output is open with preferred mixer attributes, but the routed device is
2562 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2563 // changed.
2564 return DEAD_OBJECT;
2565 }
jiabin220eea12024-05-17 17:55:20 +00002566 for (auto& outputToReopen : outputsToReopen) {
2567 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2568 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002569 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302570 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2571 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002572
Eric Laurente552edb2014-03-10 17:42:56 -07002573 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002574 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002575 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002576 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002577 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002578 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002579 outputDesc->useHwGain() /*force*/)) {
2580 // request AudioService to reinitialize the volume curves asynchronously
2581 ALOGE("checkAndSetVolume failed, requesting volume range init");
2582 mpClientInterface->onVolumeRangeInitRequest();
2583 };
Eric Laurente552edb2014-03-10 17:42:56 -07002584
2585 // update the outputs if starting an output with a stream that can affect notification
2586 // routing
2587 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002588
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002589 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002590 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002591 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002592 }
Eric Laurentdc462862016-07-19 12:29:53 -07002593
2594 if (waitMs > muteWaitMs) {
2595 *delayMs = waitMs - muteWaitMs;
2596 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002597
2598 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2599 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2600 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2601 // change occurs after the MixerThread starts and causes a stream volume
2602 // glitch.
2603 //
2604 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002605 }
Eric Laurentdc462862016-07-19 12:29:53 -07002606
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002607 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002608 mEngine->getForceUse(
2609 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002610 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002611 }
2612
Eric Laurent97ac8712018-07-27 18:59:02 -07002613 // Automatically enable the remote submix input when output is started on a re routing mix
2614 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002615 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2616 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002617 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2618 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2619 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002620 "remote-submix",
2621 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002622 }
2623
Eric Laurent96d1dda2022-03-14 17:14:19 +01002624 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2625
Eric Laurente552edb2014-03-10 17:42:56 -07002626 return NO_ERROR;
2627}
2628
Eric Laurent96d1dda2022-03-14 17:14:19 +01002629void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2630 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2631 bool isUnicastActive = isLeUnicastActive();
2632
2633 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002634 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002635 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2636 for (size_t i = 0; i < mOutputs.size(); i++) {
2637 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2638 if (desc != ignoredOutput && desc->isActive()
2639 && ((isUnicastActive &&
2640 !desc->devices().
2641 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2642 || (wasUnicastActive &&
2643 !desc->devices().getDevicesFromTypes(
2644 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2645 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2646 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002647 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002648 // If the device is using preferred mixer attributes, the output need to reopen
2649 // with default configuration when the new selected devices are different from
2650 // current routing devices.
2651 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2652 continue;
2653 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302654 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002655 // re-apply device specific volume if not done by setOutputDevice()
2656 if (!force) {
2657 applyStreamVolumes(desc, newDevices.types(), delayMs);
2658 }
2659 }
2660 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002661 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002662 }
2663}
2664
Eric Laurent8fc147b2018-07-22 19:13:55 -07002665status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002666{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002667 ALOGV("%s portId %d", __FUNCTION__, portId);
2668
2669 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2670 if (outputDesc == 0) {
2671 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002672 return BAD_VALUE;
2673 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002674 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002675
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002676 if (client->hasPreferredDevice(true)) {
2677 // playback activity with preferred device impacts routing occurred, inform upper layers
2678 mpClientInterface->onRoutingUpdated();
2679 }
2680
Eric Laurent97ac8712018-07-27 18:59:02 -07002681 ALOGV("stopOutput() output %d, stream %d, session %d",
2682 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002683
Eric Laurent97ac8712018-07-27 18:59:02 -07002684 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002685
Eric Laurent733ce942017-12-07 12:18:25 -08002686 if (status == NO_ERROR ) {
2687 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002688 } else {
2689 return status;
2690 }
2691
2692 if (outputDesc->devices().size() == 1) {
2693 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2694 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002695 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002696 if (info != nullptr && info->getUid() == client->uid()) {
2697 info->decreaseActiveClient();
2698 if (info->getActiveClientCount() == 0) {
2699 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002700 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002701 }
2702 }
jiabin220eea12024-05-17 17:55:20 +00002703 if (com::android::media::audioserver::
2704 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2705 !outputReopened && outputDesc->isBitPerfect()) {
2706 // Only need to update the clients' internal mute when the output is bit-perfect and it
2707 // is not reopened.
2708 updateClientsInternalMute(outputDesc);
2709 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002710 }
2711 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002712}
2713
Eric Laurent97ac8712018-07-27 18:59:02 -07002714status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2715 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002716{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002717 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002718 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002719 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002720 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002721
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002722 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2723
François Gaffie1c878552018-11-22 16:53:21 +01002724 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2725 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002726 // Automatically disable the remote submix input when output is stopped on a
2727 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002728 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002729 if (isSingleDeviceType(
2730 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002731 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002732 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002733 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2734 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002735 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002736 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002737 }
2738 }
2739 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002740 if (client->hasPreferredDevice(true) &&
2741 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002742 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002743 forceDeviceUpdate = true;
2744 }
2745
Eric Laurente552edb2014-03-10 17:42:56 -07002746 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002747 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002748
Eric Laurente552edb2014-03-10 17:42:56 -07002749 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002750 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002751 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002752 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002753
2754 // If the routing does not change, if an output is routed on a device using HwGain
2755 // (aka setAudioPortConfig) and there are still active clients following different
2756 // volume group(s), force reapply volume
2757 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2758 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2759
Eric Laurente552edb2014-03-10 17:42:56 -07002760 // delay the device switch by twice the latency because stopOutput() is executed when
2761 // the track stop() command is received and at that time the audio track buffer can
2762 // still contain data that needs to be drained. The latency only covers the audio HAL
2763 // and kernel buffers. Also the latency does not always include additional delay in the
2764 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302765 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002766 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002767
2768 // force restoring the device selection on other active outputs if it differs from the
2769 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002770 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002771 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002772 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002773 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002774 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002775 desc->isActive() &&
2776 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002777 (newDevices != desc->devices())) {
2778 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2779 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002780
jiabin220eea12024-05-17 17:55:20 +00002781 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002782 // If the device is using preferred mixer attributes, the output need to
2783 // reopen with default configuration when the new selected devices are
2784 // different from current routing devices.
2785 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2786 continue;
2787 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302788 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002789
Eric Laurent57de36c2016-09-28 16:59:11 -07002790 // re-apply device specific volume if not done by setOutputDevice()
2791 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002792 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002793 }
Eric Laurente552edb2014-03-10 17:42:56 -07002794 }
2795 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002796 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002797 // update the outputs if stopping one with a stream that can affect notification routing
2798 handleNotificationRoutingForStream(stream);
2799 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002800
2801 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2802 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002803 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002804 }
2805
François Gaffiec005e562018-11-06 15:04:49 +01002806 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002807 selectOutputForMusicEffects();
2808 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002809
2810 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2811
Eric Laurente552edb2014-03-10 17:42:56 -07002812 return NO_ERROR;
2813 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002814 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002815 return INVALID_OPERATION;
2816 }
2817}
2818
jiabinbce0c1d2020-10-05 11:20:18 -07002819bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002820{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002821 ALOGV("%s portId %d", __FUNCTION__, portId);
2822
2823 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2824 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002825 // If an output descriptor is closed due to a device routing change,
2826 // then there are race conditions with releaseOutput from tracks
2827 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2828 // destroyed shortly thereafter.
2829 //
2830 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002831 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002832 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002833 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834
2835 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002836
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302837 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2838 if (outputDesc->isClientActive(client)) {
2839 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2840 stopOutput(portId);
2841 }
2842
Eric Laurent8fc147b2018-07-22 19:13:55 -07002843 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2844 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002845 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002846 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002847 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002848 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002849 if (--outputDesc->mDirectOpenCount == 0) {
2850 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002851 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002852 }
2853 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302854
Andy Hung39efb7a2018-09-26 15:39:28 -07002855 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002856 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2857 // The output is pending reopened to query dynamic profiles and
2858 // there is no active clients
2859 closeOutput(outputDesc->mIoHandle);
2860 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2861 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2862 if (newOutputDesc == nullptr) {
2863 ALOGE("%s failed to open output", __func__);
2864 }
2865 return true;
2866 }
2867 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002868}
2869
Eric Laurentcaf7f482014-11-25 17:50:47 -08002870status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2871 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002872 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002873 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002874 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002875 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002876 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002877 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002878 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002879 audio_port_handle_t *portId,
2880 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002881{
François Gaffiec005e562018-11-06 15:04:49 +01002882 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002883 "flags %#x attributes=%s requested device ID %d",
2884 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2885 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002886
Eric Laurentad2e7b92017-09-14 20:06:42 -07002887 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002888 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002889 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002890 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002891 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002892 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002893 sp<RecordClientDescriptor> clientDesc;
2894 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002895 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002896 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002897
2898 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2899 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2900 return INVALID_OPERATION;
2901 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002902
Francois Gaffie716e1432019-01-14 16:58:59 +01002903 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2904 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002905 }
2906
Paul McLean466dc8e2015-04-17 13:15:36 -06002907 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002908 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002909 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002910
Eric Laurentad2e7b92017-09-14 20:06:42 -07002911 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2912 // possible
2913 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2914 *input != AUDIO_IO_HANDLE_NONE) {
2915 ssize_t index = mInputs.indexOfKey(*input);
2916 if (index < 0) {
2917 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2918 status = BAD_VALUE;
2919 goto error;
2920 }
2921 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002922 RecordClientVector clients = inputDesc->getClientsForSession(session);
2923 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002924 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2925 status = BAD_VALUE;
2926 goto error;
2927 }
2928 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2929 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002930 // corresponds to a new client and is only permitted from the same UID.
2931 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002932 if (clients.size() > 1) {
2933 for (const auto& client : clients) {
2934 // The client map is ordered by key values (portId) and portIds are allocated
2935 // incrementaly. So the first client in this list is the one opened by audio flinger
2936 // when the mmap stream is created and should be ignored as it does not correspond
2937 // to an actual client
2938 if (client == *clients.cbegin()) {
2939 continue;
2940 }
2941 if (uid != client->uid() && !client->isSilenced()) {
2942 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2943 uid, client->portId(), client->uid());
2944 status = INVALID_OPERATION;
2945 goto error;
2946 }
Eric Laurent331679c2018-04-16 17:03:16 -07002947 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002948 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002949 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002950 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002951
Eric Laurentfecbceb2021-02-09 14:46:43 +01002952 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002953 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002954 }
2955
2956 *input = AUDIO_IO_HANDLE_NONE;
2957 *inputType = API_INPUT_INVALID;
2958
Francois Gaffie716e1432019-01-14 16:58:59 +01002959 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002960 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002961 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002962 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002963 ALOGW("%s could not find input mix for attr %s",
2964 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002965 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002966 }
jiabinc1de2df2019-05-07 14:26:40 -07002967 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2968 String8(attr->tags + strlen("addr=")),
2969 AUDIO_FORMAT_DEFAULT);
2970 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002971 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002972 __func__, attributes.source, attributes.tags);
2973 status = BAD_VALUE;
2974 goto error;
2975 }
2976
Kevin Rocard25f9b052019-02-27 15:08:54 -08002977 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2978 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2979 } else {
2980 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2981 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002982 if (virtualDeviceId) {
2983 *virtualDeviceId = policyMix->mVirtualDeviceId;
2984 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002985 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002986 if (explicitRoutingDevice != nullptr) {
2987 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002988 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002989 // Prevent from storing invalid requested device id in clients
2990 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002991 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002992 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2993 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002994 }
François Gaffie11d30102018-11-02 16:09:09 +01002995 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002996 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002997 status = BAD_VALUE;
2998 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002999 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003000 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3001 *inputType = API_INPUT_MIX_CAPTURE;
3002 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003003 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3004 // there is an external policy, but this input is attached to a mix of recorders,
3005 // meaning it receives audio injected into the framework, so the recorder doesn't
3006 // know about it and is therefore considered "legacy"
3007 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003008
3009 if (virtualDeviceId) {
3010 *virtualDeviceId = policyMix->mVirtualDeviceId;
3011 }
François Gaffie11d30102018-11-02 16:09:09 +01003012 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003013 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003014 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003015 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003016 } else {
3017 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003018 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003019
Eric Laurent599c7582015-12-07 18:05:55 -08003020 }
3021
François Gaffiec005e562018-11-06 15:04:49 +01003022 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003023 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003024 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003025 AudioProfileVector profiles;
3026 status_t ret = getProfilesForDevices(
3027 DeviceVector(device), profiles, flags, true /*isInput*/);
3028 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003029 const auto channels = profiles[0]->getChannels();
3030 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3031 config->channel_mask = *channels.begin();
3032 }
3033 const auto sampleRates = profiles[0]->getSampleRates();
3034 if (!sampleRates.empty() &&
3035 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3036 config->sample_rate = *sampleRates.begin();
3037 }
jiabinf1c73972022-04-14 16:28:52 -07003038 config->format = profiles[0]->getFormat();
3039 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003040 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003041 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003042
Marvin Ramine5a122d2023-12-07 13:57:59 +01003043
3044 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3045 *virtualDeviceId = policyMix->mVirtualDeviceId;
3046 }
3047
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048exit:
3049
François Gaffiec005e562018-11-06 15:04:49 +01003050 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3051 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003052
Francois Gaffie716e1432019-01-14 16:58:59 +01003053 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003054 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003055 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003056
Mikhail Naganov2996f672019-04-18 12:29:59 -07003057 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003058 requestedDeviceId, attributes.source, flags,
3059 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003060 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003061 // Move (if found) effect for the client session to its input
3062 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003063 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003064
3065 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3066 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003067
Eric Laurent599c7582015-12-07 18:05:55 -08003068 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003069
3070error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003071 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003072}
3073
3074
François Gaffie11d30102018-11-02 16:09:09 +01003075audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003076 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003077 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003078 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003079 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003080 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003081{
3082 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003083 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003084 bool isSoundTrigger = false;
3085
François Gaffiec005e562018-11-06 15:04:49 +01003086 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003087 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3088 if (index >= 0) {
3089 input = mSoundTriggerSessions.valueFor(session);
3090 isSoundTrigger = true;
3091 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3092 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3093 } else {
3094 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003095 }
François Gaffiec005e562018-11-06 15:04:49 +01003096 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003097 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003098 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003099 }
3100
Carter Hsua3abb402021-10-26 11:11:20 +08003101 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3102 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3103 }
3104
Eric Laurentfe231122017-11-17 17:48:06 -08003105 // sampling rate and flags may be updated by getInputProfile
3106 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3107 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003108 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003109 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003110 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003111 // find a compatible input profile (not necessarily identical in parameters)
3112 sp<IOProfile> profile = getInputProfile(
3113 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3114 if (profile == nullptr) {
3115 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003116 }
jiabin2fd710d2022-05-02 23:20:22 +00003117
Glenn Kasten05ddca52016-02-11 08:17:12 -08003118 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003119 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003120 if (samplingRate == 0) {
3121 samplingRate = profileSamplingRate;
3122 }
Eric Laurente552edb2014-03-10 17:42:56 -07003123
Eric Laurent322b4d22015-04-03 15:57:54 -07003124 if (profile->getModuleHandle() == 0) {
3125 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003126 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003127 }
3128
Eric Laurentec376dc2021-04-08 20:41:22 +02003129 // Reuse an already opened input if a client with the same session ID already exists
3130 // on that input
3131 for (size_t i = 0; i < mInputs.size(); i++) {
3132 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3133 if (desc->mProfile != profile) {
3134 continue;
3135 }
3136 RecordClientVector clients = desc->clientsList();
3137 for (const auto &client : clients) {
3138 if (session == client->session()) {
3139 return desc->mIoHandle;
3140 }
3141 }
3142 }
3143
Eric Laurentc71b11b2024-06-03 12:54:53 +00003144 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003145 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003146 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3147 // First pick best candidate for preemption (there may not be any):
3148 // - Preempt and input if:
3149 // - It has only strictly lower priority use cases than the new client
3150 // - It has equal priority use cases than the new client, was not
3151 // opened thanks to preemption or has been active since opened.
3152 // - Order the preemption candidates by inactive first and priority second
3153 sp<AudioInputDescriptor> closeCandidate;
3154 int leastCloseRank = INT_MAX;
3155 static const int sCloseActive = 0x100;
3156
3157 for (size_t i = 0; i < mInputs.size(); i++) {
3158 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3159 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003160 continue;
3161 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003162 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3163 if (topPrioClient == nullptr) {
3164 continue;
3165 }
3166 int topPrio = source_priority(topPrioClient->source());
3167 if (topPrio < source_priority(attributes.source)
3168 || (topPrio == source_priority(attributes.source)
3169 && !desc->isPreemptor())) {
3170 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3171 if (closeRank < leastCloseRank) {
3172 leastCloseRank = closeRank;
3173 closeCandidate = desc;
3174 }
3175 }
3176 }
3177
3178 if (closeCandidate != nullptr) {
3179 closeInput(closeCandidate->mIoHandle);
3180 // Mark the new input as being issued from a preemption
3181 // so that is will not be preempted later
3182 isPreemptor = true;
3183 } else {
3184 // Then pick the best reusable input (There is always one)
3185 // The order of preference is:
3186 // 1) active inputs with same use case as the new client
3187 // 2) inactive inputs with same use case
3188 // 3) active inputs with different use cases
3189 // 4) inactive inputs with different use cases
3190 sp<AudioInputDescriptor> reuseCandidate;
3191 int leastReuseRank = INT_MAX;
3192 static const int sReuseDifferentUseCase = 0x100;
3193
3194 for (size_t i = 0; i < mInputs.size(); i++) {
3195 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3196 if (desc->mProfile != profile) {
3197 continue;
3198 }
3199 int reuseRank = sReuseDifferentUseCase;
3200 for (const auto& client: desc->getClientIterable()) {
3201 if (client->source() == attributes.source) {
3202 reuseRank = 0;
3203 break;
3204 }
3205 }
3206 reuseRank += desc->isActive() ? 0 : 1;
3207 if (reuseRank < leastReuseRank) {
3208 leastReuseRank = reuseRank;
3209 reuseCandidate = desc;
3210 }
3211 }
3212 return reuseCandidate->mIoHandle;
3213 }
3214 } else { // fix_input_sharing_logic()
3215 for (size_t i = 0; i < mInputs.size(); ) {
3216 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3217 if (desc->mProfile != profile) {
3218 i++;
3219 continue;
3220 }
3221 // if sound trigger, reuse input if used by other sound trigger on same session
3222 // else
3223 // reuse input if active client app is not in IDLE state
3224 //
3225 RecordClientVector clients = desc->clientsList();
3226 bool doClose = false;
3227 for (const auto& client : clients) {
3228 if (isSoundTrigger != client->isSoundTrigger()) {
3229 continue;
3230 }
3231 if (client->isSoundTrigger()) {
3232 if (session == client->session()) {
3233 return desc->mIoHandle;
3234 }
3235 continue;
3236 }
3237 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003238 return desc->mIoHandle;
3239 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003240 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003241 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003242 if (doClose) {
3243 closeInput(desc->mIoHandle);
3244 } else {
3245 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003246 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003247 }
3248 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003249 }
3250
Eric Laurentc71b11b2024-06-03 12:54:53 +00003251 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3252 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003253
Eric Laurentfe231122017-11-17 17:48:06 -08003254 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3255 lConfig.sample_rate = profileSamplingRate;
3256 lConfig.channel_mask = profileChannelMask;
3257 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003258
François Gaffie11d30102018-11-02 16:09:09 +01003259 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003260
3261 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003262 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003263 (profileSamplingRate != lConfig.sample_rate) ||
3264 !audio_formats_match(profileFormat, lConfig.format) ||
3265 (profileChannelMask != lConfig.channel_mask)) {
3266 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003267 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003268 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003269 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003270 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003271 }
Eric Laurent599c7582015-12-07 18:05:55 -08003272 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003273 }
3274
Eric Laurentc722f302014-12-10 11:21:49 -08003275 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003276
Eric Laurent599c7582015-12-07 18:05:55 -08003277 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003278 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003279
Eric Laurent599c7582015-12-07 18:05:55 -08003280 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003281}
3282
Eric Laurent4eb58f12018-12-07 16:41:02 -08003283status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003284{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003285 ALOGV("%s portId %d", __FUNCTION__, portId);
3286
3287 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3288 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003289 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003290 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003291 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003292 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003293 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003294 if (client->active()) {
3295 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3296 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003297 }
3298
Eric Laurent8f42ea12018-08-08 09:08:25 -07003299 audio_session_t session = client->session();
3300
Eric Laurent4eb58f12018-12-07 16:41:02 -08003301 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003302
Eric Laurent4eb58f12018-12-07 16:41:02 -08003303 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003304
Eric Laurent4eb58f12018-12-07 16:41:02 -08003305 status_t status = inputDesc->start();
3306 if (status != NO_ERROR) {
3307 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003308 }
Eric Laurente552edb2014-03-10 17:42:56 -07003309
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003310 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003311 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003312 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003313
Eric Laurent8f42ea12018-08-08 09:08:25 -07003314 // indicate active capture to sound trigger service if starting capture from a mic on
3315 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003316 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003317 if (device != nullptr) {
3318 status = setInputDevice(input, device, true /* force */);
3319 } else {
3320 ALOGW("%s no new input device can be found for descriptor %d",
3321 __FUNCTION__, inputDesc->getId());
3322 status = BAD_VALUE;
3323 }
Eric Laurente552edb2014-03-10 17:42:56 -07003324
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003325 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003326 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003327 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003328 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003329 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3330 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003331 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003332 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003333
François Gaffie11d30102018-11-02 16:09:09 +01003334 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3335 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003336 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003337 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003338 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003339
Eric Laurent8f42ea12018-08-08 09:08:25 -07003340 // automatically enable the remote submix output when input is started if not
3341 // used by a policy mix of type MIX_TYPE_RECORDERS
3342 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003343 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003344 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003345 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003346 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003347 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3348 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003349 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003350 if (address != "") {
3351 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3352 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003353 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003354 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003355 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003356 } else if (status != NO_ERROR) {
3357 // Restore client activity state.
3358 inputDesc->setClientActive(client, false);
3359 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003360 }
3361
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003362 ALOGV("%s input %d source = %d status = %d exit",
3363 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003364
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003365 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003366}
3367
Eric Laurent8fc147b2018-07-22 19:13:55 -07003368status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003369{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003370 ALOGV("%s portId %d", __FUNCTION__, portId);
3371
3372 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3373 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003374 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003375 return BAD_VALUE;
3376 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003377 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003378 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003379 if (!client->active()) {
3380 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003381 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003382 }
Carter Hsue6139d52021-07-08 10:30:20 +08003383 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003384 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003385
Eric Laurent8f42ea12018-08-08 09:08:25 -07003386 inputDesc->stop();
3387 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003388 auto current_source = inputDesc->source();
3389 setInputDevice(input, getNewInputDevice(inputDesc),
3390 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003391 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003392 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003393 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003394 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003395 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3396 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003397 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003398 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003399
3400 // automatically disable the remote submix output when input is stopped if not
3401 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003402 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003403 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003404 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003405 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003406 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3407 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003408 }
3409 if (address != "") {
3410 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3411 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003412 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003413 }
3414 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003415 resetInputDevice(input);
3416
3417 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3418 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003419 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3420 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003421 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003422 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003423 }
3424 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003425 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003426 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003427}
3428
Eric Laurent8fc147b2018-07-22 19:13:55 -07003429void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003430{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003431 ALOGV("%s portId %d", __FUNCTION__, portId);
3432
3433 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3434 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003435 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003436 return;
3437 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003438 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003439 audio_io_handle_t input = inputDesc->mIoHandle;
3440
Eric Laurent8f42ea12018-08-08 09:08:25 -07003441 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003442
Andy Hung39efb7a2018-09-26 15:39:28 -07003443 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003444
3445 // If no more clients are present in this session, park effects to an orphan chain
3446 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3447 if (clientsOnSession.size() == 0) {
3448 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3449 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003450 if (inputDesc->getClientCount() > 0) {
3451 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003452 return;
3453 }
3454
Eric Laurent05b90f82014-08-27 15:32:29 -07003455 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003456 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003457 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003458}
3459
Eric Laurent8f42ea12018-08-08 09:08:25 -07003460void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003461{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003462 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003463
3464 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003465 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003466 }
3467}
3468
Eric Laurent8f42ea12018-08-08 09:08:25 -07003469void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3470{
3471 stopInput(portId);
3472 releaseInput(portId);
3473}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003474
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003475bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3476 if (input->clientsList().size() == 0
3477 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3478 return true;
3479 }
3480 for (const auto& client : input->clientsList()) {
3481 sp<DeviceDescriptor> device =
3482 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3483 client->session());
3484 if (!input->supportedDevices().contains(device)) {
3485 return true;
3486 }
3487 }
3488 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3489 return false;
3490}
3491
Eric Laurent0dd51852019-04-19 18:18:58 -07003492void AudioPolicyManager::checkCloseInputs() {
3493 // After connecting or disconnecting an input device, close input if:
3494 // - it has no client (was just opened to check profile) OR
3495 // - none of its supported devices are connected anymore OR
3496 // - one of its clients cannot be routed to one of its supported
3497 // devices anymore. Otherwise update device selection
3498 std::vector<audio_io_handle_t> inputsToClose;
3499 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003500 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003501 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003502 }
3503 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003504 for (const audio_io_handle_t handle : inputsToClose) {
3505 ALOGV("%s closing input %d", __func__, handle);
3506 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003507 }
Eric Laurentd4692962014-05-05 18:13:44 -07003508}
3509
Vlad Popa87e0e582024-05-20 18:49:20 -07003510status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3511 const char *address __unused,
3512 bool enabled,
3513 audio_stream_type_t streamToDriveAbs)
3514{
Vlad Popaa536eb32024-07-18 16:00:35 -07003515 if (!enabled) {
3516 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3517 return NO_ERROR;
3518 }
3519
Vlad Popa87e0e582024-05-20 18:49:20 -07003520 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3521 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3522 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3523 toString(streamToDriveAbs).c_str());
3524 return BAD_VALUE;
3525 }
3526
Vlad Popaa536eb32024-07-18 16:00:35 -07003527 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003528 return NO_ERROR;
3529}
3530
François Gaffie251c7f02018-11-07 10:41:08 +01003531void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003532{
3533 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003534 if (indexMin < 0 || indexMax < 0) {
3535 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3536 return;
3537 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003538 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003539
3540 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003541 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3542 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003543 continue;
3544 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003545 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003546 }
Eric Laurente552edb2014-03-10 17:42:56 -07003547}
3548
Eric Laurente0720872014-03-11 09:30:41 -07003549status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003550 int index,
3551 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003552{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003553 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003554 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3555 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3556 return NO_ERROR;
3557 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303558 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3559 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003560 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003561}
3562
Eric Laurente0720872014-03-11 09:30:41 -07003563status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003564 int *index,
3565 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003566{
François Gaffiec005e562018-11-06 15:04:49 +01003567 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3568 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003569 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003570 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003571 deviceTypes = mEngine->getOutputDevicesForStream(
3572 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003573 }
jiabin9a3361e2019-10-01 09:38:30 -07003574 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003575}
3576
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003577status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003578 int index,
3579 audio_devices_t device)
3580{
3581 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003582 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3583 if (group == VOLUME_GROUP_NONE) {
3584 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003585 return BAD_VALUE;
3586 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003587 ALOGV("%s: group %d matching with %s index %d",
3588 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003589 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003590 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003591 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003592 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3593 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3594 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3595 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003596 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3597
3598 status = setVolumeCurveIndex(index, device, curves);
3599 if (status != NO_ERROR) {
3600 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3601 return status;
3602 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003603
jiabin9a3361e2019-10-01 09:38:30 -07003604 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003605 auto curCurvAttrs = curves.getAttributes();
3606 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3607 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003608 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003609 } else if (!curves.getStreamTypes().empty()) {
3610 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003611 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003612 } else {
3613 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3614 return BAD_VALUE;
3615 }
jiabin9a3361e2019-10-01 09:38:30 -07003616 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3617 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003618
François Gaffiecfe17322018-11-07 13:41:29 +01003619 // update volume on all outputs and streams matching the following:
3620 // - The requested stream (or a stream matching for volume control) is active on the output
3621 // - The device (or devices) selected by the engine for this stream includes
3622 // the requested device
3623 // - For non default requested device, currently selected device on the output is either the
3624 // requested device or one of the devices selected by the engine for this stream
3625 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3626 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003627 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003628 for (size_t i = 0; i < mOutputs.size(); i++) {
3629 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003630 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003631
jiabin9a3361e2019-10-01 09:38:30 -07003632 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3633 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003634 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003635
3636 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003637 continue;
3638 }
3639 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3640 curDevices.find(device) == curDevices.end()) {
3641 continue;
3642 }
3643 bool applyVolume = false;
3644 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3645 curSrcDevices.insert(device);
3646 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003647 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3648 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003649 } else {
3650 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3651 }
3652 if (!applyVolume) {
3653 continue; // next output
3654 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003655 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3656 // If a higher priority strategy is active, and the output is routed to a device with a
3657 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003658 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003659 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003660 // If the volume source is active with higher priority source, ensure at least Sw Muted
3661 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003662 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3663 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3664 false /*preferredDevice*/);
3665 if (activeClients.empty()) {
3666 continue;
3667 }
3668 bool isPreempted = false;
3669 bool isHigherPriority = productStrategy < strategy;
3670 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003671 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003672 ALOGV("%s: Strategy=%d (\nrequester:\n"
3673 " group %d, volumeGroup=%d attributes=%s)\n"
3674 " higher priority source active:\n"
3675 " volumeGroup=%d attributes=%s) \n"
3676 " on output %zu, bailing out", __func__, productStrategy,
3677 group, group, toString(attributes).c_str(),
3678 client->volumeSource(), toString(client->attributes()).c_str(), i);
3679 applyVolume = false;
3680 isPreempted = true;
3681 break;
3682 }
3683 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003684 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003685 applyVolume = true;
3686 }
3687 }
3688 if (isPreempted || applyVolume) {
3689 break;
3690 }
3691 }
3692 if (!applyVolume) {
3693 continue; // next output
3694 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003695 }
François Gaffieed91f582020-01-31 10:35:37 +01003696 //FIXME: workaround for truncated touch sounds
3697 // delayed volume change for system stream to be removed when the problem is
3698 // handled by system UI
3699 status_t volStatus = checkAndSetVolume(
3700 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003701 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003702 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3703 if (volStatus != NO_ERROR) {
3704 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003705 }
3706 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003707
3708 // update voice volume if the an active call route exists
3709 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3710 && (curSrcDevices.find(
3711 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3712 != curSrcDevices.end())) {
3713 bool isVoiceVolSrc;
3714 bool isBtScoVolSrc;
3715 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3716 isVoiceVolSrc, isBtScoVolSrc, __func__)
3717 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003718 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3719 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3720 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003721 }
3722 }
3723
François Gaffiecfe17322018-11-07 13:41:29 +01003724 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3725 return status;
3726}
3727
François Gaffieaaac0fd2018-11-22 17:56:39 +01003728status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003729 audio_devices_t device,
3730 IVolumeCurves &volumeCurves)
3731{
3732 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3733 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003734 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3735 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003736 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303737 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3738 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003739 return BAD_VALUE;
3740 }
3741 if (!audio_is_output_device(device)) {
3742 return BAD_VALUE;
3743 }
3744
3745 // Force max volume if stream cannot be muted
3746 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3747
François Gaffieaaac0fd2018-11-22 17:56:39 +01003748 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003749 volumeCurves.addCurrentVolumeIndex(device, index);
3750 return NO_ERROR;
3751}
3752
3753status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3754 int &index,
3755 audio_devices_t device)
3756{
3757 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3758 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003759 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003760 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003761 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003762 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003763 }
jiabin9a3361e2019-10-01 09:38:30 -07003764 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003765}
3766
3767status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3768 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003769 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003770{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003771 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003772 return BAD_VALUE;
3773 }
jiabin9a3361e2019-10-01 09:38:30 -07003774 index = curves.getVolumeIndex(deviceTypes);
3775 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003776 return NO_ERROR;
3777}
3778
3779status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3780 int &index)
3781{
3782 index = getVolumeCurves(attr).getVolumeIndexMin();
3783 return NO_ERROR;
3784}
3785
3786status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3787 int &index)
3788{
3789 index = getVolumeCurves(attr).getVolumeIndexMax();
3790 return NO_ERROR;
3791}
3792
Eric Laurent36829f92017-04-07 19:04:42 -07003793audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003794{
3795 // select one output among several suitable for global effects.
3796 // The priority is as follows:
3797 // 1: An offloaded output. If the effect ends up not being offloadable,
3798 // AudioFlinger will invalidate the track and the offloaded output
3799 // will be closed causing the effect to be moved to a PCM output.
3800 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003801 // 3: The primary output
3802 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003803
François Gaffiec005e562018-11-06 15:04:49 +01003804 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3805 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003806 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003807
Eric Laurent36829f92017-04-07 19:04:42 -07003808 if (outputs.size() == 0) {
3809 return AUDIO_IO_HANDLE_NONE;
3810 }
Eric Laurente552edb2014-03-10 17:42:56 -07003811
Eric Laurent36829f92017-04-07 19:04:42 -07003812 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3813 bool activeOnly = true;
3814
3815 while (output == AUDIO_IO_HANDLE_NONE) {
3816 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3817 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3818 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3819
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003820 for (audio_io_handle_t output : outputs) {
3821 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003822 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003823 continue;
3824 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003825 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3826 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003827 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003828 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003829 }
3830 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003831 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003832 }
3833 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003834 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003835 }
3836 }
3837 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3838 output = outputOffloaded;
3839 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3840 output = outputDeepBuffer;
3841 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3842 output = outputPrimary;
3843 } else {
3844 output = outputs[0];
3845 }
3846 activeOnly = false;
3847 }
3848
3849 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003850 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3851 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003852 mMusicEffectOutput = output;
3853 }
3854
3855 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003856 return output;
3857}
3858
Eric Laurent36829f92017-04-07 19:04:42 -07003859audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3860{
3861 return selectOutputForMusicEffects();
3862}
3863
Eric Laurente0720872014-03-11 09:30:41 -07003864status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003865 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003866 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003867 int session,
3868 int id)
3869{
Shunkai Yao29d10572024-03-19 04:31:47 +00003870 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003871 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003872 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003873 index = mInputs.indexOfKey(io);
3874 if (index < 0) {
3875 ALOGW("registerEffect() unknown io %d", io);
3876 return INVALID_OPERATION;
3877 }
Eric Laurente552edb2014-03-10 17:42:56 -07003878 }
3879 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003880 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3881 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3882 || strategy == PRODUCT_STRATEGY_NONE));
3883 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003884}
3885
Eric Laurentc241b0d2018-11-28 09:08:49 -08003886status_t AudioPolicyManager::unregisterEffect(int id)
3887{
3888 if (mEffects.getEffect(id) == nullptr) {
3889 return INVALID_OPERATION;
3890 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003891 if (mEffects.isEffectEnabled(id)) {
3892 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3893 setEffectEnabled(id, false);
3894 }
3895 return mEffects.unregisterEffect(id);
3896}
3897
3898status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3899{
3900 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3901 if (effect == nullptr) {
3902 return INVALID_OPERATION;
3903 }
3904
3905 status_t status = mEffects.setEffectEnabled(id, enabled);
3906 if (status == NO_ERROR) {
3907 mInputs.trackEffectEnabled(effect, enabled);
3908 }
3909 return status;
3910}
3911
Eric Laurent6c796322019-04-09 14:13:17 -07003912
3913status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3914{
3915 mEffects.moveEffects(ids, io);
3916 return NO_ERROR;
3917}
3918
Eric Laurentc75307b2015-03-17 15:29:32 -07003919bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3920{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003921 auto vs = toVolumeSource(stream, false);
3922 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003923}
3924
3925bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3926{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003927 auto vs = toVolumeSource(stream, false);
3928 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003929}
3930
Eric Laurente0720872014-03-11 09:30:41 -07003931bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003932{
3933 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003934 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003935 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003936 return true;
3937 }
3938 }
3939 return false;
3940}
3941
Eric Laurent275e8e92014-11-30 15:14:47 -08003942// Register a list of custom mixes with their attributes and format.
3943// When a mix is registered, corresponding input and output profiles are
3944// added to the remote submix hw module. The profile contains only the
3945// parameters (sampling rate, format...) specified by the mix.
3946// The corresponding input remote submix device is also connected.
3947//
3948// When a remote submix device is connected, the address is checked to select the
3949// appropriate profile and the corresponding input or output stream is opened.
3950//
3951// When capture starts, getInputForAttr() will:
3952// - 1 look for a mix matching the address passed in attribtutes tags if any
3953// - 2 if none found, getDeviceForInputSource() will:
3954// - 2.1 look for a mix matching the attributes source
3955// - 2.2 if none found, default to device selection by policy rules
3956// At this time, the corresponding output remote submix device is also connected
3957// and active playback use cases can be transferred to this mix if needed when reconnecting
3958// after AudioTracks are invalidated
3959//
3960// When playback starts, getOutputForAttr() will:
3961// - 1 look for a mix matching the address passed in attribtutes tags if any
3962// - 2 if none found, look for a mix matching the attributes usage
3963// - 3 if none found, default to device and output selection by policy rules.
3964
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003965status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003966{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003967 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3968 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003969 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003970 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003971 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003972 // examine each mix's route type
3973 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003974 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003975 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3976 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3977 ALOGE("Unsupported Policy Mix %zu of %zu: "
3978 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3979 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003980 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003981 break;
3982 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003983 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3984 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003985 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003986 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3987 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003988 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003989 rSubmixModule = mHwModules.getModuleFromName(
3990 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3991 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003992 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003993 i);
3994 res = INVALID_OPERATION;
3995 break;
3996 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003997 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003998
Eric Laurent97ac8712018-07-27 18:59:02 -07003999 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004000 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004001 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004002 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004003 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4004 } else {
4005 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4006 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004007 }
François Gaffie036e1e92015-03-19 10:16:24 +01004008
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004009 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004010 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004011 res = INVALID_OPERATION;
4012 break;
4013 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004014 audio_config_t outputConfig = mix.mFormat;
4015 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004016 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4017 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004018 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4019 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004020 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004021 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4022 audio_is_linear_pcm(outputConfig.format)
4023 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004024 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004025 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4026 audio_is_linear_pcm(inputConfig.format)
4027 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004028
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004029 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004030 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004031 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004032 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004033 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004034 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004035 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004036 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4037 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004038 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004039 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004040 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004041
4042 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4043 mix.mDeviceType, mix.mDeviceAddress,
4044 String8(), AUDIO_FORMAT_DEFAULT);
4045 if (device == nullptr) {
4046 res = INVALID_OPERATION;
4047 break;
4048 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004049
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004050 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004051 // First try to find an already opened output supporting the device
4052 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004053 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004054
Eric Laurentc529cf62020-04-17 18:19:10 -07004055 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004056 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004057 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004058 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004059 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004060 } else {
4061 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004062 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004063 }
4064 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004065 // If no output found, try to find a direct output profile supporting the device
4066 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4067 sp<HwModule> module = mHwModules[i];
4068 for (size_t j = 0;
4069 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4070 j++) {
4071 sp<IOProfile> profile = module->getOutputProfiles()[j];
4072 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4073 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4074 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004075 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004076 res = INVALID_OPERATION;
4077 } else {
4078 foundOutput = true;
4079 }
4080 }
4081 }
4082 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004083 if (res != NO_ERROR) {
4084 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004085 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004086 res = INVALID_OPERATION;
4087 break;
4088 } else if (!foundOutput) {
4089 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004090 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004091 res = INVALID_OPERATION;
4092 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004093 } else {
4094 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004095 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004096 }
Eric Laurentc722f302014-12-10 11:21:49 -08004097 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004098 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004099 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004100 if (audio_flags::audio_mix_ownership()) {
4101 // Only unregister mixes that were actually registered to not accidentally unregister
4102 // mixes that already existed previously.
4103 unregisterPolicyMixes(registeredMixes);
4104 registeredMixes.clear();
4105 } else {
4106 unregisterPolicyMixes(mixes);
4107 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004108 } else if (checkOutputs) {
4109 checkForDeviceAndOutputChanges();
4110 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004111 }
4112 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004113}
4114
4115status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4116{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004117 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004118 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004119 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004120 sp<HwModule> rSubmixModule;
4121 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004122 for (const auto& mix : mixes) {
4123 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004124
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004125 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004126 rSubmixModule = mHwModules.getModuleFromName(
4127 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4128 if (rSubmixModule == 0) {
4129 res = INVALID_OPERATION;
4130 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004131 }
4132 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004133
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004134 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004135
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004136 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004137 res = INVALID_OPERATION;
4138 continue;
4139 }
4140
Marvin Ramin0783e202024-03-05 12:45:50 +01004141 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004142 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004143 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4144 status_t currentRes =
4145 setDeviceConnectionStateInt(device,
4146 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4147 address.c_str(),
4148 "remote-submix",
4149 AUDIO_FORMAT_DEFAULT);
4150 if (!audio_flags::audio_mix_ownership()) {
4151 res = currentRes;
4152 }
4153 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004154 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004155 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004156 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004157 }
4158 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004159 }
jiabin5740f082019-08-19 15:08:30 -07004160 rSubmixModule->removeOutputProfile(address.c_str());
4161 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004162
Kevin Rocard153f92d2018-12-18 18:33:28 -08004163 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004164 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004165 res = INVALID_OPERATION;
4166 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004167 } else {
4168 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004169 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004170 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004171 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004172
4173 if (res == NO_ERROR && checkOutputs) {
4174 checkForDeviceAndOutputChanges();
4175 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004176 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004177 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004178}
4179
Marvin Raminbdefaf02023-11-01 09:10:32 +01004180status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4181 if (!audio_flags::audio_mix_test_api()) {
4182 return INVALID_OPERATION;
4183 }
4184
4185 _aidl_return.clear();
4186 _aidl_return.reserve(mPolicyMixes.size());
4187 for (const auto &policyMix: mPolicyMixes) {
4188 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4189 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4190 policyMix->mCbFlags);
4191 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004192 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004193 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004194 }
4195
Vlad Popaa5d73f32024-03-08 16:05:38 -08004196 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004197 return OK;
4198}
4199
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004200status_t AudioPolicyManager::updatePolicyMix(
4201 const AudioMix& mix,
4202 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4203 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4204 if (res == NO_ERROR) {
4205 checkForDeviceAndOutputChanges();
4206 updateCallAndOutputRouting();
4207 }
4208 return res;
4209}
4210
Mikhail Naganov100f0122018-11-29 11:22:16 -08004211void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4212{
4213 size_t i = 0;
4214 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4215 for (const auto& fmt : mManualSurroundFormats) {
4216 if (i++ != 0) dst->append(", ");
4217 std::string sfmt;
4218 FormatConverter::toString(fmt, sfmt);
4219 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4220 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4221 }
4222}
4223
Eric Laurentc529cf62020-04-17 18:19:10 -07004224// Returns true if all devices types match the predicate and are supported by one HW module
4225bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004226 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004227 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004228 const char *context,
4229 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004230 for (size_t i = 0; i < devices.size(); i++) {
4231 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004232 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004233 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004234 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004235 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004236 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004237 return false;
4238 }
4239 }
4240 return true;
4241}
4242
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004243void AudioPolicyManager::changeOutputDevicesMuteState(
4244 const AudioDeviceTypeAddrVector& devices) {
4245 ALOGVV("%s() num devices %zu", __func__, devices.size());
4246
4247 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4248 getSoftwareOutputsForDevices(devices);
4249
4250 for (size_t i = 0; i < outputs.size(); i++) {
4251 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4252 DeviceVector prevDevices = outputDesc->devices();
4253 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4254 }
4255}
4256
4257std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4258 const AudioDeviceTypeAddrVector& devices) const
4259{
4260 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4261 DeviceVector deviceDescriptors;
4262 for (size_t j = 0; j < devices.size(); j++) {
4263 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4264 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4265 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4266 ALOGE("%s: device type %#x address %s not supported or not an output device",
4267 __func__, devices[j].mType, devices[j].getAddress());
4268 continue;
4269 }
4270 deviceDescriptors.add(desc);
4271 }
4272 for (size_t i = 0; i < mOutputs.size(); i++) {
4273 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4274 continue;
4275 }
4276 outputs.push_back(mOutputs.valueAt(i));
4277 }
4278 return outputs;
4279}
4280
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004281status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004282 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004283 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004284 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4285 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004286 }
4287 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004288 if (res != NO_ERROR) {
4289 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4290 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004291 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004292
4293 checkForDeviceAndOutputChanges();
4294 updateCallAndOutputRouting();
4295
4296 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004297}
4298
4299status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4300 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004301 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4302 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004303 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004304 __FUNCTION__, uid);
4305 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004306 }
4307
Eric Laurentc529cf62020-04-17 18:19:10 -07004308 checkForDeviceAndOutputChanges();
4309 updateCallAndOutputRouting();
4310
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004311 return res;
4312}
4313
Eric Laurent2517af32020-11-25 15:31:27 +01004314
jiabin0a488932020-08-07 17:32:40 -07004315status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4316 device_role_t role,
4317 const AudioDeviceTypeAddrVector &devices) {
4318 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4319 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004320
Eric Laurentc529cf62020-04-17 18:19:10 -07004321 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004322 return BAD_VALUE;
4323 }
jiabin0a488932020-08-07 17:32:40 -07004324 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004325 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004326 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4327 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004328 return status;
4329 }
4330
4331 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004332
4333 bool forceVolumeReeval = false;
4334 // FIXME: workaround for truncated touch sounds
4335 // to be removed when the problem is handled by system UI
4336 uint32_t delayMs = 0;
4337 if (strategy == mCommunnicationStrategy) {
4338 forceVolumeReeval = true;
4339 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4340 updateInputRouting();
4341 }
4342 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004343
4344 return NO_ERROR;
4345}
4346
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004347void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4348 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004349{
4350 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004351 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004352 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004353 // Only apply special touch sound delay once
4354 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004355 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004356 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004357 for (size_t i = 0; i < mOutputs.size(); i++) {
4358 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4359 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004360 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4361 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004362 // As done in setDeviceConnectionState, we could also fix default device issue by
4363 // preventing the force re-routing in case of default dev that distinguishes on address.
4364 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004365 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004366 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004367 // If the device is using preferred mixer attributes, the output need to reopen
4368 // with default configuration when the new selected devices are different from
4369 // current routing devices.
4370 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4371 continue;
4372 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304373
4374 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4375 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004376 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004377 // Only apply special touch sound delay once
4378 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004379 }
4380 if (forceVolumeReeval && !newDevices.isEmpty()) {
4381 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4382 }
4383 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004384 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004385 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004386}
4387
Eric Laurent2517af32020-11-25 15:31:27 +01004388void AudioPolicyManager::updateInputRouting() {
4389 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304390 // Skip for hotword recording as the input device switch
4391 // is handled within sound trigger HAL
4392 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4393 continue;
4394 }
Eric Laurent2517af32020-11-25 15:31:27 +01004395 auto newDevice = getNewInputDevice(activeDesc);
4396 // Force new input selection if the new device can not be reached via current input
4397 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4398 setInputDevice(activeDesc->mIoHandle, newDevice);
4399 } else {
4400 closeInput(activeDesc->mIoHandle);
4401 }
4402 }
4403}
4404
Paul Wang5d7cdb52022-11-22 09:45:06 +00004405status_t
4406AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4407 device_role_t role,
4408 const AudioDeviceTypeAddrVector &devices) {
4409 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4410 dumpAudioDeviceTypeAddrVector(devices).c_str());
4411
Eric Laurent78fedbf2023-03-09 14:40:44 +01004412 if (!areAllDevicesSupported(
4413 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004414 return BAD_VALUE;
4415 }
4416 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4417 if (status != NO_ERROR) {
4418 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4419 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4420 return status;
4421 }
4422
4423 checkForDeviceAndOutputChanges();
4424
4425 bool forceVolumeReeval = false;
4426 // TODO(b/263479999): workaround for truncated touch sounds
4427 // to be removed when the problem is handled by system UI
4428 uint32_t delayMs = 0;
4429 if (strategy == mCommunnicationStrategy) {
4430 forceVolumeReeval = true;
4431 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4432 updateInputRouting();
4433 }
4434 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4435
4436 return NO_ERROR;
4437}
4438
4439status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4440 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004441{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004442 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004443
Paul Wang5d7cdb52022-11-22 09:45:06 +00004444 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004445 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004446 ALOGW_IF(status != NAME_NOT_FOUND,
4447 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004448 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004449 return status;
4450 }
4451
4452 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004453
4454 bool forceVolumeReeval = false;
4455 // FIXME: workaround for truncated touch sounds
4456 // to be removed when the problem is handled by system UI
4457 uint32_t delayMs = 0;
4458 if (strategy == mCommunnicationStrategy) {
4459 forceVolumeReeval = true;
4460 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4461 updateInputRouting();
4462 }
4463 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004464
4465 return NO_ERROR;
4466}
4467
jiabin0a488932020-08-07 17:32:40 -07004468status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4469 device_role_t role,
4470 AudioDeviceTypeAddrVector &devices) {
4471 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004472}
4473
Jiabin Huang3b98d322020-09-03 17:54:16 +00004474status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
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->setDevicesRoleForCapturePreset(audioSource, role, devices);
4483 ALOGW_IF(status != NO_ERROR,
4484 "Engine could not set preferred devices %s for audio source %d role %d",
4485 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4486
4487 return status;
4488}
4489
4490status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4491 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4492 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4493 dumpAudioDeviceTypeAddrVector(devices).c_str());
4494
Mikhail Naganov55773032020-10-01 15:08:13 -07004495 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004496 return BAD_VALUE;
4497 }
4498 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4499 ALOGW_IF(status != NO_ERROR,
4500 "Engine could not add preferred devices %s for audio source %d role %d",
4501 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4502
Eric Laurent2517af32020-11-25 15:31:27 +01004503 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004504 return status;
4505}
4506
4507status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4508 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4509{
4510 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4511 dumpAudioDeviceTypeAddrVector(devices).c_str());
4512
Eric Laurent78fedbf2023-03-09 14:40:44 +01004513 if (!areAllDevicesSupported(
4514 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004515 return BAD_VALUE;
4516 }
4517
4518 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4519 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004520 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004521 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004522 if (status == NO_ERROR) {
4523 updateInputRouting();
4524 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004525 return status;
4526}
4527
4528status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4529 device_role_t role) {
4530 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4531
4532 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004533 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004534 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004535 if (status == NO_ERROR) {
4536 updateInputRouting();
4537 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004538 return status;
4539}
4540
4541status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4542 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4543 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4544}
4545
Oscar Azucena90e77632019-11-27 17:12:28 -08004546status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004547 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004548 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004549 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4550 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004551 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004552 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4553 if (status != NO_ERROR) {
4554 ALOGE("%s() could not set device affinity for userId %d",
4555 __FUNCTION__, userId);
4556 return status;
4557 }
4558
4559 // reevaluate outputs for all devices
4560 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004561 changeOutputDevicesMuteState(devices);
4562 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4563 true /* skipDelays */);
4564 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004565
4566 return NO_ERROR;
4567}
4568
4569status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004570 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004571 AudioDeviceTypeAddrVector devices;
4572 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004573 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4574 if (status != NO_ERROR) {
4575 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4576 __FUNCTION__, userId);
4577 return status;
4578 }
4579
4580 // reevaluate outputs for all devices
4581 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004582 changeOutputDevicesMuteState(devices);
4583 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4584 true /* skipDelays */);
4585 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004586
4587 return NO_ERROR;
4588}
4589
Andy Hungc29d82b2018-10-05 12:23:17 -07004590void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004591{
Andy Hungc29d82b2018-10-05 12:23:17 -07004592 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004593 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004594 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004595 std::string stateLiteral;
4596 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004597 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004598 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4599 "communications", "media", "record", "dock", "system",
4600 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4601 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4602 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004603 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4604 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4605 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4606 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4607 dst->append(" (MANUAL: ");
4608 dumpManualSurroundFormats(dst);
4609 dst->append(")");
4610 }
4611 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004612 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004613 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4614 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004615 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004616 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004617
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004618 dst->append("\n");
4619 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4620 dst->append("\n");
4621 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004622 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004623 mOutputs.dump(dst);
4624 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004625 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004626 mAudioPatches.dump(dst);
4627 mPolicyMixes.dump(dst);
4628 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004629
Kevin Rocardb99cc752019-03-21 20:52:24 -07004630 dst->appendFormat(" AllowedCapturePolicies:\n");
4631 for (auto& policy : mAllowedCapturePolicies) {
4632 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4633 }
4634
jiabina84c3d32022-12-02 18:59:55 +00004635 dst->appendFormat(" Preferred mixer audio configuration:\n");
4636 for (const auto it : mPreferredMixerAttrInfos) {
4637 dst->appendFormat(" - device port id: %d\n", it.first);
4638 for (const auto preferredMixerInfoIt : it.second) {
4639 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4640 preferredMixerInfoIt.second->dump(dst);
4641 }
4642 }
4643
François Gaffiec005e562018-11-06 15:04:49 +01004644 dst->appendFormat("\nPolicy Engine dump:\n");
4645 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004646
4647 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4648 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4649 dst->appendFormat(" - device type: %s, driving stream %d\n",
4650 dumpDeviceTypes({it.first}).c_str(),
4651 mEngine->getVolumeGroupForAttributes(it.second));
4652 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004653}
4654
4655status_t AudioPolicyManager::dump(int fd)
4656{
4657 String8 result;
4658 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004659 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004660 return NO_ERROR;
4661}
4662
Kevin Rocardb99cc752019-03-21 20:52:24 -07004663status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4664{
4665 mAllowedCapturePolicies[uid] = capturePolicy;
4666 return NO_ERROR;
4667}
4668
Eric Laurente552edb2014-03-10 17:42:56 -07004669// This function checks for the parameters which can be offloaded.
4670// This can be enhanced depending on the capability of the DSP and policy
4671// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004672audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004673{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004674 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004675 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004676 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004677 offloadInfo.format,
4678 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4679 offloadInfo.has_video);
4680
jiabin2b9d5a12021-12-10 01:06:29 +00004681 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004682 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004683 }
4684
4685 // See if there is a profile to support this.
4686 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004687 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004688 offloadInfo.sample_rate,
4689 offloadInfo.format,
4690 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004691 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4692 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004693 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4694 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4695 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004696 if (profile == nullptr) {
4697 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4698 }
4699 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4700 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4701 }
4702 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004703}
4704
Michael Chana94fbb22018-04-24 14:31:19 +10004705bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4706 const audio_attributes_t& attributes) {
4707 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004708 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004709 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4710 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004711 config.sample_rate,
4712 config.format,
4713 config.channel_mask,
4714 output_flags,
4715 true /* directOnly */);
4716 ALOGV("%s() profile %sfound with name: %s, "
4717 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4718 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004719 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004720 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004721
4722 // also try the MSD module if compatible profile not found
4723 if (profile == nullptr) {
4724 profile = getMsdProfileForOutput(outputDevices,
4725 config.sample_rate,
4726 config.format,
4727 config.channel_mask,
4728 output_flags,
4729 true /* directOnly */);
4730 ALOGV("%s() MSD profile %sfound with name: %s, "
4731 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4732 __FUNCTION__, profile != 0 ? "" : "NOT ",
4733 (profile != 0 ? profile->getTagName().c_str() : "null"),
4734 config.sample_rate, config.format, config.channel_mask, output_flags);
4735 }
4736 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004737}
4738
jiabin2b9d5a12021-12-10 01:06:29 +00004739bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4740 bool durationIgnored) {
4741 if (mMasterMono) {
4742 return false; // no offloading if mono is set.
4743 }
4744
4745 // Check if offload has been disabled
4746 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4747 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4748 return false;
4749 }
4750
4751 // Check if stream type is music, then only allow offload as of now.
4752 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4753 {
4754 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4755 return false;
4756 }
4757
4758 //TODO: enable audio offloading with video when ready
4759 const bool allowOffloadWithVideo =
4760 property_get_bool("audio.offload.video", false /* default_value */);
4761 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4762 ALOGV("%s: has_video == true, returning false", __func__);
4763 return false;
4764 }
4765
4766 //If duration is less than minimum value defined in property, return false
4767 const int min_duration_secs = property_get_int32(
4768 "audio.offload.min.duration.secs", -1 /* default_value */);
4769 if (!durationIgnored) {
4770 if (min_duration_secs >= 0) {
4771 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4772 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4773 __func__, min_duration_secs);
4774 return false;
4775 }
4776 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4777 ALOGV("%s: Offload denied by duration < default min(=%u)",
4778 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4779 return false;
4780 }
4781 }
4782
4783 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4784 // creating an offloaded track and tearing it down immediately after start when audioflinger
4785 // detects there is an active non offloadable effect.
4786 // FIXME: We should check the audio session here but we do not have it in this context.
4787 // This may prevent offloading in rare situations where effects are left active by apps
4788 // in the background.
4789 if (mEffects.isNonOffloadableEffectEnabled()) {
4790 return false;
4791 }
4792
4793 return true;
4794}
4795
4796audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4797 const audio_config_t *config) {
4798 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4799 offloadInfo.format = config->format;
4800 offloadInfo.sample_rate = config->sample_rate;
4801 offloadInfo.channel_mask = config->channel_mask;
4802 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4803 offloadInfo.has_video = false;
4804 offloadInfo.is_streaming = false;
4805 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4806
4807 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4808 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4809 audio_flags_to_audio_output_flags(attr->flags, &flags);
4810 // only retain flags that will drive compressed offload or passthrough
4811 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4812 if (offloadPossible) {
4813 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4814 }
4815 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4816
Dorin Drimusfae3c642022-03-17 18:36:30 +01004817 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004818 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004819 DeviceVector outputDevices = engineOutputDevices;
4820 // the MSD module checks for different conditions and output devices
4821 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4822 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4823 continue;
4824 }
4825 outputDevices = getMsdAudioOutDevices();
4826 }
jiabin2b9d5a12021-12-10 01:06:29 +00004827 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004828 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004829 config->sample_rate, nullptr /*updatedSamplingRate*/,
4830 config->format, nullptr /*updatedFormat*/,
4831 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004832 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004833 continue;
4834 }
4835 // reject profiles not corresponding to a device currently available
4836 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4837 continue;
4838 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004839 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4840 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004841 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004842 != AUDIO_DIRECT_NOT_SUPPORTED) {
4843 // Already reports offload gapless supported. No need to report offload support.
4844 continue;
4845 }
4846 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4847 != AUDIO_OUTPUT_FLAG_NONE) {
4848 // If offload gapless is reported, no need to report offload support.
4849 directMode = (audio_direct_mode_t) ((directMode &
4850 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4851 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4852 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004853 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004854 }
4855 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004856 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004857 }
4858 }
4859 }
4860 return directMode;
4861}
4862
Dorin Drimusf2196d82022-01-03 12:11:18 +01004863status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4864 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004865 if (mEffects.isNonOffloadableEffectEnabled()) {
4866 return OK;
4867 }
jiabinf1c73972022-04-14 16:28:52 -07004868 DeviceVector devices;
4869 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004870 if (status != OK) {
4871 return status;
4872 }
4873 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4874 if (devices.empty()) {
4875 return OK; // no output devices for the attributes
4876 }
jiabinf1c73972022-04-14 16:28:52 -07004877 return getProfilesForDevices(devices, audioProfilesVector,
4878 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004879}
4880
jiabina84c3d32022-12-02 18:59:55 +00004881status_t AudioPolicyManager::getSupportedMixerAttributes(
4882 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4883 ALOGV("%s, portId=%d", __func__, portId);
4884 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4885 if (deviceDescriptor == nullptr) {
4886 ALOGE("%s the requested device is currently unavailable", __func__);
4887 return BAD_VALUE;
4888 }
jiabin96daffc2023-05-11 17:51:55 +00004889 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4890 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4891 deviceDescriptor->type());
4892 return BAD_VALUE;
4893 }
jiabina84c3d32022-12-02 18:59:55 +00004894 for (const auto& hwModule : mHwModules) {
4895 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4896 if (curProfile->supportsDevice(deviceDescriptor)) {
4897 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4898 }
4899 }
4900 }
4901 return NO_ERROR;
4902}
4903
4904status_t AudioPolicyManager::setPreferredMixerAttributes(
4905 const audio_attributes_t *attr,
4906 audio_port_handle_t portId,
4907 uid_t uid,
4908 const audio_mixer_attributes_t *mixerAttributes) {
4909 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4910 "mixerBehavior=%d}, uid=%d, portId=%u",
4911 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4912 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4913 mixerAttributes->mixer_behavior, uid, portId);
4914 if (attr->usage != AUDIO_USAGE_MEDIA) {
4915 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4916 return BAD_VALUE;
4917 }
4918 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4919 if (deviceDescriptor == nullptr) {
4920 ALOGE("%s the requested device is currently unavailable", __func__);
4921 return BAD_VALUE;
4922 }
4923 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4924 ALOGE("%s(%d), type=%d, is not a usb output device",
4925 __func__, portId, deviceDescriptor->type());
4926 return BAD_VALUE;
4927 }
4928
4929 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4930 audio_flags_to_audio_output_flags(attr->flags, &flags);
4931 flags = (audio_output_flags_t) (flags |
4932 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4933 sp<IOProfile> profile = nullptr;
4934 DeviceVector devices(deviceDescriptor);
4935 for (const auto& hwModule : mHwModules) {
4936 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4937 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004938 && curProfile->getCompatibilityScore(
4939 devices,
4940 mixerAttributes->config.sample_rate,
4941 nullptr /*updatedSamplingRate*/,
4942 mixerAttributes->config.format,
4943 nullptr /*updatedFormat*/,
4944 mixerAttributes->config.channel_mask,
4945 nullptr /*updatedChannelMask*/,
4946 flags,
4947 false /*exactMatchRequiredForInputFlags*/)
4948 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004949 profile = curProfile;
4950 break;
4951 }
4952 }
4953 }
4954 if (profile == nullptr) {
4955 ALOGE("%s, there is no compatible profile found", __func__);
4956 return BAD_VALUE;
4957 }
4958
4959 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4960 sp<PreferredMixerAttributesInfo>::make(
4961 uid, portId, profile, flags, *mixerAttributes);
4962 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4963 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4964
4965 // If 1) there is any client from the preferred mixer configuration owner that is currently
4966 // active and matches the strategy and 2) current output is on the preferred device and the
4967 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4968 // configuration.
4969 std::vector<audio_io_handle_t> outputsToReopen;
4970 for (size_t i = 0; i < mOutputs.size(); i++) {
4971 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004972 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4973 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004974 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004975 } else {
4976 for (const auto &client: output->getActiveClients()) {
4977 if (client->uid() == uid && client->strategy() == strategy) {
4978 client->setIsInvalid();
4979 outputsToReopen.push_back(output->mIoHandle);
4980 }
jiabina84c3d32022-12-02 18:59:55 +00004981 }
4982 }
4983 }
4984 }
4985 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4986 config.sample_rate = mixerAttributes->config.sample_rate;
4987 config.channel_mask = mixerAttributes->config.channel_mask;
4988 config.format = mixerAttributes->config.format;
4989 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004990 sp<SwAudioOutputDescriptor> desc =
4991 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4992 if (desc == nullptr) {
4993 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4994 continue;
4995 }
jiabin220eea12024-05-17 17:55:20 +00004996 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004997 }
4998
4999 return NO_ERROR;
5000}
5001
5002sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005003 audio_port_handle_t devicePortId,
5004 product_strategy_t strategy,
5005 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005006 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5007 if (it == mPreferredMixerAttrInfos.end()) {
5008 return nullptr;
5009 }
jiabind9a58d32023-06-01 17:57:30 +00005010 if (activeBitPerfectPreferred) {
5011 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005012 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005013 return info;
5014 }
5015 }
jiabina84c3d32022-12-02 18:59:55 +00005016 }
jiabind9a58d32023-06-01 17:57:30 +00005017 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5018 return strategyMatchedMixerAttrInfoIt == it->second.end()
5019 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005020}
5021
5022status_t AudioPolicyManager::getPreferredMixerAttributes(
5023 const audio_attributes_t *attr,
5024 audio_port_handle_t portId,
5025 audio_mixer_attributes_t* mixerAttributes) {
5026 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5027 portId, mEngine->getProductStrategyForAttributes(*attr));
5028 if (info == nullptr) {
5029 return NAME_NOT_FOUND;
5030 }
5031 *mixerAttributes = info->getMixerAttributes();
5032 return NO_ERROR;
5033}
5034
5035status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5036 audio_port_handle_t portId,
5037 uid_t uid) {
5038 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5039 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5040 if (preferredMixerAttrInfo == nullptr) {
5041 return NAME_NOT_FOUND;
5042 }
5043 if (preferredMixerAttrInfo->getUid() != uid) {
5044 ALOGE("%s, requested uid=%d, owned uid=%d",
5045 __func__, uid, preferredMixerAttrInfo->getUid());
5046 return PERMISSION_DENIED;
5047 }
5048 mPreferredMixerAttrInfos[portId].erase(strategy);
5049 if (mPreferredMixerAttrInfos[portId].empty()) {
5050 mPreferredMixerAttrInfos.erase(portId);
5051 }
5052
5053 // Reconfig existing output
5054 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5055 for (size_t i = 0; i < mOutputs.size(); i++) {
5056 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5057 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5058 }
5059 }
5060 for (const auto output : potentialOutputsToReopen) {
5061 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5062 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5063 preferredMixerAttrInfo->getFlags())) {
5064 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5065 }
5066 }
5067 return NO_ERROR;
5068}
5069
Eric Laurent6a94d692014-05-20 11:18:06 -07005070status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5071 audio_port_type_t type,
5072 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005073 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 unsigned int *generation)
5075{
jiabin19cdba52020-11-24 11:28:58 -08005076 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5077 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005078 return BAD_VALUE;
5079 }
5080 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005081 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005082 *num_ports = 0;
5083 }
5084
5085 size_t portsWritten = 0;
5086 size_t portsMax = *num_ports;
5087 *num_ports = 0;
5088 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005089 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5090 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005091 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005092 for (const auto& dev : mAvailableOutputDevices) {
5093 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005094 continue;
5095 }
5096 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005097 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005098 }
5099 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005100 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005101 }
5102 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005103 for (const auto& dev : mAvailableInputDevices) {
5104 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005105 continue;
5106 }
5107 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005108 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005109 }
5110 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005111 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005112 }
5113 }
5114 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5115 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5116 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5117 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5118 }
5119 *num_ports += mInputs.size();
5120 }
5121 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005122 size_t numOutputs = 0;
5123 for (size_t i = 0; i < mOutputs.size(); i++) {
5124 if (!mOutputs[i]->isDuplicated()) {
5125 numOutputs++;
5126 if (portsWritten < portsMax) {
5127 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5128 }
5129 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005130 }
Eric Laurent84c70242014-06-23 08:46:27 -07005131 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005132 }
5133 }
jiabina84c3d32022-12-02 18:59:55 +00005134
Eric Laurent6a94d692014-05-20 11:18:06 -07005135 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005136 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005137 return NO_ERROR;
5138}
5139
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005140status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5141 std::vector<media::AudioPortFw>* _aidl_return) {
5142 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5143 audio_port_v7 port;
5144 dev->toAudioPort(&port);
5145 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5146 _aidl_return->push_back(std::move(aidlPort));
5147 return OK;
5148 };
5149
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005150 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005151 for (const auto& dev : module->getDeclaredDevices()) {
5152 if (role == media::AudioPortRole::NONE ||
5153 ((role == media::AudioPortRole::SOURCE)
5154 == audio_is_input_device(dev->type()))) {
5155 RETURN_STATUS_IF_ERROR(pushPort(dev));
5156 }
5157 }
5158 }
5159 return OK;
5160}
5161
jiabin19cdba52020-11-24 11:28:58 -08005162status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005163{
Eric Laurent99fcae42018-05-17 16:59:18 -07005164 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5165 return BAD_VALUE;
5166 }
5167 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5168 if (dev != 0) {
5169 dev->toAudioPort(port);
5170 return NO_ERROR;
5171 }
5172 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5173 if (dev != 0) {
5174 dev->toAudioPort(port);
5175 return NO_ERROR;
5176 }
5177 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5178 if (out != 0) {
5179 out->toAudioPort(port);
5180 return NO_ERROR;
5181 }
5182 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5183 if (in != 0) {
5184 in->toAudioPort(port);
5185 return NO_ERROR;
5186 }
5187 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005188}
5189
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005190status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5191 audio_patch_handle_t *handle,
5192 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005193{
François Gaffieafd4cea2019-11-18 15:50:22 +01005194 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005195 if (handle == NULL || patch == NULL) {
5196 return BAD_VALUE;
5197 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005198 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005199 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005200 return BAD_VALUE;
5201 }
5202 // only one source per audio patch supported for now
5203 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005204 return INVALID_OPERATION;
5205 }
Eric Laurent874c42872014-08-08 15:13:39 -07005206 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 return INVALID_OPERATION;
5208 }
Eric Laurent874c42872014-08-08 15:13:39 -07005209 for (size_t i = 0; i < patch->num_sinks; i++) {
5210 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5211 return INVALID_OPERATION;
5212 }
5213 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005214
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005215 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5216 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5217 if (srcDevice == nullptr || sinkDevice == nullptr) {
5218 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5219 return BAD_VALUE;
5220 }
5221 ALOGV("%s between source %s and sink %s", __func__,
5222 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5223 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5224 // Default attributes, default volume priority, not to infer with non raw audio patches.
5225 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5226 const struct audio_port_config *source = &patch->sources[0];
5227 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005228 new SourceClientDescriptor(
5229 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5230 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005231 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005232 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005233
5234 status_t status =
5235 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5236
5237 if (status != NO_ERROR) {
5238 return INVALID_OPERATION;
5239 }
5240 mAudioSources.add(portId, sourceDesc);
5241 return NO_ERROR;
5242}
5243
5244status_t AudioPolicyManager::connectAudioSourceToSink(
5245 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5246 const struct audio_patch *patch,
5247 audio_patch_handle_t &handle,
5248 uid_t uid, uint32_t delayMs)
5249{
5250 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5251 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5252 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5253 return INVALID_OPERATION;
5254 }
5255 sourceDesc->connect(handle, sinkDevice);
5256 if (isMsdPatch(handle)) {
5257 return NO_ERROR;
5258 }
5259 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5260 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5261 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5262 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5263 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5264 goto FailurePatchAdded;
5265 }
5266 status = swOutput->start();
5267 if (status != NO_ERROR) {
5268 goto FailureSourceAdded;
5269 }
5270 swOutput->addClient(sourceDesc);
5271 status = startSource(swOutput, sourceDesc, &delayMs);
5272 if (status != NO_ERROR) {
5273 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5274 goto FailureSourceActive;
5275 }
5276 if (delayMs != 0) {
5277 usleep(delayMs * 1000);
5278 }
5279 return NO_ERROR;
5280
5281FailureSourceActive:
5282 swOutput->stop();
5283 releaseOutput(sourceDesc->portId());
5284FailureSourceAdded:
5285 sourceDesc->setSwOutput(nullptr);
5286FailurePatchAdded:
5287 releaseAudioPatchInternal(handle);
5288 return INVALID_OPERATION;
5289}
5290
5291status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5292 audio_patch_handle_t *handle,
5293 uid_t uid, uint32_t delayMs,
5294 const sp<SourceClientDescriptor>& sourceDesc)
5295{
5296 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 sp<AudioPatch> patchDesc;
5298 ssize_t index = mAudioPatches.indexOfKey(*handle);
5299
François Gaffieafd4cea2019-11-18 15:50:22 +01005300 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5301 patch->sources[0].role,
5302 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005303#if LOG_NDEBUG == 0
5304 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005305 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5306 patch->sinks[i].role,
5307 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005308 }
5309#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005310
5311 if (index >= 0) {
5312 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005313 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5314 __func__, mUidCached, patchDesc->getUid(), uid);
5315 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005316 return INVALID_OPERATION;
5317 }
5318 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005319 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005320 }
5321
5322 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005323 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005324 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005325 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005326 return BAD_VALUE;
5327 }
Eric Laurent84c70242014-06-23 08:46:27 -07005328 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5329 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005330 if (patchDesc != 0) {
5331 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005332 ALOGV("%s source id differs for patch current id %d new id %d",
5333 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005334 return BAD_VALUE;
5335 }
5336 }
Eric Laurent874c42872014-08-08 15:13:39 -07005337 DeviceVector devices;
5338 for (size_t i = 0; i < patch->num_sinks; i++) {
5339 // Only support mix to devices connection
5340 // TODO add support for mix to mix connection
5341 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005342 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005343 return INVALID_OPERATION;
5344 }
5345 sp<DeviceDescriptor> devDesc =
5346 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5347 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005348 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005349 return BAD_VALUE;
5350 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005351
jiabin66acc432024-02-06 00:57:36 +00005352 if (outputDesc->mProfile->getCompatibilityScore(
5353 DeviceVector(devDesc),
5354 patch->sources[0].sample_rate,
5355 nullptr, // updatedSamplingRate
5356 patch->sources[0].format,
5357 nullptr, // updatedFormat
5358 patch->sources[0].channel_mask,
5359 nullptr, // updatedChannelMask
5360 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005361 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005362 return INVALID_OPERATION;
5363 }
5364 devices.add(devDesc);
5365 }
5366 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005367 return INVALID_OPERATION;
5368 }
Eric Laurent874c42872014-08-08 15:13:39 -07005369
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005371 ALOGV("%s setting device %s on output %d",
5372 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305373 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005374 index = mAudioPatches.indexOfKey(*handle);
5375 if (index >= 0) {
5376 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005377 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005378 }
5379 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005380 patchDesc->setUid(uid);
5381 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005382 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005383 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005384 return INVALID_OPERATION;
5385 }
5386 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5387 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5388 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005389 // only one sink supported when connecting an input device to a mix
5390 if (patch->num_sinks > 1) {
5391 return INVALID_OPERATION;
5392 }
François Gaffie53615e22015-03-19 09:24:12 +01005393 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005394 if (inputDesc == NULL) {
5395 return BAD_VALUE;
5396 }
5397 if (patchDesc != 0) {
5398 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5399 return BAD_VALUE;
5400 }
5401 }
François Gaffie11d30102018-11-02 16:09:09 +01005402 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005403 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005404 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005405 return BAD_VALUE;
5406 }
5407
jiabin66acc432024-02-06 00:57:36 +00005408 if (inputDesc->mProfile->getCompatibilityScore(
5409 DeviceVector(device),
5410 patch->sinks[0].sample_rate,
5411 nullptr, /*updatedSampleRate*/
5412 patch->sinks[0].format,
5413 nullptr, /*updatedFormat*/
5414 patch->sinks[0].channel_mask,
5415 nullptr, /*updatedChannelMask*/
5416 // FIXME for the parameter type,
5417 // and the NONE
5418 (audio_output_flags_t)
5419 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005420 return INVALID_OPERATION;
5421 }
5422 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005423 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005424 device->toString().c_str(), inputDesc->mIoHandle);
5425 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005426 index = mAudioPatches.indexOfKey(*handle);
5427 if (index >= 0) {
5428 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005429 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 }
5431 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005432 patchDesc->setUid(uid);
5433 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005434 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005435 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005436 return INVALID_OPERATION;
5437 }
5438 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5439 // device to device connection
5440 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005441 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 return BAD_VALUE;
5443 }
5444 }
François Gaffie11d30102018-11-02 16:09:09 +01005445 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005446 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005447 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005448 return BAD_VALUE;
5449 }
Eric Laurent874c42872014-08-08 15:13:39 -07005450
Eric Laurent6a94d692014-05-20 11:18:06 -07005451 //update source and sink with our own data as the data passed in the patch may
5452 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005453 PatchBuilder patchBuilder;
5454 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005455
5456 // if first sink is to MSD, establish single MSD patch
5457 if (getMsdAudioOutDevices().contains(
5458 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5459 ALOGV("%s patching to MSD", __FUNCTION__);
5460 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5461 goto installPatch;
5462 }
5463
François Gaffieafd4cea2019-11-18 15:50:22 +01005464 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5465 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005466
Eric Laurent874c42872014-08-08 15:13:39 -07005467 for (size_t i = 0; i < patch->num_sinks; i++) {
5468 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005469 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005470 return INVALID_OPERATION;
5471 }
François Gaffie11d30102018-11-02 16:09:09 +01005472 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005473 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005474 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005475 return BAD_VALUE;
5476 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005477 audio_port_config sinkPortConfig = {};
5478 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5479 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005480
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005481 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5482 // volume management purpose (tracking activity)
5483 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5484 // in config XML to reach the sink so that is can be declared as available.
5485 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005486 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005487 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005488 // take care of dynamic routing for SwOutput selection,
5489 audio_attributes_t attributes = sourceDesc->attributes();
5490 audio_stream_type_t stream = sourceDesc->stream();
5491 audio_attributes_t resultAttr;
5492 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5493 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005494 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5495 config.channel_mask =
5496 (audio_channel_mask_get_representation(sourceMask)
5497 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5498 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005499 config.format = sourceDesc->config().format;
5500 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5501 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5502 bool isRequestedDeviceForExclusiveUse = false;
5503 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005504 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005505 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005506 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5507 &stream, sourceDesc->uid(), &config, &flags,
5508 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005509 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005510 if (output == AUDIO_IO_HANDLE_NONE) {
5511 ALOGV("%s no output for device %s",
5512 __FUNCTION__, sinkDevice->toString().c_str());
5513 return INVALID_OPERATION;
5514 }
5515 outputDesc = mOutputs.valueFor(output);
5516 if (outputDesc->isDuplicated()) {
5517 ALOGE("%s output is duplicated", __func__);
5518 return INVALID_OPERATION;
5519 }
François Gaffie7e39df22022-04-26 12:48:49 +02005520 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5521 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005522 } else {
5523 // Same for "raw patches" aka created from createAudioPatch API
5524 SortedVector<audio_io_handle_t> outputs =
5525 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5526 // if the sink device is reachable via an opened output stream, request to
5527 // go via this output stream by adding a second source to the patch
5528 // description
5529 output = selectOutput(outputs);
5530 if (output == AUDIO_IO_HANDLE_NONE) {
5531 ALOGE("%s no output available for internal patch sink", __func__);
5532 return INVALID_OPERATION;
5533 }
5534 outputDesc = mOutputs.valueFor(output);
5535 if (outputDesc->isDuplicated()) {
5536 ALOGV("%s output for device %s is duplicated",
5537 __func__, sinkDevice->toString().c_str());
5538 return INVALID_OPERATION;
5539 }
François Gaffie7e39df22022-04-26 12:48:49 +02005540 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005541 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005542 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005543 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005544 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005545 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005546 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5547 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005548 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5549 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005550 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005551 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005552 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005553 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005554 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005555 return INVALID_OPERATION;
5556 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005557 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005558 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005559 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005560 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005561 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005562 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005563 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005564 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5565 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005566 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005567 }
Eric Laurent83b88082014-06-20 18:31:16 -07005568 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005569 }
5570 // TODO: check from routing capabilities in config file and other conflicting patches
5571
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005572installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005573 status_t status = installPatch(
5574 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005575 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005576 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005577 return INVALID_OPERATION;
5578 }
5579 } else {
5580 return BAD_VALUE;
5581 }
5582 } else {
5583 return BAD_VALUE;
5584 }
5585 return NO_ERROR;
5586}
5587
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005588status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005589{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005590 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005591 ssize_t index = mAudioPatches.indexOfKey(handle);
5592
5593 if (index < 0) {
5594 return BAD_VALUE;
5595 }
5596 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005597 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5598 __func__, mUidCached, patchDesc->getUid(), uid);
5599 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005600 return INVALID_OPERATION;
5601 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005602 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5603 for (size_t i = 0; i < mAudioSources.size(); i++) {
5604 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5605 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5606 portId = sourceDesc->portId();
5607 break;
5608 }
5609 }
5610 return portId != AUDIO_PORT_HANDLE_NONE ?
5611 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005612}
Eric Laurent6a94d692014-05-20 11:18:06 -07005613
François Gaffieafd4cea2019-11-18 15:50:22 +01005614status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005615 uint32_t delayMs,
5616 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005617{
5618 ALOGV("%s patch %d", __func__, handle);
5619 if (mAudioPatches.indexOfKey(handle) < 0) {
5620 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5621 return BAD_VALUE;
5622 }
5623 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005624 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005625 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005626 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005627 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005628 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005629 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005630 return BAD_VALUE;
5631 }
5632
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305633 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005634 getNewOutputDevices(outputDesc, true /*fromCache*/),
5635 true,
5636 0,
5637 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005638 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5639 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005640 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005641 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005642 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005643 return BAD_VALUE;
5644 }
5645 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005646 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005647 true,
5648 NULL);
5649 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005650 status_t status =
5651 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5652 ALOGV("%s patch panel returned %d patchHandle %d",
5653 __func__, status, patchDesc->getAfHandle());
5654 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005655 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005656 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005657 // SW or HW Bridge
5658 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5659 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005660 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005661 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5662 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5663 outputDesc = sourceDesc->swOutput().promote();
5664 }
5665 if (outputDesc == nullptr) {
5666 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5667 // releaseOutput has already called closeOutput in case of direct output
5668 return NO_ERROR;
5669 }
François Gaffie7e39df22022-04-26 12:48:49 +02005670 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005671 // While using a HwBridge, force reconsidering device only if not reusing an existing
5672 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005673 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005674 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5675 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5676 // Reconsider device only for cases:
5677 // 1 / Active Output
5678 // 2 / Inactive Output previously hosting HwBridge
5679 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5680 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5681 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305682 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005683 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5684 outputDesc->devices(),
5685 force,
5686 0,
5687 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005688 } else {
5689 return BAD_VALUE;
5690 }
5691 } else {
5692 return BAD_VALUE;
5693 }
5694 return NO_ERROR;
5695}
5696
5697status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5698 struct audio_patch *patches,
5699 unsigned int *generation)
5700{
François Gaffie53615e22015-03-19 09:24:12 +01005701 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005702 return BAD_VALUE;
5703 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005704 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005705 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005706}
5707
Eric Laurente1715a42014-05-20 11:30:42 -07005708status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005709{
Eric Laurente1715a42014-05-20 11:30:42 -07005710 ALOGV("setAudioPortConfig()");
5711
5712 if (config == NULL) {
5713 return BAD_VALUE;
5714 }
5715 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5716 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005717 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5718 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005719 }
5720
Eric Laurenta121f902014-06-03 13:32:54 -07005721 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005722 if (config->type == AUDIO_PORT_TYPE_MIX) {
5723 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005724 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005725 if (outputDesc == NULL) {
5726 return BAD_VALUE;
5727 }
Eric Laurent84c70242014-06-23 08:46:27 -07005728 ALOG_ASSERT(!outputDesc->isDuplicated(),
5729 "setAudioPortConfig() called on duplicated output %d",
5730 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005731 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005732 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005733 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005734 if (inputDesc == NULL) {
5735 return BAD_VALUE;
5736 }
Eric Laurenta121f902014-06-03 13:32:54 -07005737 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005738 } else {
5739 return BAD_VALUE;
5740 }
5741 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5742 sp<DeviceDescriptor> deviceDesc;
5743 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5744 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5745 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5746 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5747 } else {
5748 return BAD_VALUE;
5749 }
5750 if (deviceDesc == NULL) {
5751 return BAD_VALUE;
5752 }
Eric Laurenta121f902014-06-03 13:32:54 -07005753 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005754 } else {
5755 return BAD_VALUE;
5756 }
5757
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005758 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005759 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5760 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005761 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005762 audioPortConfig->toAudioPortConfig(&newConfig, config);
5763 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005764 }
Eric Laurenta121f902014-06-03 13:32:54 -07005765 if (status != NO_ERROR) {
5766 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005767 }
Eric Laurente1715a42014-05-20 11:30:42 -07005768
5769 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005770}
5771
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005772void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5773{
Eric Laurentd60560a2015-04-10 11:31:20 -07005774 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005775 clearAudioPatches(uid);
5776 clearSessionRoutes(uid);
5777}
5778
Eric Laurent6a94d692014-05-20 11:18:06 -07005779void AudioPolicyManager::clearAudioPatches(uid_t uid)
5780{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005781 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005782 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005783 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005784 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005785 }
5786 }
5787}
5788
François Gaffiec005e562018-11-06 15:04:49 +01005789void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005790{
François Gaffiec005e562018-11-06 15:04:49 +01005791 // Take the first attributes following the product strategy as it is used to retrieve the routed
5792 // device. All attributes wihin a strategy follows the same "routing strategy"
5793 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5794 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005795 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005796 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005797 for (size_t j = 0; j < mOutputs.size(); j++) {
5798 if (mOutputs.keyAt(j) == ouptutToSkip) {
5799 continue;
5800 }
5801 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005802 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005803 continue;
5804 }
5805 // If the default device for this strategy is on another output mix,
5806 // invalidate all tracks in this strategy to force re connection.
5807 // Otherwise select new device on the output mix.
5808 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005809 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005810 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005811 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005812 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005813 // If the device is using preferred mixer attributes, the output need to reopen
5814 // with default configuration when the new selected devices are different from
5815 // current routing devices.
5816 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5817 continue;
5818 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305819 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005820 }
5821 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005822 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005823}
5824
5825void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5826{
5827 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005828 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005829 for (size_t i = 0; i < mOutputs.size(); i++) {
5830 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005831 for (const auto& client : outputDesc->getClientIterable()) {
5832 if (client->hasPreferredDevice() && client->uid() == uid) {
5833 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005834 auto clientStrategy = client->strategy();
5835 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5836 end(affectedStrategies)) {
5837 continue;
5838 }
5839 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005840 }
5841 }
5842 }
5843 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005844 for (const auto& strategy : affectedStrategies) {
5845 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005846 }
5847
5848 // remove input routes associated with this uid
5849 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005850 for (size_t i = 0; i < mInputs.size(); i++) {
5851 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005852 for (const auto& client : inputDesc->getClientIterable()) {
5853 if (client->hasPreferredDevice() && client->uid() == uid) {
5854 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5855 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005856 }
5857 }
5858 }
5859 // reroute inputs if necessary
5860 SortedVector<audio_io_handle_t> inputsToClose;
5861 for (size_t i = 0; i < mInputs.size(); i++) {
5862 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005863 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005864 inputsToClose.add(inputDesc->mIoHandle);
5865 }
5866 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005867 for (const auto& input : inputsToClose) {
5868 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005869 }
5870}
5871
Eric Laurentd60560a2015-04-10 11:31:20 -07005872void AudioPolicyManager::clearAudioSources(uid_t uid)
5873{
5874 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005875 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5876 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005877 stopAudioSource(mAudioSources.keyAt(i));
5878 }
5879 }
5880}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005881
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005882status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5883 audio_io_handle_t *ioHandle,
5884 audio_devices_t *device)
5885{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005886 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5887 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005888 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005889 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5890 if (deviceDesc == nullptr) {
5891 return INVALID_OPERATION;
5892 }
5893 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005894
François Gaffiedf372692015-03-19 10:43:27 +01005895 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005896}
5897
Eric Laurentd60560a2015-04-10 11:31:20 -07005898status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005899 const audio_attributes_t *attributes,
5900 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005901 uid_t uid) {
5902 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005903 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005904}
5905
5906status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5907 const audio_attributes_t *attributes,
5908 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005909 uid_t uid, bool internal, bool isCallRx,
5910 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005911{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005912 ALOGV("%s", __FUNCTION__);
5913 *portId = AUDIO_PORT_HANDLE_NONE;
5914
5915 if (source == NULL || attributes == NULL || portId == NULL) {
5916 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5917 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005918 return BAD_VALUE;
5919 }
5920
Eric Laurentd60560a2015-04-10 11:31:20 -07005921 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5922 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005923 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5924 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005925 return INVALID_OPERATION;
5926 }
5927
François Gaffie11d30102018-11-02 16:09:09 +01005928 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005929 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005930 String8(source->ext.device.address),
5931 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005932 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005933 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005934 return BAD_VALUE;
5935 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005936
jiabin4ef93452019-09-10 14:29:54 -07005937 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005938
François Gaffieaaac0fd2018-11-22 17:56:39 +01005939 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005940 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005941 mEngine->getStreamTypeForAttributes(*attributes),
5942 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005943 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005944
David Lif85c5e32024-07-01 13:14:10 +00005945 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005946 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005947 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005948 }
5949 return status;
5950}
5951
David Lif85c5e32024-07-01 13:14:10 +00005952status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5953 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005954{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005955 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005956
5957 // make sure we only have one patch per source.
5958 disconnectAudioSource(sourceDesc);
5959
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005960 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005961 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5962 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5963 sourceDesc->srcDevice()->type(),
5964 String8(sourceDesc->srcDevice()->address().c_str()),
5965 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005966 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005967 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005968 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005969 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005970 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5971 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5972 return INVALID_OPERATION;
5973 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005974 PatchBuilder patchBuilder;
5975 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5976 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005977
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005978 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00005979 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005980}
5981
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005982status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005983{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005984 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5985 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005986 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005987 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005988 return BAD_VALUE;
5989 }
5990 status_t status = disconnectAudioSource(sourceDesc);
5991
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005992 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005993 return status;
5994}
5995
Andy Hung2ddee192015-12-18 17:34:44 -08005996status_t AudioPolicyManager::setMasterMono(bool mono)
5997{
5998 if (mMasterMono == mono) {
5999 return NO_ERROR;
6000 }
6001 mMasterMono = mono;
6002 // if enabling mono we close all offloaded devices, which will invalidate the
6003 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6004 // for recreating the new AudioTrack as non-offloaded PCM.
6005 //
6006 // If disabling mono, we leave all tracks as is: we don't know which clients
6007 // and tracks are able to be recreated as offloaded. The next "song" should
6008 // play back offloaded.
6009 if (mMasterMono) {
6010 Vector<audio_io_handle_t> offloaded;
6011 for (size_t i = 0; i < mOutputs.size(); ++i) {
6012 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6013 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6014 offloaded.push(desc->mIoHandle);
6015 }
6016 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006017 for (const auto& handle : offloaded) {
6018 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006019 }
6020 }
6021 // update master mono for all remaining outputs
6022 for (size_t i = 0; i < mOutputs.size(); ++i) {
6023 updateMono(mOutputs.keyAt(i));
6024 }
6025 return NO_ERROR;
6026}
6027
6028status_t AudioPolicyManager::getMasterMono(bool *mono)
6029{
6030 *mono = mMasterMono;
6031 return NO_ERROR;
6032}
6033
Eric Laurentac9cef52017-06-09 15:46:26 -07006034float AudioPolicyManager::getStreamVolumeDB(
6035 audio_stream_type_t stream, int index, audio_devices_t device)
6036{
Vlad Popa9d482762024-06-21 16:40:23 -07006037 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6038 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006039}
6040
jiabin81772902018-04-02 17:52:27 -07006041status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6042 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006043 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006044{
Kriti Dang6537def2021-03-02 13:46:59 +01006045 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6046 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006047 return BAD_VALUE;
6048 }
Kriti Dang6537def2021-03-02 13:46:59 +01006049 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6050 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006051
6052 size_t formatsWritten = 0;
6053 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006054
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006055 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006056 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6057 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006058 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006059 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006060 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006061 bool formatEnabled = true;
6062 switch (forceUse) {
6063 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006064 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006065 break;
6066 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6067 formatEnabled = false;
6068 break;
6069 default: // AUTO or ALWAYS => true
6070 break;
jiabin81772902018-04-02 17:52:27 -07006071 }
6072 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6073 }
jiabin81772902018-04-02 17:52:27 -07006074 }
6075 return NO_ERROR;
6076}
6077
Kriti Dang6537def2021-03-02 13:46:59 +01006078status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6079 audio_format_t *surroundFormats) {
6080 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6081 return BAD_VALUE;
6082 }
6083 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6084 __func__, *numSurroundFormats, surroundFormats);
6085
6086 size_t formatsWritten = 0;
6087 size_t formatsMax = *numSurroundFormats;
6088 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6089
6090 // Return formats from all device profiles that have already been resolved by
6091 // checkOutputsForDevice().
6092 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6093 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6094 audio_devices_t deviceType = device->type();
6095 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6096 // returns formats reported by HDMI devices.
6097 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6098 continue;
6099 }
6100 // Formats reported by sink devices
6101 std::unordered_set<audio_format_t> formatset;
6102 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6103 formatset.insert(it->second.begin(), it->second.end());
6104 }
6105
6106 // Formats hard-coded in the in policy configuration file (if any).
6107 FormatVector encodedFormats = device->encodedFormats();
6108 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6109 // Filter the formats which are supported by the vendor hardware.
6110 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006111 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006112 formats.insert(*it);
6113 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006114 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006115 if (pair.second.count(*it) != 0) {
6116 formats.insert(pair.first);
6117 break;
6118 }
6119 }
6120 }
6121 }
6122 }
6123 *numSurroundFormats = formats.size();
6124 for (const auto& format: formats) {
6125 if (formatsWritten < formatsMax) {
6126 surroundFormats[formatsWritten++] = format;
6127 }
6128 }
6129 return NO_ERROR;
6130}
6131
jiabin81772902018-04-02 17:52:27 -07006132status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6133{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006134 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006135 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6136 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006137 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006138 return BAD_VALUE;
6139 }
6140
Mikhail Naganov100f0122018-11-29 11:22:16 -08006141 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6142 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006143 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006144 return INVALID_OPERATION;
6145 }
6146
Mikhail Naganov100f0122018-11-29 11:22:16 -08006147 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006148 return NO_ERROR;
6149 }
6150
Mikhail Naganov100f0122018-11-29 11:22:16 -08006151 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006152 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006153 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006154 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006155 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006156 }
6157 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006158 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006159 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006160 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006161 }
6162 }
6163
6164 sp<SwAudioOutputDescriptor> outputDesc;
6165 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006166 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6167 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006168 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6169 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006170 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006171 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006172 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6173 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6174 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006175 name.c_str(),
6176 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006177 if (status != NO_ERROR) {
6178 continue;
6179 }
6180 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6181 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6182 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006183 name.c_str(),
6184 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006185 profileUpdated |= (status == NO_ERROR);
6186 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006187 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006188 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006189 AUDIO_DEVICE_IN_HDMI);
6190 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6191 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006192 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006193 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006194 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6195 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6196 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006197 name.c_str(),
6198 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006199 if (status != NO_ERROR) {
6200 continue;
6201 }
6202 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6203 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6204 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006205 name.c_str(),
6206 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006207 profileUpdated |= (status == NO_ERROR);
6208 }
6209
jiabin81772902018-04-02 17:52:27 -07006210 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006211 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006212 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006213 }
6214
6215 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6216}
6217
Eric Laurent5ada82e2019-08-29 17:53:54 -07006218void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006219{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006220 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006221 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006222 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006223 }
6224}
6225
jiabin6012f912018-11-02 17:06:30 -07006226bool AudioPolicyManager::isHapticPlaybackSupported()
6227{
6228 for (const auto& hwModule : mHwModules) {
6229 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6230 for (const auto &outProfile : outputProfiles) {
6231 struct audio_port audioPort;
6232 outProfile->toAudioPort(&audioPort);
6233 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6234 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6235 return true;
6236 }
6237 }
6238 }
6239 }
6240 return false;
6241}
6242
Carter Hsu325a8eb2022-01-19 19:56:51 +08006243bool AudioPolicyManager::isUltrasoundSupported()
6244{
6245 bool hasUltrasoundOutput = false;
6246 bool hasUltrasoundInput = false;
6247 for (const auto& hwModule : mHwModules) {
6248 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6249 if (!hasUltrasoundOutput) {
6250 for (const auto &outProfile : outputProfiles) {
6251 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6252 hasUltrasoundOutput = true;
6253 break;
6254 }
6255 }
6256 }
6257
6258 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6259 if (!hasUltrasoundInput) {
6260 for (const auto &inputProfile : inputProfiles) {
6261 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6262 hasUltrasoundInput = true;
6263 break;
6264 }
6265 }
6266 }
6267
6268 if (hasUltrasoundOutput && hasUltrasoundInput)
6269 return true;
6270 }
6271 return false;
6272}
6273
Atneya Nair698f5ef2022-12-15 16:15:09 -08006274bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6275{
6276 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6277 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6278 for (const auto& hwModule : mHwModules) {
6279 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6280 for (const auto &inputProfile : inputProfiles) {
6281 if ((inputProfile->getFlags() & mask) == mask) {
6282 return true;
6283 }
6284 }
6285 }
6286 return false;
6287}
6288
Eric Laurent8340e672019-11-06 11:01:08 -08006289bool AudioPolicyManager::isCallScreenModeSupported()
6290{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006291 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006292}
6293
6294
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006295status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006296{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006297 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006298 if (!sourceDesc->isConnected()) {
6299 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6300 return NO_ERROR;
6301 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006302 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6303 if (swOutput != 0) {
6304 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006305 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006306 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006307 }
jiabinbce0c1d2020-10-05 11:20:18 -07006308 if (releaseOutput(sourceDesc->portId())) {
6309 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6310 // no need to release audio patch here but just return NO_ERROR.
6311 return NO_ERROR;
6312 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006313 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006314 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006315 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006316 // close Hwoutput and remove from mHwOutputs
6317 } else {
6318 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6319 }
6320 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006321 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006322 sourceDesc->disconnect();
6323 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006324}
6325
François Gaffiec005e562018-11-06 15:04:49 +01006326sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6327 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006328{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006329 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006330 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006331 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006332 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006333 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6334 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006335 source = sourceDesc;
6336 break;
6337 }
6338 }
6339 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006340}
6341
Eric Laurentb4f42a92022-01-17 17:37:31 +01006342bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006343 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006344 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006345{
6346 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6347 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006348 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006349 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006350 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6351 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6352 return false;
6353 }
6354 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6355 return false;
6356 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006357 }
6358
Eric Laurentd332bc82023-08-04 11:45:23 +02006359 // The caller can have the audio config criteria ignored by either passing a null ptr or
6360 // the AUDIO_CONFIG_INITIALIZER value.
6361 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006362 // some positional channel masks and PCM format and for stereo if low latency performance
6363 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006364
6365 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurentb16eac52024-08-02 16:46:08 +00006366 static const bool stereo_spatialization_prop_enabled =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006367 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006368 const bool channel_mask_spatialized =
Eric Laurentb16eac52024-08-02 16:46:08 +00006369 (stereo_spatialization_prop_enabled
6370 && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006371 ? audio_channel_mask_contains_stereo(config->channel_mask)
6372 : audio_is_channel_mask_spatialized(config->channel_mask);
6373 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006374 return false;
6375 }
6376 if (!audio_is_linear_pcm(config->format)) {
6377 return false;
6378 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006379 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6380 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6381 return false;
6382 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006383 }
6384
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006385 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006386 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006387 if (profile == nullptr) {
6388 return false;
6389 }
6390
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006391 return true;
6392}
6393
Shunkai Yao4c3af932024-04-26 04:12:21 +00006394// The Spatializer output is compatible with Haptic use cases if:
6395// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6396// with client if client haptic channel bits were set, or
6397// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6398// including the haptic bits or creating the HapticGenerator effect for same session.
6399bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6400 const audio_config_t* config, audio_session_t sessionId) const {
6401 const auto clientHapticChannel =
6402 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6403 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6404 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6405
6406 if (threadOutputHapticChannel) {
6407 // check format and sampleRate match if client haptic channel mask exist
6408 if (clientHapticChannel) {
6409 return mSpatializerOutput->getFormat() == config->format &&
6410 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6411 }
6412 return true;
6413 } else {
6414 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6415 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6416 // HapticGenerator effect for this session) are not supported.
6417 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006418 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006419 }
6420}
6421
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006422void AudioPolicyManager::checkVirtualizerClientRoutes() {
6423 std::set<audio_stream_type_t> streamsToInvalidate;
6424 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006425 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6426 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006427 audio_attributes_t attr = client->attributes();
6428 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6429 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6430 audio_config_base_t clientConfig = client->config();
6431 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006432 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006433 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006434 streamsToInvalidate.insert(client->stream());
6435 }
6436 }
6437 }
6438
jiabinc44b3462022-12-08 12:52:31 -08006439 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006440}
6441
Eric Laurente191d1b2022-04-15 11:59:25 +02006442
6443bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6444 const sp<SwAudioOutputDescriptor>& outputDesc) {
6445 if (outputDesc->isDuplicated()) {
6446 return false;
6447 }
6448 DeviceVector devices = outputDesc->supportedDevices();
6449 for (size_t i = 0; i < mOutputs.size(); i++) {
6450 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6451 if (desc == outputDesc || desc->isDuplicated()) {
6452 continue;
6453 }
6454 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6455 if (!sharedDevices.isEmpty()
6456 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6457 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6458 return false;
6459 }
6460 }
6461 return true;
6462}
6463
6464
Eric Laurentfa0f6742021-08-17 18:39:44 +02006465status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006466 const audio_attributes_t *attr,
6467 audio_io_handle_t *output) {
6468 *output = AUDIO_IO_HANDLE_NONE;
6469
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006470 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6471 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6472 audio_config_t *configPtr = nullptr;
6473 audio_config_t config;
6474 if (mixerConfig != nullptr) {
6475 config = audio_config_initializer(mixerConfig);
6476 configPtr = &config;
6477 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006478 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006479 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006480 return BAD_VALUE;
6481 }
6482
6483 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006484 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006485 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006486 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006487 return BAD_VALUE;
6488 }
6489
Eric Laurente191d1b2022-04-15 11:59:25 +02006490 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006491 for (size_t i = 0; i < mOutputs.size(); i++) {
6492 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006493 if (!desc->isDuplicated()
6494 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6495 spatializerOutputs.push_back(desc);
6496 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006497 }
6498 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006499 mSpatializerOutput.clear();
6500 bool outputsChanged = false;
6501 for (const auto& desc : spatializerOutputs) {
6502 if (desc->mProfile == profile
6503 && (configPtr == nullptr
6504 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6505 mSpatializerOutput = desc;
6506 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6507 } else {
6508 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6509 " and devices %s", __func__, desc->mIoHandle,
6510 configPtr != nullptr ? configPtr->channel_mask : 0,
6511 devices.toString().c_str());
6512 closeOutput(desc->mIoHandle);
6513 outputsChanged = true;
6514 }
Eric Laurent39095982021-08-24 18:29:27 +02006515 }
6516
Eric Laurente191d1b2022-04-15 11:59:25 +02006517 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006518 sp<SwAudioOutputDescriptor> desc =
6519 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006520 if (desc != nullptr) {
6521 mSpatializerOutput = desc;
6522 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006523 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006524 }
6525
6526 checkVirtualizerClientRoutes();
6527
Eric Laurente191d1b2022-04-15 11:59:25 +02006528 if (outputsChanged) {
6529 mPreviousOutputs = mOutputs;
6530 mpClientInterface->onAudioPortListUpdate();
6531 }
6532
6533 if (mSpatializerOutput == nullptr) {
6534 ALOGV("%s could not open spatializer output with requested config", __func__);
6535 return BAD_VALUE;
6536 }
Eric Laurent39095982021-08-24 18:29:27 +02006537 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006538 ALOGV("%s returning new spatializer output %d", __func__, *output);
6539 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006540}
6541
Eric Laurentfa0f6742021-08-17 18:39:44 +02006542status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6543 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006544 return INVALID_OPERATION;
6545 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006546 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006547 return BAD_VALUE;
6548 }
Eric Laurent39095982021-08-24 18:29:27 +02006549
Eric Laurente191d1b2022-04-15 11:59:25 +02006550 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6551 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6552 closeOutput(mSpatializerOutput->mIoHandle);
6553 //from now on mSpatializerOutput is null
6554 checkVirtualizerClientRoutes();
6555 }
Eric Laurent39095982021-08-24 18:29:27 +02006556
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006557 return NO_ERROR;
6558}
6559
Eric Laurente552edb2014-03-10 17:42:56 -07006560// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006561// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006562// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006563uint32_t AudioPolicyManager::nextAudioPortGeneration()
6564{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006565 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006566}
6567
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006568AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006569 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006570 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006571 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006572 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006573 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006574 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006575 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006576 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006577 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006578 mAudioPortGeneration(1),
6579 mBeaconMuteRefCount(0),
6580 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006581 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006582 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006583 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006584 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006585{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006586}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006587
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006588status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006589 if (mEngine == nullptr) {
6590 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006591 }
6592 mEngine->setObserver(this);
6593 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006594 if (status != NO_ERROR) {
6595 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6596 return status;
6597 }
François Gaffie2110e042015-03-24 08:41:51 +01006598
jiabin29230182023-04-04 21:02:36 +00006599 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6600 // at the end of this function.
6601 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006602 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6603 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6604
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006605 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006606 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006607 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006608
Eric Laurent3a4311c2014-03-17 12:00:47 -07006609 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006610 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6611 defaultOutputDevice == nullptr ||
6612 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6613 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6614 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006615 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006616 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006617 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006618
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006619 // Silence ALOGV statements
6620 property_set("log.tag." LOG_TAG, "D");
6621
Eric Laurente552edb2014-03-10 17:42:56 -07006622 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006623 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006624}
6625
Eric Laurente0720872014-03-11 09:30:41 -07006626AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006627{
Eric Laurente552edb2014-03-10 17:42:56 -07006628 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006629 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006630 }
6631 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006632 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006633 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006634 mAvailableOutputDevices.clear();
6635 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006636 mOutputs.clear();
6637 mInputs.clear();
6638 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006639 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006640 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006641}
6642
Eric Laurente0720872014-03-11 09:30:41 -07006643status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006644{
Eric Laurent87ffa392015-05-22 10:32:38 -07006645 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006646}
6647
Eric Laurente552edb2014-03-10 17:42:56 -07006648// ---
6649
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006650void AudioPolicyManager::onNewAudioModulesAvailable()
6651{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006652 DeviceVector newDevices;
6653 onNewAudioModulesAvailableInt(&newDevices);
6654 if (!newDevices.empty()) {
6655 nextAudioPortGeneration();
6656 mpClientInterface->onAudioPortListUpdate();
6657 }
6658}
6659
6660void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6661{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006662 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006663 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6664 continue;
6665 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006666 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006667 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6668 handle != AUDIO_MODULE_HANDLE_NONE) {
6669 hwModule->setHandle(handle);
6670 } else {
6671 ALOGW("could not load HW module %s", hwModule->getName());
6672 continue;
6673 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006674 }
6675 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006676 // open all output streams needed to access attached devices.
6677 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006678 // This also validates mAvailableOutputDevices list
6679 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6680 if (!outProfile->canOpenNewIo()) {
6681 ALOGE("Invalid Output profile max open count %u for profile %s",
6682 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6683 continue;
6684 }
6685 if (!outProfile->hasSupportedDevices()) {
6686 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6687 continue;
6688 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006689 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6690 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006691 mTtsOutputAvailable = true;
6692 }
6693
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006694 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006695 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006696 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006697 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6698 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006699 } else {
6700 // choose first device present in profile's SupportedDevices also part of
6701 // mAvailableOutputDevices.
6702 if (availProfileDevices.isEmpty()) {
6703 continue;
6704 }
6705 supportedDevice = availProfileDevices.itemAt(0);
6706 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006707 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006708 continue;
6709 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306710
6711 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6712 && availProfileDevices.areAllDevicesAttached()) {
6713 ALOGV("%s skip opening output for mmap profile %s", __func__,
6714 outProfile->getTagName().c_str());
6715 continue;
6716 }
6717
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006718 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6719 mpClientInterface);
6720 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006721 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006722 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6723 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006724 AUDIO_STREAM_DEFAULT,
Haofan Wangf6e304f2024-07-09 23:06:58 -07006725 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006726 if (status != NO_ERROR) {
6727 ALOGW("Cannot open output stream for devices %s on hw module %s",
6728 supportedDevice->toString().c_str(), hwModule->getName());
6729 continue;
6730 }
6731 for (const auto &device : availProfileDevices) {
6732 // give a valid ID to an attached device once confirmed it is reachable
6733 if (!device->isAttached()) {
6734 device->attach(hwModule);
6735 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006736 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006737 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006738 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6739 }
6740 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006741 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006742 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6743 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006744 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006745 }
Eric Laurent39095982021-08-24 18:29:27 +02006746 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006747 outputDesc->close();
6748 } else {
6749 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306750 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006751 DeviceVector(supportedDevice),
6752 true,
6753 0,
6754 NULL);
6755 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006756 }
6757 // open input streams needed to access attached devices to validate
6758 // mAvailableInputDevices list
6759 for (const auto& inProfile : hwModule->getInputProfiles()) {
6760 if (!inProfile->canOpenNewIo()) {
6761 ALOGE("Invalid Input profile max open count %u for profile %s",
6762 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6763 continue;
6764 }
6765 if (!inProfile->hasSupportedDevices()) {
6766 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6767 continue;
6768 }
6769 // chose first device present in profile's SupportedDevices also part of
6770 // available input devices
6771 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006772 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006773 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006774 ALOGV("%s: Input device list is empty! for profile %s",
6775 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006776 continue;
6777 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306778
6779 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6780 && availProfileDevices.areAllDevicesAttached()) {
6781 ALOGV("%s skip opening input for mmap profile %s", __func__,
6782 inProfile->getTagName().c_str());
6783 continue;
6784 }
6785
Eric Laurentc71b11b2024-06-03 12:54:53 +00006786 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6787 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006788
6789 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6790 status_t status = inputDesc->open(nullptr,
6791 availProfileDevices.itemAt(0),
6792 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306793 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006794 &input);
6795 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306796 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6797 __func__, availProfileDevices.toString().c_str(),
6798 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006799 continue;
6800 }
6801 for (const auto &device : availProfileDevices) {
6802 // give a valid ID to an attached device once confirmed it is reachable
6803 if (!device->isAttached()) {
6804 device->attach(hwModule);
6805 device->importAudioPortAndPickAudioProfile(inProfile, true);
6806 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006807 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006808 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6809 }
6810 }
6811 inputDesc->close();
6812 }
6813 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006814
6815 // Check if spatializer outputs can be closed until used.
6816 // mOutputs vector never contains duplicated outputs at this point.
6817 std::vector<audio_io_handle_t> outputsClosed;
6818 for (size_t i = 0; i < mOutputs.size(); i++) {
6819 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6820 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6821 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6822 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006823 nextAudioPortGeneration();
6824 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6825 if (index >= 0) {
6826 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6827 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6828 patchDesc->getAfHandle(), 0);
6829 mAudioPatches.removeItemsAt(index);
6830 mpClientInterface->onAudioPatchListUpdate();
6831 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006832 desc->close();
6833 }
6834 }
6835 for (auto output : outputsClosed) {
6836 removeOutput(output);
6837 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006838}
6839
Eric Laurent98e38192018-02-15 18:31:53 -08006840void AudioPolicyManager::addOutput(audio_io_handle_t output,
6841 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006842{
Eric Laurent1c333e22014-05-20 10:48:17 -07006843 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006844 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006845 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006846 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006847 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006848}
6849
François Gaffie53615e22015-03-19 09:24:12 +01006850void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6851{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006852 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6853 ALOGV("%s: removing primary output", __func__);
6854 mPrimaryOutput = nullptr;
6855 }
François Gaffie53615e22015-03-19 09:24:12 +01006856 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006857 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006858}
6859
Eric Laurent98e38192018-02-15 18:31:53 -08006860void AudioPolicyManager::addInput(audio_io_handle_t input,
6861 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006862{
Eric Laurent1c333e22014-05-20 10:48:17 -07006863 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006864 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006865}
Eric Laurente552edb2014-03-10 17:42:56 -07006866
François Gaffie11d30102018-11-02 16:09:09 +01006867status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006868 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006869 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006870{
François Gaffie11d30102018-11-02 16:09:09 +01006871 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006872 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006873 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006874
François Gaffie11d30102018-11-02 16:09:09 +01006875 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006876 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006877 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006878 }
Eric Laurente552edb2014-03-10 17:42:56 -07006879
Eric Laurent3b73df72014-03-11 09:06:29 -07006880 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006881 // first call getAudioPort to get the supported attributes from the HAL
6882 struct audio_port_v7 port = {};
6883 device->toAudioPort(&port);
6884 status_t status = mpClientInterface->getAudioPort(&port);
6885 if (status == NO_ERROR) {
6886 device->importAudioPort(port);
6887 }
6888
6889 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006890 for (size_t i = 0; i < mOutputs.size(); i++) {
6891 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006892 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006893 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006894 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6895 mOutputs.keyAt(i), device->toString().c_str());
6896 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006897 }
6898 }
6899 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006900 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006901 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006902 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6903 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006904 if (profile->supportsDevice(device)) {
6905 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306906 ALOGV("%s(): adding profile %s from module %s",
6907 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006908 }
6909 }
6910 }
6911
Eric Laurent7b279bb2015-12-14 10:18:23 -08006912 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006913
Eric Laurente552edb2014-03-10 17:42:56 -07006914 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006915 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006916 return BAD_VALUE;
6917 }
6918
6919 // open outputs for matching profiles if needed. Direct outputs are also opened to
6920 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6921 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006922 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006923
6924 // nothing to do if one output is already opened for this profile
6925 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006926 for (j = 0; j < outputs.size(); j++) {
6927 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006928 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006929 // matching profile: save the sample rates, format and channel masks supported
6930 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006931 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006932 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006933 }
Eric Laurente552edb2014-03-10 17:42:56 -07006934 break;
6935 }
6936 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006937 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006938 continue;
6939 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306940 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6941 ALOGV("%s skip opening output for mmap profile %s",
6942 __func__, profile->getTagName().c_str());
6943 continue;
6944 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006945 if (!profile->canOpenNewIo()) {
6946 ALOGW("Max Output number %u already opened for this profile %s",
6947 profile->maxOpenCount, profile->getTagName().c_str());
6948 continue;
6949 }
6950
Eric Laurent83efe1c2017-07-09 16:51:08 -07006951 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006952 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006953 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6954 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006955 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006956 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006957 profiles.removeAt(profile_index);
6958 profile_index--;
6959 } else {
6960 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006961 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006962 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006963 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6964 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006965 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006966 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006967
François Gaffie11d30102018-11-02 16:09:09 +01006968 if (device_distinguishes_on_address(deviceType)) {
6969 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6970 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306971 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6972 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006973 }
Eric Laurente552edb2014-03-10 17:42:56 -07006974 ALOGV("checkOutputsForDevice(): adding output %d", output);
6975 }
6976 }
6977
6978 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006979 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006980 return BAD_VALUE;
6981 }
Eric Laurentd4692962014-05-05 18:13:44 -07006982 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006983 // check if one opened output is not needed any more after disconnecting one device
6984 for (size_t i = 0; i < mOutputs.size(); i++) {
6985 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006986 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006987 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006988 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006989 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006990 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006991 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006992 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6993 mOutputs.keyAt(i));
6994 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006995 }
Eric Laurente552edb2014-03-10 17:42:56 -07006996 }
6997 }
Eric Laurentd4692962014-05-05 18:13:44 -07006998 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006999 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007000 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7001 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007002 if (!profile->supportsDevice(device)) {
7003 continue;
7004 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307005 ALOGV("%s(): clearing direct output profile %s on module %s",
7006 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007007 profile->clearAudioProfiles();
7008 if (!profile->hasDynamicAudioProfile()) {
7009 continue;
7010 }
7011 // When a device is disconnected, if there is an IOProfile that contains dynamic
7012 // profiles and supports the disconnected device, call getAudioPort to repopulate
7013 // the capabilities of the devices that is supported by the IOProfile.
7014 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7015 if (supportedDevice == device ||
7016 !mAvailableOutputDevices.contains(supportedDevice)) {
7017 continue;
7018 }
7019 struct audio_port_v7 port;
7020 supportedDevice->toAudioPort(&port);
7021 status_t status = mpClientInterface->getAudioPort(&port);
7022 if (status == NO_ERROR) {
7023 supportedDevice->importAudioPort(port);
7024 }
Eric Laurente552edb2014-03-10 17:42:56 -07007025 }
7026 }
7027 }
7028 }
7029 return NO_ERROR;
7030}
7031
François Gaffie11d30102018-11-02 16:09:09 +01007032status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007033 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007034{
François Gaffie11d30102018-11-02 16:09:09 +01007035 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007036 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007037 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007038 }
7039
Eric Laurentd4692962014-05-05 18:13:44 -07007040 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007041 sp<AudioInputDescriptor> desc;
7042
jiabinbf5f4262023-04-12 21:48:34 +00007043 // first call getAudioPort to get the supported attributes from the HAL
7044 struct audio_port_v7 port = {};
7045 device->toAudioPort(&port);
7046 status_t status = mpClientInterface->getAudioPort(&port);
7047 if (status == NO_ERROR) {
7048 device->importAudioPort(port);
7049 }
7050
Eric Laurent0dd51852019-04-19 18:18:58 -07007051 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007052 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007053 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007054 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007055 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007056 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007057 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007058
François Gaffie11d30102018-11-02 16:09:09 +01007059 if (profile->supportsDevice(device)) {
7060 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307061 ALOGV("%s : adding profile %s from module %s", __func__,
7062 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007063 }
7064 }
7065 }
7066
Eric Laurent0dd51852019-04-19 18:18:58 -07007067 if (profiles.isEmpty()) {
7068 ALOGW("%s: No input profile available for device %s",
7069 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007070 return BAD_VALUE;
7071 }
7072
7073 // open inputs for matching profiles if needed. Direct inputs are also opened to
7074 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7075 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7076
Eric Laurent1c333e22014-05-20 10:48:17 -07007077 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007078
Eric Laurentd4692962014-05-05 18:13:44 -07007079 // nothing to do if one input is already opened for this profile
7080 size_t input_index;
7081 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7082 desc = mInputs.valueAt(input_index);
7083 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007084 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007085 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007086 }
Eric Laurentd4692962014-05-05 18:13:44 -07007087 break;
7088 }
7089 }
7090 if (input_index != mInputs.size()) {
7091 continue;
7092 }
7093
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307094 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7095 ALOGV("%s skip opening input for mmap profile %s",
7096 __func__, profile->getTagName().c_str());
7097 continue;
7098 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007099 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307100 ALOGW("%s Max Input number %u already opened for this profile %s",
7101 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007102 continue;
7103 }
7104
Eric Laurentc71b11b2024-06-03 12:54:53 +00007105 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007106 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307107 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307108 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7109 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007110
Eric Laurentcf2c0212014-07-25 16:20:43 -07007111 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007112 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007113 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007114 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007115 mpClientInterface->setParameters(input, String8(param));
7116 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007117 }
jiabin12537fc2023-10-12 17:56:08 +00007118 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007119 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307120 ALOGW("%s direct input missing param for profile %s", __func__,
7121 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007122 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007123 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007124 }
7125
Eric Laurent0dd51852019-04-19 18:18:58 -07007126 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007127 addInput(input, desc);
7128 }
7129 } // endif input != 0
7130
Eric Laurentcf2c0212014-07-25 16:20:43 -07007131 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307132 ALOGW("%s could not open input for device %s on profile %s", __func__,
7133 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007134 profiles.removeAt(profile_index);
7135 profile_index--;
7136 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007137 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007138 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007139 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307140 ALOGV("%s: adding input %d for profile %s", __func__,
7141 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007142
7143 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307144 ALOGV("%s: closing input %d for profile %s", __func__,
7145 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007146 closeInput(input);
7147 }
Eric Laurentd4692962014-05-05 18:13:44 -07007148 }
7149 } // end scan profiles
7150
7151 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007152 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007153 return BAD_VALUE;
7154 }
7155 } else {
7156 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007157 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007158 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007159 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007160 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007161 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007162 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007163 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307164 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7165 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007166 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007167 }
7168 }
7169 }
7170 } // end disconnect
7171
7172 return NO_ERROR;
7173}
7174
7175
Eric Laurente0720872014-03-11 09:30:41 -07007176void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007177{
7178 ALOGV("closeOutput(%d)", output);
7179
François Gaffie1c878552018-11-22 16:53:21 +01007180 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7181 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007182 ALOGW("closeOutput() unknown output %d", output);
7183 return;
7184 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007185 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007186 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007187
Eric Laurente552edb2014-03-10 17:42:56 -07007188 // look for duplicated outputs connected to the output being removed.
7189 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007190 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7191 if (dupOutput->isDuplicated() &&
7192 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7193 sp<SwAudioOutputDescriptor> remainingOutput =
7194 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007195 // As all active tracks on duplicated output will be deleted,
7196 // and as they were also referenced on the other output, the reference
7197 // count for their stream type must be adjusted accordingly on
7198 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007199 const bool wasActive = remainingOutput->isActive();
7200 // Note: no-op on the closing output where all clients has already been set inactive
7201 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007202 // stop() will be a no op if the output is still active but is needed in case all
7203 // active streams refcounts where cleared above
7204 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007205 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007206 }
Eric Laurente552edb2014-03-10 17:42:56 -07007207 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7208 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7209
7210 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007211 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007212 }
7213 }
7214
Eric Laurent05b90f82014-08-27 15:32:29 -07007215 nextAudioPortGeneration();
7216
François Gaffie1c878552018-11-22 16:53:21 +01007217 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007218 if (index >= 0) {
7219 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007220 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7221 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007222 mAudioPatches.removeItemsAt(index);
7223 mpClientInterface->onAudioPatchListUpdate();
7224 }
7225
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007226 if (closingOutputWasActive) {
7227 closingOutput->stop();
7228 }
François Gaffie1c878552018-11-22 16:53:21 +01007229 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007230 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007231 for (const auto device : closingOutput->devices()) {
7232 device->setPreferredConfig(nullptr);
7233 }
7234 }
Eric Laurente552edb2014-03-10 17:42:56 -07007235
François Gaffie53615e22015-03-19 09:24:12 +01007236 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007237 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007238 if (closingOutput == mSpatializerOutput) {
7239 mSpatializerOutput.clear();
7240 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007241
7242 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7243 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007244 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007245 bool directOutputOpen = false;
7246 for (size_t i = 0; i < mOutputs.size(); i++) {
7247 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7248 directOutputOpen = true;
7249 break;
7250 }
7251 }
7252 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007253 ALOGV("no direct outputs open, reset MSD patches");
7254 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7255 // how output devices for patching are resolved. Avoid by caching and reusing the
7256 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7257 // devices to patch to. This may be complicated by the fact that devices may become
7258 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007259 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007260 }
7261 }
jiabin220eea12024-05-17 17:55:20 +00007262
7263 if (closingOutput->mPreferredAttrInfo != nullptr) {
7264 closingOutput->mPreferredAttrInfo->resetActiveClient();
7265 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007266}
7267
7268void AudioPolicyManager::closeInput(audio_io_handle_t input)
7269{
7270 ALOGV("closeInput(%d)", input);
7271
7272 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7273 if (inputDesc == NULL) {
7274 ALOGW("closeInput() unknown input %d", input);
7275 return;
7276 }
7277
Eric Laurent6a94d692014-05-20 11:18:06 -07007278 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007279
François Gaffie11d30102018-11-02 16:09:09 +01007280 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007281 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007282 if (index >= 0) {
7283 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007284 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7285 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007286 mAudioPatches.removeItemsAt(index);
7287 mpClientInterface->onAudioPatchListUpdate();
7288 }
7289
François Gaffie6ebbce02023-07-19 13:27:53 +02007290 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007291 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007292 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007293
François Gaffie11d30102018-11-02 16:09:09 +01007294 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7295 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007296 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007297 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007298 }
Eric Laurente552edb2014-03-10 17:42:56 -07007299}
7300
François Gaffie11d30102018-11-02 16:09:09 +01007301SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7302 const DeviceVector &devices,
7303 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007304{
7305 SortedVector<audio_io_handle_t> outputs;
7306
François Gaffie11d30102018-11-02 16:09:09 +01007307 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007308 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007309 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007310 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007311 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007312 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007313 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007314 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007315 outputs.add(openOutputs.keyAt(i));
7316 }
7317 }
7318 return outputs;
7319}
7320
Mikhail Naganov37977152018-07-11 15:54:44 -07007321void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7322{
7323 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7324 // output is suspended before any tracks are moved to it
7325 checkA2dpSuspend();
7326 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007327 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007328 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007329 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007330 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007331 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7332 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7333 // configuration changes will ultimately be rerouted correctly. We can still avoid
7334 // unnecessary rerouting by caching and reusing the arguments to
7335 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7336 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007337 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007338 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007339 // an event that changed routing likely occurred, inform upper layers
7340 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007341}
7342
François Gaffiec005e562018-11-06 15:04:49 +01007343bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7344 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007345{
François Gaffiec005e562018-11-06 15:04:49 +01007346 return mEngine->getProductStrategyForAttributes(lAttr) ==
7347 mEngine->getProductStrategyForAttributes(rAttr);
7348}
7349
Francois Gaffieff1eb522020-05-06 18:37:04 +02007350void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7351{
7352 for (size_t i = 0; i < mAudioSources.size(); i++) {
7353 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7354 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007355 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007356 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007357 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007358 }
7359 }
7360}
7361
7362void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7363{
7364 for (size_t i = 0; i < mAudioSources.size(); i++) {
7365 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7366 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7367 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7368 disconnectAudioSource(sourceDesc);
7369 }
7370 }
7371}
7372
François Gaffiec005e562018-11-06 15:04:49 +01007373void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7374{
7375 auto psId = mEngine->getProductStrategyForAttributes(attr);
7376
7377 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7378 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007379
François Gaffie11d30102018-11-02 16:09:09 +01007380 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7381 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007382
Eric Laurentc209fe42020-06-05 18:11:23 -07007383 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007384 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007385 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007386 // take into account dynamic audio policies related changes: if a client is now associated
7387 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007388 // invalidate clients on outputs that do not support all the newly selected devices for the
7389 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007390 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007391 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007392 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007393 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007394 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007395
Eric Laurentc209fe42020-06-05 18:11:23 -07007396 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7397 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7398 continue;
7399 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007400 if (!desc->supportsAllDevices(newDevices)) {
7401 invalidatedOutputs.push_back(desc);
7402 break;
7403 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007404 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007405 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007406 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7407 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7408 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007409 if (status == OK) {
7410 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7411 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7412 maxLatency = desc->latency();
7413 }
7414 invalidatedOutputs.push_back(desc);
7415 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007416 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007417 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007418 }
7419 }
7420
Eric Laurent56ed8842022-11-15 16:04:41 +01007421 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007422 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7423 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007424 for (audio_io_handle_t srcOut : srcOutputs) {
7425 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007426 if (desc == nullptr) continue;
7427
7428 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007429 maxLatency = desc->latency();
7430 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007431
Eric Laurent56ed8842022-11-15 16:04:41 +01007432 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007433 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007434 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007435 // a client on a non direct outputs has necessarily a linear PCM format
7436 // so we can call selectOutput() safely
7437 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7438 client->flags(),
7439 client->config().format,
7440 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007441 client->config().sample_rate,
7442 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007443 if (newOutput != srcOut) {
7444 invalidate = true;
7445 break;
7446 }
7447 } else {
7448 sp<IOProfile> profile = getProfileForOutput(newDevices,
7449 client->config().sample_rate,
7450 client->config().format,
7451 client->config().channel_mask,
7452 client->flags(),
7453 true /* directOnly */);
7454 if (profile != desc->mProfile) {
7455 invalidate = true;
7456 break;
7457 }
7458 }
7459 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007460 // mute strategy while moving tracks from one output to another
7461 if (invalidate) {
7462 invalidatedOutputs.push_back(desc);
7463 if (desc->isStrategyActive(psId)) {
7464 setStrategyMute(psId, true, desc);
7465 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7466 newDevices.types());
7467 }
Eric Laurente552edb2014-03-10 17:42:56 -07007468 }
François Gaffiec005e562018-11-06 15:04:49 +01007469 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007470 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007471 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007472 }
Eric Laurente552edb2014-03-10 17:42:56 -07007473 }
7474
Eric Laurent56ed8842022-11-15 16:04:41 +01007475 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7476 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7477 std::to_string(srcOutputs[0]).c_str(),
7478 std::to_string(dstOutputs[0]).c_str());
7479
François Gaffiec005e562018-11-06 15:04:49 +01007480 // Move effects associated to this stream from previous output to new output
7481 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007482 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007483 }
François Gaffiec005e562018-11-06 15:04:49 +01007484 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007485 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007486 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007487 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007488 desc->setTracksInvalidatedStatusByStrategy(psId);
7489 }
Eric Laurente552edb2014-03-10 17:42:56 -07007490 }
7491 }
7492}
7493
Eric Laurente0720872014-03-11 09:30:41 -07007494void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007495{
François Gaffiec005e562018-11-06 15:04:49 +01007496 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7497 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7498 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007499 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007500 }
Eric Laurente552edb2014-03-10 17:42:56 -07007501}
7502
Kevin Rocard153f92d2018-12-18 18:33:28 -08007503void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007504 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007505 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007506 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007507 for (size_t i = 0; i < mOutputs.size(); i++) {
7508 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7509 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007510 sp<AudioPolicyMix> primaryMix;
7511 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007512 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007513 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7514 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7515 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007516 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7517 for (auto &secondaryMix : secondaryMixes) {
7518 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7519 if (outputDesc != nullptr &&
7520 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7521 secondaryDescs.push_back(outputDesc);
7522 }
7523 }
7524
jiabinc44b3462022-12-08 12:52:31 -08007525 if (status != OK &&
7526 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7527 // When it failed to query secondary output, only invalidate the client that is not
7528 // MMAP. The reason is that MMAP stream will not support secondary output.
7529 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007530 } else if (!std::equal(
7531 client->getSecondaryOutputs().begin(),
7532 client->getSecondaryOutputs().end(),
7533 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007534 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7535 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007536 // If the format is not PCM, the tracks should be invalidated to get correct
7537 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007538 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007539 } else {
7540 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7541 std::vector<audio_io_handle_t> secondaryOutputIds;
7542 for (const auto &secondaryDesc: secondaryDescs) {
7543 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7544 weakSecondaryDescs.push_back(secondaryDesc);
7545 }
7546 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7547 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007548 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007549 }
7550 }
7551 }
jiabin10a03f12021-05-07 23:46:28 +00007552 if (!trackSecondaryOutputs.empty()) {
7553 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7554 }
jiabinc44b3462022-12-08 12:52:31 -08007555 if (!clientsToInvalidate.empty()) {
7556 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7557 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007558 }
7559}
7560
Eric Laurent2517af32020-11-25 15:31:27 +01007561bool AudioPolicyManager::isScoRequestedForComm() const {
7562 AudioDeviceTypeAddrVector devices;
7563 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7564 for (const auto &device : devices) {
7565 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7566 return true;
7567 }
7568 }
7569 return false;
7570}
7571
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007572bool AudioPolicyManager::isHearingAidUsedForComm() const {
7573 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7574 true /*fromCache*/);
7575 for (const auto &device : devices) {
7576 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7577 return true;
7578 }
7579 }
7580 return false;
7581}
7582
7583
Eric Laurente0720872014-03-11 09:30:41 -07007584void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007585{
François Gaffie53615e22015-03-19 09:24:12 +01007586 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007587 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007588 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007589 return;
7590 }
7591
Eric Laurent3a4311c2014-03-17 12:00:47 -07007592 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007593 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7594 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007595 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007596
7597 // if suspended, restore A2DP output if:
7598 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007599 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007600 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007601 //
Eric Laurentf732e072016-08-03 19:30:28 -07007602 // if not suspended, suspend A2DP output if:
7603 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007604 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007605 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007606 //
7607 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007608 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007609 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007610 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007611 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007612
7613 mpClientInterface->restoreOutput(a2dpOutput);
7614 mA2dpSuspended = false;
7615 }
7616 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007617 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007618 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007619 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007620 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007621
7622 mpClientInterface->suspendOutput(a2dpOutput);
7623 mA2dpSuspended = true;
7624 }
7625 }
7626}
7627
François Gaffie11d30102018-11-02 16:09:09 +01007628DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7629 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007630{
François Gaffiedb1755b2023-09-01 11:50:35 +02007631 if (outputDesc == nullptr) {
7632 return DeviceVector{};
7633 }
François Gaffie11d30102018-11-02 16:09:09 +01007634
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007635 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007636 if (index >= 0) {
7637 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007638 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007639 ALOGV("%s device %s forced by patch %d", __func__,
7640 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7641 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007642 }
7643 }
7644
Dean Wheatley514b4312020-06-17 21:45:00 +10007645 // Do not retrieve engine device for outputs through MSD
7646 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7647 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7648 return outputDesc->devices();
7649 }
7650
Eric Laurent97ac8712018-07-27 18:59:02 -07007651 // Honor explicit routing requests only if no client using default routing is active on this
7652 // input: a specific app can not force routing for other apps by setting a preferred device.
7653 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007654 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007655 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007656 if (device != nullptr) {
7657 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007658 }
7659
François Gaffiea807ef92018-11-05 10:44:33 +01007660 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7661 // of setForceUse / Default Bus device here
7662 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7663 if (device != nullptr) {
7664 return DeviceVector(device);
7665 }
7666
François Gaffiedb1755b2023-09-01 11:50:35 +02007667 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007668 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7669 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307670 auto hasStreamActive = [&](auto stream) {
7671 return hasStream(streams, stream) && isStreamActive(stream, 0);
7672 };
Eric Laurent484e9272018-06-07 17:29:23 -07007673
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307674 auto doGetOutputDevicesForVoice = [&]() {
7675 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007676 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307677 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007678 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7679 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307680 };
7681
7682 // With low-latency playing on speaker, music on WFD, when the first low-latency
7683 // output is stopped, getNewOutputDevices checks for a product strategy
7684 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007685 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307686 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7687 // stream is associated to the output descriptor.
7688 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7689 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7690 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7691 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007692 // Retrieval of devices for voice DL is done on primary output profile, cannot
7693 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007694 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007695 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7696 break;
7697 }
Eric Laurente552edb2014-03-10 17:42:56 -07007698 }
François Gaffiec005e562018-11-06 15:04:49 +01007699 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007700 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007701}
7702
François Gaffie11d30102018-11-02 16:09:09 +01007703sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7704 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007705{
François Gaffie11d30102018-11-02 16:09:09 +01007706 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007707
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007708 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007709 if (index >= 0) {
7710 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007711 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007712 ALOGV("getNewInputDevice() device %s forced by patch %d",
7713 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7714 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007715 }
7716 }
7717
Eric Laurent97ac8712018-07-27 18:59:02 -07007718 // Honor explicit routing requests only if no client using default routing is active on this
7719 // input: a specific app can not force routing for other apps by setting a preferred device.
7720 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007721 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7722 if (device != nullptr) {
7723 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007724 }
7725
Eric Laurentdc95a252018-04-12 12:46:56 -07007726 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007727 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007728 audio_attributes_t attributes;
7729 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007730 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007731 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7732 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007733 attributes = topClient->attributes();
7734 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007735 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007736 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007737 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7738 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007739 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007740 }
7741
Francois Gaffie716e1432019-01-14 16:58:59 +01007742 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7743 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007744 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007745 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007746 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007747 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007748
Eric Laurente552edb2014-03-10 17:42:56 -07007749 return device;
7750}
7751
Eric Laurent794fde22016-03-11 09:50:45 -08007752bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7753 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007754 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007755}
7756
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007757status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007758 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007759 if (devices == nullptr) {
7760 return BAD_VALUE;
7761 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007762
Andy Hung6d23c0f2022-02-16 09:37:15 -08007763 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007764 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7765 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007766 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007767 for (const auto& device : curDevices) {
7768 devices->push_back(device->getDeviceTypeAddr());
7769 }
7770 return NO_ERROR;
7771}
7772
Eric Laurente0720872014-03-11 09:30:41 -07007773void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007774 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007775 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007776 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007777 updateDevicesAndOutputs();
7778 break;
7779 default:
7780 break;
7781 }
7782}
7783
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007784uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007785
7786 // skip beacon mute management if a dedicated TTS output is available
7787 if (mTtsOutputAvailable) {
7788 return 0;
7789 }
7790
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007791 switch(event) {
7792 case STARTING_OUTPUT:
7793 mBeaconMuteRefCount++;
7794 break;
7795 case STOPPING_OUTPUT:
7796 if (mBeaconMuteRefCount > 0) {
7797 mBeaconMuteRefCount--;
7798 }
7799 break;
7800 case STARTING_BEACON:
7801 mBeaconPlayingRefCount++;
7802 break;
7803 case STOPPING_BEACON:
7804 if (mBeaconPlayingRefCount > 0) {
7805 mBeaconPlayingRefCount--;
7806 }
7807 break;
7808 }
7809
7810 if (mBeaconMuteRefCount > 0) {
7811 // any playback causes beacon to be muted
7812 return setBeaconMute(true);
7813 } else {
7814 // no other playback: unmute when beacon starts playing, mute when it stops
7815 return setBeaconMute(mBeaconPlayingRefCount == 0);
7816 }
7817}
7818
7819uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7820 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7821 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7822 // keep track of muted state to avoid repeating mute/unmute operations
7823 if (mBeaconMuted != mute) {
7824 // mute/unmute AUDIO_STREAM_TTS on all outputs
7825 ALOGV("\t muting %d", mute);
7826 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007827 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7828 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7829 ALOGV("\t no tts volume source available");
7830 return 0;
7831 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007832 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007833 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007834 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007835 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007836 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007837 maxLatency = latency;
7838 }
7839 }
7840 mBeaconMuted = mute;
7841 return maxLatency;
7842 }
7843 return 0;
7844}
7845
Eric Laurente0720872014-03-11 09:30:41 -07007846void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007847{
François Gaffiec005e562018-11-06 15:04:49 +01007848 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007849 mPreviousOutputs = mOutputs;
7850}
7851
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007852uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007853 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007854 uint32_t delayMs)
7855{
7856 // mute/unmute strategies using an incompatible device combination
7857 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7858 // if unmuting, unmute only after the specified delay
7859 if (outputDesc->isDuplicated()) {
7860 return 0;
7861 }
7862
7863 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007864 DeviceVector devices = outputDesc->devices();
7865 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007866
François Gaffiec005e562018-11-06 15:04:49 +01007867 auto productStrategies = mEngine->getOrderedProductStrategies();
7868 for (const auto &productStrategy : productStrategies) {
7869 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7870 DeviceVector curDevices =
7871 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7872 curDevices = curDevices.filter(outputDesc->supportedDevices());
7873 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007874 bool doMute = false;
7875
François Gaffiec005e562018-11-06 15:04:49 +01007876 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007877 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007878 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7879 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007880 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007881 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007882 }
Eric Laurent99401132014-05-07 19:48:15 -07007883 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007884 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007885 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007886 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007887 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007888 continue;
7889 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307890 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007891 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7892 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7893 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007894 if (mute) {
7895 // FIXME: should not need to double latency if volume could be applied
7896 // immediately by the audioflinger mixer. We must account for the delay
7897 // between now and the next time the audioflinger thread for this output
7898 // will process a buffer (which corresponds to one buffer size,
7899 // usually 1/2 or 1/4 of the latency).
7900 if (muteWaitMs < desc->latency() * 2) {
7901 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007902 }
7903 }
7904 }
7905 }
7906 }
7907 }
7908
Eric Laurent99401132014-05-07 19:48:15 -07007909 // temporary mute output if device selection changes to avoid volume bursts due to
7910 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007911 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007912 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007913
Eric Laurentdc462862016-07-19 12:29:53 -07007914 if (muteWaitMs < tempMuteWaitMs) {
7915 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007916 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007917
7918 // If recommended duration is defined, replace temporary mute duration to avoid
7919 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7920 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7921 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7922 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7923 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7924
François Gaffieaaac0fd2018-11-22 17:56:39 +01007925 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7926 // make sure that we do not start the temporary mute period too early in case of
7927 // delayed device change
7928 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7929 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007930 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007931 }
7932 }
7933
Eric Laurente552edb2014-03-10 17:42:56 -07007934 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7935 if (muteWaitMs > delayMs) {
7936 muteWaitMs -= delayMs;
7937 usleep(muteWaitMs * 1000);
7938 return muteWaitMs;
7939 }
7940 return 0;
7941}
7942
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307943uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7944 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007945 const DeviceVector &devices,
7946 bool force,
7947 int delayMs,
7948 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007949 bool requiresMuteCheck, bool requiresVolumeCheck,
7950 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007951{
jiabin3ff8d7d2022-12-13 06:27:44 +00007952 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307953 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7954 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7955 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007956 uint32_t muteWaitMs;
7957
7958 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307959 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007960 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307961 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007962 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007963 return muteWaitMs;
7964 }
Eric Laurente552edb2014-03-10 17:42:56 -07007965
7966 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007967 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007968 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007969 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007970
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307971 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7972 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007973
7974 if (!filteredDevices.isEmpty()) {
7975 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007976 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007977
7978 // if the outputs are not materially active, there is no need to mute.
7979 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007980 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007981 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307982 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7983 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007984 muteWaitMs = 0;
7985 }
Eric Laurente552edb2014-03-10 17:42:56 -07007986
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007987 bool outputRouted = outputDesc->isRouted();
7988
Eric Laurent79ea9582020-06-11 18:49:24 -07007989 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7990 // output profile or if new device is not supported AND previous device(s) is(are) still
7991 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007992 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307993 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7994 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007995 // restore previous device after evaluating strategy mute state
7996 outputDesc->setDevices(prevDevices);
7997 return muteWaitMs;
7998 }
7999
Eric Laurente552edb2014-03-10 17:42:56 -07008000 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008001 // the requested device is AUDIO_DEVICE_NONE
8002 // OR the requested device is the same as current device
8003 // AND force is not specified
8004 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008005 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008006 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308007 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8008 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8009 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008010 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308011 ALOGV("%s %s setting same device on routed output, force apply volumes",
8012 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008013 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8014 }
Eric Laurente552edb2014-03-10 17:42:56 -07008015 return muteWaitMs;
8016 }
8017
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308018 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8019 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008020
Eric Laurente552edb2014-03-10 17:42:56 -07008021 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008022 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008023 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008024 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008025 PatchBuilder patchBuilder;
8026 patchBuilder.addSource(outputDesc);
8027 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8028 for (const auto &filteredDevice : filteredDevices) {
8029 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008030 }
8031
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008032 // Add half reported latency to delayMs when muteWaitMs is null in order
8033 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008034 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8035 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8036 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008037 }
Eric Laurente552edb2014-03-10 17:42:56 -07008038
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008039 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8040 if (!skipMuteDelay) {
8041 // update stream volumes according to new device
8042 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8043 }
Eric Laurente552edb2014-03-10 17:42:56 -07008044
8045 return muteWaitMs;
8046}
8047
Eric Laurentc75307b2015-03-17 15:29:32 -07008048status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008049 int delayMs,
8050 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008051{
Eric Laurent6a94d692014-05-20 11:18:06 -07008052 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008053 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8054 return INVALID_OPERATION;
8055 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008056 if (patchHandle) {
8057 index = mAudioPatches.indexOfKey(*patchHandle);
8058 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008059 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008060 }
8061 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008062 return INVALID_OPERATION;
8063 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008064 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008065 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008066 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008067 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008068 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008069 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008070 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008071 return status;
8072}
8073
8074status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008075 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008076 bool force,
8077 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008078{
8079 status_t status = NO_ERROR;
8080
Eric Laurent1f2f2232014-06-02 12:01:23 -07008081 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008082 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8083 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008084
François Gaffie11d30102018-11-02 16:09:09 +01008085 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008086 PatchBuilder patchBuilder;
8087 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008088 // AUDIO_SOURCE_HOTWORD is for internal use only:
8089 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008090 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8091 auto result = usecase;
8092 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8093 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8094 }
8095 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07008096 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01008097 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008098 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008099 }
8100 }
8101 return status;
8102}
8103
Eric Laurent6a94d692014-05-20 11:18:06 -07008104status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8105 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008106{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008107 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008108 ssize_t index;
8109 if (patchHandle) {
8110 index = mAudioPatches.indexOfKey(*patchHandle);
8111 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008112 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008113 }
8114 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008115 return INVALID_OPERATION;
8116 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008117 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008118 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008119 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008120 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008121 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008122 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008123 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008124 return status;
8125}
8126
François Gaffie11d30102018-11-02 16:09:09 +01008127sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008128 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008129 audio_format_t& format,
8130 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008131 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008132{
8133 // Choose an input profile based on the requested capture parameters: select the first available
8134 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008135 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008136
Atneya Nair0f0a8032022-12-12 16:20:12 -08008137 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8138 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8139 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8140
8141 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008142
jiabin2fd710d2022-05-02 23:20:22 +00008143 for (;;) {
8144 sp<IOProfile> firstInexact = nullptr;
8145 uint32_t updatedSamplingRate = 0;
8146 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8147 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8148 for (const auto& hwModule : mHwModules) {
8149 for (const auto& profile : hwModule->getInputProfiles()) {
8150 // profile->log();
8151 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008152 if (profile->getCompatibilityScore(
8153 DeviceVector(device),
8154 samplingRate,
8155 &updatedSamplingRate,
8156 format,
8157 &updatedFormat,
8158 channelMask,
8159 &updatedChannelMask,
8160 // FIXME ugly cast
8161 (audio_output_flags_t) flags,
8162 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8163 samplingRate = updatedSamplingRate;
8164 format = updatedFormat;
8165 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008166 return profile;
8167 }
jiabin66acc432024-02-06 00:57:36 +00008168 if (firstInexact == nullptr
8169 && profile->getCompatibilityScore(
8170 DeviceVector(device),
8171 samplingRate,
8172 &updatedSamplingRate,
8173 format,
8174 &updatedFormat,
8175 channelMask,
8176 &updatedChannelMask,
8177 // FIXME ugly cast
8178 (audio_output_flags_t) flags,
8179 false /*exactMatchRequiredForInputFlags*/)
8180 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008181 firstInexact = profile;
8182 }
8183 }
8184 }
8185
8186 if (firstInexact != nullptr) {
8187 samplingRate = updatedSamplingRate;
8188 format = updatedFormat;
8189 channelMask = updatedChannelMask;
8190 return firstInexact;
8191 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8192 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8193 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8194 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8195 flags = AUDIO_INPUT_FLAG_NONE;
8196 } else { // fail
8197 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8198 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8199 samplingRate, format, channelMask, oriFlags);
8200 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008201 }
8202 }
jiabin2fd710d2022-05-02 23:20:22 +00008203
8204 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008205}
8206
Vlad Popa87e0e582024-05-20 18:49:20 -07008207float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8208 VolumeSource volumeSource,
8209 int index,
8210 const DeviceTypeSet &deviceTypes)
8211{
8212 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8213 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8214 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8215
8216 if (com_android_media_audio_abs_volume_index_fix()) {
8217 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8218 mAbsoluteVolumeDrivingStreams.end()) {
8219 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8220 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8221 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8222 ALOGD("%s: no group matching with %s", __FUNCTION__,
8223 toString(attributesToDriveAbs).c_str());
8224 return volumeDb;
8225 }
8226
8227 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8228 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8229 if (vsToDriveAbs == volumeSource) {
8230 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008231 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008232 } else {
8233 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8234 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8235 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8236 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8237 curvesAbs.getVolumeIndexMax());
8238 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8239 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8240 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8241 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8242 return newVolumeDb;
8243 }
8244 }
8245 return volumeDb;
8246 } else {
8247 return volumeDb;
8248 }
8249}
8250
François Gaffieaaac0fd2018-11-22 17:56:39 +01008251float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8252 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008253 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008254 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008255 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008256 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008257{
Vlad Popa9d482762024-06-21 16:40:23 -07008258 float volumeDb;
8259 if (adjustAttenuation) {
8260 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8261 } else {
8262 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8263 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008264 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8265 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8266
8267 if (!computeInternalInteraction) {
8268 return volumeDb;
8269 }
8270
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008271 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8272 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8273 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8274 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008275 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8276 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8277 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8278 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8279 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008280 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008281 mOutputs.isActive(ringVolumeSrc, 0)) {
8282 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008283 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008284 adjustAttenuation,
8285 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008286 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008287 }
8288
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008289 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008290 if ((volumeSource != callVolumeSrc && (isInCall() ||
8291 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008292 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008293 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8294 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008295 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8296 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8297 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008298 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008299 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008300 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008301 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008302 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008303 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008304 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008305 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8306 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8307 // programmatically muted.
8308 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8309 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8310 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008311 bool exemptFromCapping =
8312 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8313 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008314 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8315 volumeSource, volumeDb);
8316 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008317 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8318 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8319 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008320 }
8321 }
Eric Laurente552edb2014-03-10 17:42:56 -07008322 // if a headset is connected, apply the following rules to ring tones and notifications
8323 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008324 // - always attenuate notifications volume by 6dB
8325 // - attenuate ring tones volume by 6dB unless music is not playing and
8326 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008327 // - if music is playing, always limit the volume to current music volume,
8328 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008329 if (!Intersection(deviceTypes,
8330 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8331 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008332 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8333 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008334 ((volumeSource == alarmVolumeSrc ||
8335 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008336 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8337 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8338 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008339 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8340 curves.canBeMuted()) {
8341
Eric Laurente552edb2014-03-10 17:42:56 -07008342 // when the phone is ringing we must consider that music could have been paused just before
8343 // by the music application and behave as if music was active if the last music track was
8344 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008345 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8346 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008347 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008348 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008349 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8350 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008351 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008352 float musicVolDb = computeVolume(musicCurves,
8353 musicVolumeSrc,
8354 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008355 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008356 adjustAttenuation,
8357 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008358 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8359 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8360 if (volumeDb > minVolDb) {
8361 volumeDb = minVolDb;
8362 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008363 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008364 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8365 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008366 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8367 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8368 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8369 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008370 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008371 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008372 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8373 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008374 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8375 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008376 }
8377 }
jiabin9a3361e2019-10-01 09:38:30 -07008378 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008379 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008380 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008381 }
8382 }
8383
François Gaffie43c73442018-11-08 08:21:55 +01008384 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008385}
8386
Eric Laurent3839bc02018-07-10 18:33:34 -07008387int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008388 VolumeSource fromVolumeSource,
8389 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008390{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008391 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008392 return srcIndex;
8393 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008394 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8395 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008396 float minSrc = (float)srcCurves.getVolumeIndexMin();
8397 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8398 float minDst = (float)dstCurves.getVolumeIndexMin();
8399 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008400
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008401 // preserve mute request or correct range
8402 if (srcIndex < minSrc) {
8403 if (srcIndex == 0) {
8404 return 0;
8405 }
8406 srcIndex = minSrc;
8407 } else if (srcIndex > maxSrc) {
8408 srcIndex = maxSrc;
8409 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008410 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8411}
8412
François Gaffieaaac0fd2018-11-22 17:56:39 +01008413status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8414 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008415 int index,
8416 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008417 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008418 int delayMs,
8419 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008420{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008421 // do not change actual attributes volume if the attributes is muted
8422 if (outputDesc->isMuted(volumeSource)) {
8423 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8424 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008425 return NO_ERROR;
8426 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008427
Eric Laurentae6e88c2024-01-10 14:42:57 +01008428 bool isVoiceVolSrc;
8429 bool isBtScoVolSrc;
8430 if (!isVolumeConsistentForCalls(
8431 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008432 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008433 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008434 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008435 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008436
jiabin9a3361e2019-10-01 09:38:30 -07008437 if (deviceTypes.empty()) {
8438 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008439 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008440 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008441 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008442 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008443
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008444 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8445 ALOGE("invalid volume index range");
8446 return BAD_VALUE;
8447 }
8448
jiabin9a3361e2019-10-01 09:38:30 -07008449 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8450 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008451 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008452 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008453 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8454 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008455 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008456 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008457 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008458 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8459 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008460
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008461 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008462 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8463 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8464 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008465 }
Eric Laurente552edb2014-03-10 17:42:56 -07008466 return NO_ERROR;
8467}
8468
Eric Laurentae6e88c2024-01-10 14:42:57 +01008469void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008470 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008471 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008472 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008473 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008474 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008475 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8476 } else {
8477 voiceVolume = index == 0 ? 0.0 : 1.0;
8478 }
8479 if (voiceVolume != mLastVoiceVolume) {
8480 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8481 mLastVoiceVolume = voiceVolume;
8482 }
8483}
8484
8485bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8486 const DeviceTypeSet& deviceTypes,
8487 bool& isVoiceVolSrc,
8488 bool& isBtScoVolSrc,
8489 const char* caller) {
8490 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008491 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8492
Eric Laurentae6e88c2024-01-10 14:42:57 +01008493 const bool isScoRequested = isScoRequestedForComm();
8494 const bool isHAUsed = isHearingAidUsedForComm();
8495
Vlad Popa695b76b2024-06-14 16:49:25 -07008496 if (com_android_media_audio_replace_stream_bt_sco()) {
8497 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8498 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8499 (isScoRequested || isHAUsed);
8500 return true;
8501 }
8502
8503 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008504 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8505
8506 if ((callVolSrc != btScoVolSrc) &&
8507 ((isVoiceVolSrc && isScoRequested) ||
8508 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8509 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8510 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8511 volumeSource, isScoRequested ? " " : " not ");
8512 return false;
8513 }
8514 return true;
8515}
8516
Eric Laurentc75307b2015-03-17 15:29:32 -07008517void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008518 const DeviceTypeSet& deviceTypes,
8519 int delayMs,
8520 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008521{
jiabincd510522020-01-22 09:40:55 -08008522 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008523 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8524 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8525 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008526 curves.getVolumeIndex(deviceTypes),
8527 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008528 }
8529}
8530
François Gaffiec005e562018-11-06 15:04:49 +01008531void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8532 bool on,
8533 const sp<AudioOutputDescriptor>& outputDesc,
8534 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008535 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008536{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008537 std::vector<VolumeSource> sourcesToMute;
8538 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8539 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8540 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008541 VolumeSource source = toVolumeSource(attributes, false);
8542 if ((source != VOLUME_SOURCE_NONE) &&
8543 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8544 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008545 sourcesToMute.push_back(source);
8546 }
Eric Laurente552edb2014-03-10 17:42:56 -07008547 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008548 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008549 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008550 }
8551
Eric Laurente552edb2014-03-10 17:42:56 -07008552}
8553
François Gaffieaaac0fd2018-11-22 17:56:39 +01008554void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8555 bool on,
8556 const sp<AudioOutputDescriptor>& outputDesc,
8557 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008558 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008559{
jiabin9a3361e2019-10-01 09:38:30 -07008560 if (deviceTypes.empty()) {
8561 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008562 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008563 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008564 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008565 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008566 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008567 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008568 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8569 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008570 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008571 }
8572 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008573 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8574 // ignored
8575 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008576 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008577 if (!outputDesc->isMuted(volumeSource)) {
8578 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008579 return;
8580 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008581 if (outputDesc->decMuteCount(volumeSource) == 0) {
8582 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008583 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008584 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008585 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008586 delayMs);
8587 }
8588 }
8589}
8590
François Gaffie53615e22015-03-19 09:24:12 +01008591bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8592{
François Gaffiec005e562018-11-06 15:04:49 +01008593 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008594 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8595 return true;
8596 }
8597
8598 // has known usage?
8599 switch (paa->usage) {
8600 case AUDIO_USAGE_UNKNOWN:
8601 case AUDIO_USAGE_MEDIA:
8602 case AUDIO_USAGE_VOICE_COMMUNICATION:
8603 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8604 case AUDIO_USAGE_ALARM:
8605 case AUDIO_USAGE_NOTIFICATION:
8606 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8607 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8608 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8609 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8610 case AUDIO_USAGE_NOTIFICATION_EVENT:
8611 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8612 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8613 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8614 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008615 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008616 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008617 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008618 case AUDIO_USAGE_EMERGENCY:
8619 case AUDIO_USAGE_SAFETY:
8620 case AUDIO_USAGE_VEHICLE_STATUS:
8621 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008622 break;
8623 default:
8624 return false;
8625 }
8626 return true;
8627}
8628
François Gaffie2110e042015-03-24 08:41:51 +01008629audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8630{
8631 return mEngine->getForceUse(usage);
8632}
8633
Eric Laurent96d1dda2022-03-14 17:14:19 +01008634bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008635 return isStateInCall(mEngine->getPhoneState());
8636}
8637
Eric Laurent96d1dda2022-03-14 17:14:19 +01008638bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008639 return is_state_in_call(state);
8640}
8641
Eric Laurentf9cccec2022-11-16 19:12:00 +01008642bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008643 audio_mode_t mode = mEngine->getPhoneState();
8644 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008645 || (mode == AUDIO_MODE_CALL_SCREEN)
8646 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008647}
8648
Eric Laurentf9cccec2022-11-16 19:12:00 +01008649bool AudioPolicyManager::isInCallOrScreening() const {
8650 audio_mode_t mode = mEngine->getPhoneState();
8651 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8652}
8653
Eric Laurentd60560a2015-04-10 11:31:20 -07008654void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8655{
8656 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008657 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008658 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008659 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008660 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008661 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008662 }
8663 }
8664
8665 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8666 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8667 bool release = false;
8668 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8669 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8670 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8671 source->ext.device.type == deviceDesc->type()) {
8672 release = true;
8673 }
8674 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008675 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008676 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8677 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8678 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008679 sink->ext.device.type == deviceDesc->type() &&
8680 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8681 || strncmp(sink->ext.device.address, address,
8682 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008683 release = true;
8684 }
8685 }
8686 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008687 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8688 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008689 }
8690 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008691
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008692 mInputs.clearSessionRoutesForDevice(deviceDesc);
8693
Francois Gaffie716e1432019-01-14 16:58:59 +01008694 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008695}
8696
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008697void AudioPolicyManager::modifySurroundFormats(
8698 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008699 std::unordered_set<audio_format_t> enforcedSurround(
8700 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008701 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008702 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008703 allSurround.insert(pair.first);
8704 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8705 }
Phil Burk09bc4612016-02-24 15:58:15 -08008706
8707 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8708 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008709 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008710 // This is the resulting set of formats depending on the surround mode:
8711 // 'all surround' = allSurround
8712 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8713 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8714 // 'manual surround' = mManualSurroundFormats
8715 // AUTO: formats v 'enforced surround'
8716 // ALWAYS: formats v 'all surround' v 'enforced surround'
8717 // NEVER: formats ^ 'non-surround'
8718 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008719
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008720 std::unordered_set<audio_format_t> formatSet;
8721 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8722 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008723 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008724 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008725 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008726 formatSet.insert(*formatIter);
8727 }
8728 }
8729 } else {
8730 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8731 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008732 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008733
jiabin81772902018-04-02 17:52:27 -07008734 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008735 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008736 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8737 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8738 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008739 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008740 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8741 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8742 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008743 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008744 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008745 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008746 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008747 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008748 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008749}
8750
jiabin06e4bab2019-07-29 10:13:34 -07008751void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8752 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008753 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8754 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8755
8756 // If NEVER, then remove support for channelMasks > stereo.
8757 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008758 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8759 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008760 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008761 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008762 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008763 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008764 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008765 }
8766 }
jiabin81772902018-04-02 17:52:27 -07008767 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8768 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8769 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008770 bool supports5dot1 = false;
8771 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008772 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008773 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8774 supports5dot1 = true;
8775 break;
8776 }
8777 }
8778 // If not then add 5.1 support.
8779 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008780 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008781 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008782 }
Phil Burk09bc4612016-02-24 15:58:15 -08008783 }
8784}
8785
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008786void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008787 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008788 const sp<IOProfile>& profile) {
8789 if (!profile->hasDynamicAudioProfile()) {
8790 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008791 }
François Gaffie112b0af2015-11-19 16:13:25 +01008792
jiabin12537fc2023-10-12 17:56:08 +00008793 audio_port_v7 devicePort;
8794 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008795
jiabin12537fc2023-10-12 17:56:08 +00008796 audio_port_v7 mixPort;
8797 profile->toAudioPort(&mixPort);
8798 mixPort.ext.mix.handle = ioHandle;
8799
8800 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8801 if (status != NO_ERROR) {
8802 ALOGE("%s failed to query the attributes of the mix port", __func__);
8803 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008804 }
jiabin12537fc2023-10-12 17:56:08 +00008805
8806 std::set<audio_format_t> supportedFormats;
8807 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8808 supportedFormats.insert(mixPort.audio_profiles[i].format);
8809 }
8810 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8811 mReportedFormatsMap[devDesc] = formats;
8812
8813 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8814 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8815 modifySurroundFormats(devDesc, &formats);
8816 size_t modifiedNumProfiles = 0;
8817 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8818 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8819 formats.end()) {
8820 // Skip the format that is not present after modifying surround formats.
8821 continue;
8822 }
8823 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8824 sizeof(struct audio_profile));
8825 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8826 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8827 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8828 modifySurroundChannelMasks(&channels);
8829 std::copy(channels.begin(), channels.end(),
8830 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8831 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8832 }
8833 mixPort.num_audio_profiles = modifiedNumProfiles;
8834 }
8835 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008836}
Eric Laurentd60560a2015-04-10 11:31:20 -07008837
Mikhail Naganovdc769682018-05-04 15:34:08 -07008838status_t AudioPolicyManager::installPatch(const char *caller,
8839 audio_patch_handle_t *patchHandle,
8840 AudioIODescriptorInterface *ioDescriptor,
8841 const struct audio_patch *patch,
8842 int delayMs)
8843{
8844 ssize_t index = mAudioPatches.indexOfKey(
8845 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8846 *patchHandle : ioDescriptor->getPatchHandle());
8847 sp<AudioPatch> patchDesc;
8848 status_t status = installPatch(
8849 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8850 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008851 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008852 }
8853 return status;
8854}
8855
8856status_t AudioPolicyManager::installPatch(const char *caller,
8857 ssize_t index,
8858 audio_patch_handle_t *patchHandle,
8859 const struct audio_patch *patch,
8860 int delayMs,
8861 uid_t uid,
8862 sp<AudioPatch> *patchDescPtr)
8863{
8864 sp<AudioPatch> patchDesc;
8865 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8866 if (index >= 0) {
8867 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008868 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008869 }
8870
8871 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8872 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8873 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8874 if (status == NO_ERROR) {
8875 if (index < 0) {
8876 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008877 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008878 } else {
8879 patchDesc->mPatch = *patch;
8880 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008881 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008882 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008883 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008884 }
8885 nextAudioPortGeneration();
8886 mpClientInterface->onAudioPatchListUpdate();
8887 }
8888 if (patchDescPtr) *patchDescPtr = patchDesc;
8889 return status;
8890}
8891
jiabinbce0c1d2020-10-05 11:20:18 -07008892bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8893{
8894 const TrackClientVector activeClients = output->getActiveClients();
8895 if (activeClients.empty()) {
8896 return true;
8897 }
8898 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8899 if (index < 0) {
8900 ALOGE("%s, no audio patch found while there are active clients on output %d",
8901 __func__, output->getId());
8902 return false;
8903 }
8904 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8905 DeviceVector routedDevices;
8906 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8907 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8908 patchDesc->mPatch.sinks[i].id);
8909 if (device == nullptr) {
8910 ALOGE("%s, no audio device found with id(%d)",
8911 __func__, patchDesc->mPatch.sinks[i].id);
8912 return false;
8913 }
8914 routedDevices.add(device);
8915 }
8916 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008917 if (client->isInvalid()) {
8918 // No need to take care about invalidated clients.
8919 continue;
8920 }
jiabinbce0c1d2020-10-05 11:20:18 -07008921 sp<DeviceDescriptor> preferredDevice =
8922 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8923 if (mEngine->getOutputDevicesForAttributes(
8924 client->attributes(), preferredDevice, false) == routedDevices) {
8925 return false;
8926 }
8927 }
8928 return true;
8929}
8930
8931sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008932 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008933 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8934 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008935{
8936 for (const auto& device : devices) {
8937 // TODO: This should be checking if the profile supports the device combo.
8938 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008939 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8940 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008941 return nullptr;
8942 }
8943 }
8944 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8945 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07008946 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008947 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07008948 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008949 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008950 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008951 return nullptr;
8952 }
jiabin14b50cc2023-12-13 19:01:52 +00008953 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8954 auto portConfig = desc->getConfig();
8955 for (const auto& device : devices) {
8956 device->setPreferredConfig(&portConfig);
8957 }
8958 }
jiabinbce0c1d2020-10-05 11:20:18 -07008959
8960 // Here is where the out_set_parameters() for card & device gets called
8961 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8962 const audio_devices_t deviceType = device->type();
8963 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008964 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008965 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8966 mpClientInterface->setParameters(output, String8(param));
8967 free(param);
8968 }
jiabin12537fc2023-10-12 17:56:08 +00008969 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008970 if (!profile->hasValidAudioProfile()) {
8971 ALOGW("%s() missing param", __func__);
8972 desc->close();
8973 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008974 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8975 // Reopen the output with the best audio profile picked by APM when the profile supports
8976 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008977 desc->close();
8978 output = AUDIO_IO_HANDLE_NONE;
8979 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8980 profile->pickAudioProfile(
8981 config.sample_rate, config.channel_mask, config.format);
8982 config.offload_info.sample_rate = config.sample_rate;
8983 config.offload_info.channel_mask = config.channel_mask;
8984 config.offload_info.format = config.format;
8985
Haofan Wangf6e304f2024-07-09 23:06:58 -07008986 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
8987 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008988 if (status != NO_ERROR) {
8989 return nullptr;
8990 }
8991 }
8992
8993 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008994 setOutputDevices(__func__, desc,
8995 devices,
8996 true,
8997 0,
8998 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008999 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9000 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9001
jiabinbce0c1d2020-10-05 11:20:18 -07009002 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9003 sp<AudioPolicyMix> policyMix;
9004 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9005 policyMix->setOutput(desc);
9006 desc->mPolicyMix = policyMix;
9007 } else {
9008 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009009 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009010 }
9011
baek.kim -61c20122022-07-27 10:05:32 +00009012 } else if (hasPrimaryOutput() && speaker != nullptr
9013 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009014 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9015 // no duplicated output for:
9016 // - direct outputs
9017 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009018 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009019 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9020
9021 //TODO: configure audio effect output stage here
9022
9023 // open a duplicating output thread for the new output and the primary output
9024 sp<SwAudioOutputDescriptor> dupOutputDesc =
9025 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9026 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9027 if (status == NO_ERROR) {
9028 // add duplicated output descriptor
9029 addOutput(duplicatedOutput, dupOutputDesc);
9030 } else {
9031 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9032 mPrimaryOutput->mIoHandle, output);
9033 desc->close();
9034 removeOutput(output);
9035 nextAudioPortGeneration();
9036 return nullptr;
9037 }
9038 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009039 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9040 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9041 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009042 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009043 }
jiabinbce0c1d2020-10-05 11:20:18 -07009044 return desc;
9045}
9046
jiabinf1c73972022-04-14 16:28:52 -07009047status_t AudioPolicyManager::getDevicesForAttributes(
9048 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
9049 // Devices are determined in the following precedence:
9050 //
9051 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9052 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9053 //
9054 // If no such dynamic policy then
9055 // 2) Devices containing an active client using setPreferredDevice
9056 // with same strategy as the attributes.
9057 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9058 //
9059 // If no corresponding active client with setPreferredDevice then
9060 // 3) Devices associated with the strategy determined by the attributes
9061 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9062 //
9063 // See related getOutputForAttrInt().
9064
9065 // check dynamic policies but only for primary descriptors (secondary not used for audible
9066 // audio routing, only used for duplication for playback capture)
9067 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009068 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009069 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009070 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9071 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9072 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009073 if (status != OK) {
9074 return status;
9075 }
9076
9077 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9078 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9079 // as they are unaffected by device/stream volume
9080 // (per SwAudioOutputDescriptor::isFixedVolume()).
9081 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9082 ) {
9083 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9084 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9085 devices.add(deviceDesc);
9086 } else {
9087 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9088 // which selects setPreferredDevice if active. This means forVolume call
9089 // will take an active setPreferredDevice, if such exists.
9090
9091 devices = mEngine->getOutputDevicesForAttributes(
9092 attr, nullptr /* preferredDevice */, false /* fromCache */);
9093 }
9094
9095 if (forVolume) {
9096 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9097 // for single volume control in AudioService (such relationship should exist if
9098 // SPEAKER_SAFE is present).
9099 //
9100 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9101 DeviceVector speakerSafeDevices =
9102 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9103 if (!speakerSafeDevices.isEmpty()) {
9104 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9105 devices.remove(speakerSafeDevices);
9106 }
9107 }
9108
9109 return NO_ERROR;
9110}
9111
9112status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9113 AudioProfileVector& audioProfiles,
9114 uint32_t flags,
9115 bool isInput) {
9116 for (const auto& hwModule : mHwModules) {
9117 // the MSD module checks for different conditions
9118 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9119 continue;
9120 }
9121 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9122 : hwModule->getOutputProfiles();
9123 for (const auto& profile : ioProfiles) {
9124 if (!profile->areAllDevicesSupported(devices) ||
9125 !profile->isCompatibleProfileForFlags(
9126 flags, false /*exactMatchRequiredForInputFlags*/)) {
9127 continue;
9128 }
9129 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9130 }
9131 }
9132
9133 if (!isInput) {
9134 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9135 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9136 if (msdModule != nullptr) {
9137 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9138 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9139 for (const auto &profile: msdModule->getOutputProfiles()) {
9140 if (!profile->asAudioPort()->isDirectOutput()) {
9141 continue;
9142 }
9143 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9144 }
9145 } else {
9146 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9147 }
9148 }
9149 }
9150
9151 return NO_ERROR;
9152}
9153
jiabin3ff8d7d2022-12-13 06:27:44 +00009154sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9155 const audio_config_t *config,
9156 audio_output_flags_t flags,
9157 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009158 closeOutput(outputDesc->mIoHandle);
9159 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9160 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9161 if (preferredOutput == nullptr) {
9162 ALOGE("%s failed to reopen output device=%d, caller=%s",
9163 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009164 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009165 return preferredOutput;
9166}
9167
9168void AudioPolicyManager::reopenOutputsWithDevices(
9169 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9170 for (const auto& [output, devices] : outputsToReopen) {
9171 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9172 closeOutput(output);
9173 openOutputWithProfileAndDevice(desc->mProfile, devices);
9174 }
jiabina84c3d32022-12-02 18:59:55 +00009175}
9176
jiabinc44b3462022-12-08 12:52:31 -08009177PortHandleVector AudioPolicyManager::getClientsForStream(
9178 audio_stream_type_t streamType) const {
9179 PortHandleVector clients;
9180 for (size_t i = 0; i < mOutputs.size(); ++i) {
9181 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9182 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9183 }
9184 return clients;
9185}
9186
9187void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9188 PortHandleVector clients;
9189 for (auto stream : streams) {
9190 PortHandleVector clientsForStream = getClientsForStream(stream);
9191 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9192 }
9193 mpClientInterface->invalidateTracks(clients);
9194}
9195
jiabin220eea12024-05-17 17:55:20 +00009196void AudioPolicyManager::updateClientsInternalMute(
9197 const sp<android::SwAudioOutputDescriptor> &desc) {
9198 if (!desc->isBitPerfect() ||
9199 !com::android::media::audioserver::
9200 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9201 // This is only used for bit perfect output now.
9202 return;
9203 }
9204 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9205 bool bitPerfectClientInternalMute = false;
9206 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9207 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9208 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9209 bitPerfectClient = client;
9210 continue;
9211 }
9212 bool muted = false;
9213 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9214 // System sound is muted.
9215 muted = true;
9216 } else {
9217 bitPerfectClientInternalMute = true;
9218 }
9219 if (client->setInternalMute(muted)) {
9220 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9221 if (!result.ok()) {
9222 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9223 continue;
9224 }
9225 media::TrackInternalMuteInfo info;
9226 info.portId = result.value();
9227 info.muted = client->getInternalMute();
9228 clientsInternalMute.push_back(std::move(info));
9229 }
9230 }
9231 if (bitPerfectClient != nullptr &&
9232 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9233 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9234 if (result.ok()) {
9235 media::TrackInternalMuteInfo info;
9236 info.portId = result.value();
9237 info.muted = bitPerfectClient->getInternalMute();
9238 clientsInternalMute.push_back(std::move(info));
9239 } else {
9240 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9241 __func__, bitPerfectClient->portId());
9242 }
9243 }
9244 if (!clientsInternalMute.empty()) {
9245 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9246 status != NO_ERROR) {
9247 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9248 }
9249 }
9250}
9251
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009252} // namespace android