blob: addbd10e328c87fa446c2ea59ff95bfd45121924 [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>
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000043#include <android/media/audio/common/AudioMMapPolicy.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010044#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080045#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010046#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080047#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070048#include <cutils/bitops.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"
Shunkai Yao2dcd60c2024-08-27 21:08:53 +000058#include "SpatializerHelper.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010059#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070060
Eric Laurent3b73df72014-03-11 09:06:29 -070061namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070062
Marvin Raminbdefaf02023-11-01 09:10:32 +010063
64namespace audio_flags = android::media::audiopolicy;
65
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010066using android::media::audio::common::AudioDevice;
67using android::media::audio::common::AudioDeviceAddress;
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000068using android::media::audio::common::AudioDeviceDescription;
69using android::media::audio::common::AudioMMapPolicy;
70using android::media::audio::common::AudioMMapPolicyInfo;
71using android::media::audio::common::AudioMMapPolicyType;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010072using android::media::audio::common::AudioPortDeviceExt;
73using android::media::audio::common::AudioPortExt;
Eric Laurentb2fb4102024-06-21 12:25:26 +000074using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000075using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070076
Eric Laurentdc462862016-07-19 12:29:53 -070077//FIXME: workaround for truncated touch sounds
78// to be removed when the problem is handled by system UI
79#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070080
81// Largest difference in dB on earpiece in call between the voice volume and another
82// media / notification / system volume.
83constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
84
jiabin06e4bab2019-07-29 10:13:34 -070085template <typename T>
86bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
87{
88 if (left.size() != right.size()) {
89 return false;
90 }
91 for (size_t index = 0; index < right.size(); index++) {
92 if (left[index] != right[index]) {
93 return false;
94 }
95 }
96 return true;
97}
98
99template <typename T>
100bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
101{
102 return !(left == right);
103}
104
Eric Laurente552edb2014-03-10 17:42:56 -0700105// ----------------------------------------------------------------------------
106// AudioPolicyInterface implementation
107// ----------------------------------------------------------------------------
108
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
110 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
111 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800112 nextAudioPortGeneration();
113 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800114}
115
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
117 audio_policy_dev_state_t state,
118 const char* device_address,
119 const char* device_name,
120 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800121 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100122 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
123 status == OK) {
124 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
125 } else {
126 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
127 return status;
128 }
129}
130
Ping Tsai2a5a5242024-08-16 13:39:10 +0800131status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000132 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200133{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 audio_port_v7 devicePort;
135 device->toAudioPort(&devicePort);
Ping Tsai2a5a5242024-08-16 13:39:10 +0800136 status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
137 ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
138 static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
139
140 return status;
François Gaffie44481e72016-04-20 07:49:57 +0200141}
142
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100143status_t AudioPolicyManager::setDeviceConnectionStateInt(
144 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
145 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100146 if (port.ext.getTag() != AudioPortExt::device) {
147 return BAD_VALUE;
148 }
149 audio_devices_t device_type;
150 std::string device_address;
151 if (status_t status = aidl2legacy_AudioDevice_audio_device(
152 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
153 status != OK) {
154 return status;
155 };
156 const char* device_name = port.name.c_str();
157 // connect/disconnect only 1 device at a time
158 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
159 return BAD_VALUE;
160
161 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
162 device_type, device_address.c_str(), device_name, encodedFormat,
163 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000164 if (device == nullptr) {
165 return INVALID_OPERATION;
166 }
167 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
168 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
169 }
170 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100171}
172
François Gaffie11d30102018-11-02 16:09:09 +0100173status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800174 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100175 const char* device_address,
176 const char* device_name,
177 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800178 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100179 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
180 status == OK) {
181 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
182 } else {
183 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
184 return status;
185 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700186}
Paul McLeane743a472015-01-28 11:07:31 -0800187
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700188status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
189 audio_policy_dev_state_t state)
190{
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700192 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700193 SortedVector <audio_io_handle_t> outputs;
194
François Gaffie11d30102018-11-02 16:09:09 +0100195 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700196
Eric Laurente552edb2014-03-10 17:42:56 -0700197 // save a copy of the opened output descriptors before any output is opened or closed
198 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
199 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100200
201 bool wasLeUnicastActive = isLeUnicastActive();
202
Eric Laurente552edb2014-03-10 17:42:56 -0700203 switch (state)
204 {
205 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800206 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700207 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100208 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700209 return INVALID_OPERATION;
210 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800211 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700212 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurente552edb2014-03-10 17:42:56 -0700214 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200215 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700216 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
218
François Gaffie44481e72016-04-20 07:49:57 +0200219 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
220 // parameters on newly connected devices (instead of opening the outputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800221 if (broadcastDeviceConnectionState(
222 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
223 mAvailableOutputDevices.remove(device);
224 mHwModules.cleanUpForDevice(device);
225 ALOGE("%s() device %s format %x connection failed", __func__,
226 device->toString().c_str(), device->getEncodedFormat());
227 return INVALID_OPERATION;
228 }
François Gaffie44481e72016-04-20 07:49:57 +0200229
François Gaffie11d30102018-11-02 16:09:09 +0100230 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
231 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200232
jiabinc0048632023-04-27 22:04:31 +0000233 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700234
235 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700236 return INVALID_OPERATION;
237 }
François Gaffie2110e042015-03-24 08:41:51 +0100238
jiabin1c4794b2020-05-05 10:08:05 -0700239 // Populate encapsulation information when a output device is connected.
240 device->setEncapsulationInfoFromHal(mpClientInterface);
241
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700242 // outputs should never be empty here
243 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
244 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100245 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800246
Eric Laurent3ae5f312015-02-03 17:12:08 -0800247 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700249 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100251 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700252 return INVALID_OPERATION;
253 }
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700256
jiabinc0048632023-04-27 22:04:31 +0000257 // Notify the HAL to prepare to disconnect device
258 broadcastDeviceConnectionState(
259 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700260
Eric Laurente552edb2014-03-10 17:42:56 -0700261 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100262 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700263
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100264 mOutputs.clearSessionRoutesForDevice(device);
265
François Gaffie11d30102018-11-02 16:09:09 +0100266 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100267
jiabinc0048632023-04-27 22:04:31 +0000268 // Send Disconnect to HALs
269 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
270
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800271 // Reset active device codec
272 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
273
Kriti Dangef6be8f2020-11-05 11:58:19 +0100274 // remove device from mReportedFormatsMap cache
275 mReportedFormatsMap.erase(device);
276
jiabina84c3d32022-12-02 18:59:55 +0000277 // remove preferred mixer configurations
278 mPreferredMixerAttrInfos.erase(device->getId());
279
Eric Laurente552edb2014-03-10 17:42:56 -0700280 } break;
281
282 default:
François Gaffie11d30102018-11-02 16:09:09 +0100283 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700284 return BAD_VALUE;
285 }
286
Eric Laurent736a1022019-03-27 18:28:46 -0700287 // Propagate device availability to Engine
288 setEngineDeviceConnectionState(device, state);
289
Eric Laurentae970022019-01-29 14:25:04 -0800290 // No need to evaluate playback routing when connecting a remote submix
291 // output device used by a dynamic policy of type recorder as no
292 // playback use case is affected.
293 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700294 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800295 for (audio_io_handle_t output : outputs) {
296 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800297 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
298 if (policyMix != nullptr
299 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000300 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800301 doCheckForDeviceAndOutputChanges = false;
302 break;
303 }
304 }
305 }
306
307 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 // outputs must be closed after checkOutputForAllStrategies() is executed
309 if (!outputs.isEmpty()) {
310 for (audio_io_handle_t output : outputs) {
311 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100312 // close unused outputs after device disconnection or direct outputs that have
313 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200314 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200315 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
316 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200317 (desc->mDirectOpenCount == 0))
318 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
319 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200320 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700321 closeOutput(output);
322 }
Eric Laurente552edb2014-03-10 17:42:56 -0700323 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700324 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
325 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700326 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700327 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800328 };
329
330 if (doCheckForDeviceAndOutputChanges) {
331 checkForDeviceAndOutputChanges(checkCloseOutputs);
332 } else {
333 checkCloseOutputs();
334 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100335 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100336 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700337 const DeviceVector activeMediaDevices =
338 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000339 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700340 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700341 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530342 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
343 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100344 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700345 // do not force device change on duplicated output because if device is 0, it will
346 // also force a device 0 for the two outputs it is duplicated to which may override
347 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100348 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100349 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700350 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700351 // always force when disconnecting (a non-duplicated device)
352 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000353 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000354 // If the device is using preferred mixer attributes, the output need to reopen
355 // with default configuration when the new selected devices are different from
356 // current routing devices
357 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
358 continue;
359 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530360 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700361 }
jiabinbce0c1d2020-10-05 11:20:18 -0700362 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000363 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700364 desc->supportsDevicesForPlayback(activeMediaDevices)) {
365 // Reopen the output to query the dynamic profiles when there is not active
366 // clients or all active clients will be rerouted. Otherwise, set the flag
367 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
368 // can be reopened to query dynamic profiles when all clients are inactive.
369 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000370 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700371 } else {
372 desc->mPendingReopenToQueryProfiles = true;
373 }
374 }
375 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
376 // Clear the flag that previously set for re-querying profiles.
377 desc->mPendingReopenToQueryProfiles = false;
378 }
379 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000380 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700381
Eric Laurentd60560a2015-04-10 11:31:20 -0700382 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700384 }
385
Eric Laurent96d1dda2022-03-14 17:14:19 +0100386 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
387
Eric Laurent72aa32f2014-05-30 18:51:48 -0700388 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530389 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700390 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700391 } // end if is output device
392
Eric Laurente552edb2014-03-10 17:42:56 -0700393 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700394 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700396 switch (state)
397 {
398 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700399 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700400 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100401 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700402 return INVALID_OPERATION;
403 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700404
Jaideep Sharma33173202024-06-18 17:46:45 +0530405 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
406
Eric Laurent0dd51852019-04-19 18:18:58 -0700407 if (mAvailableInputDevices.add(device) < 0) {
408 return NO_MEMORY;
409 }
410
François Gaffie44481e72016-04-20 07:49:57 +0200411 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
412 // parameters on newly connected devices (instead of opening the inputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800413 if (broadcastDeviceConnectionState(
414 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
415 mAvailableInputDevices.remove(device);
416 mHwModules.cleanUpForDevice(device);
417 ALOGE("%s() device %s format %x connection failed", __func__,
418 device->toString().c_str(), device->getEncodedFormat());
419 return INVALID_OPERATION;
420 }
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700421 // Propagate device availability to Engine
422 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200423
Eric Laurent0dd51852019-04-19 18:18:58 -0700424 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700425 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
426
Eric Laurent0dd51852019-04-19 18:18:58 -0700427 mAvailableInputDevices.remove(device);
428
jiabinc0048632023-04-27 22:04:31 +0000429 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100430
431 mHwModules.cleanUpForDevice(device);
432
Eric Laurentd4692962014-05-05 18:13:44 -0700433 return INVALID_OPERATION;
434 }
435
Eric Laurentd4692962014-05-05 18:13:44 -0700436 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700437
438 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700439 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700440 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100441 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700442 return INVALID_OPERATION;
443 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700444
François Gaffie11d30102018-11-02 16:09:09 +0100445 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700446
jiabinc0048632023-04-27 22:04:31 +0000447 // Notify the HAL to prepare to disconnect device
448 broadcastDeviceConnectionState(
449 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700450
François Gaffie11d30102018-11-02 16:09:09 +0100451 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700452
453 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100454
jiabinc0048632023-04-27 22:04:31 +0000455 // Set Disconnect to HALs
456 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
457
Kriti Dangef6be8f2020-11-05 11:58:19 +0100458 // remove device from mReportedFormatsMap cache
459 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700460
461 // Propagate device availability to Engine
462 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700463 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700464
465 default:
François Gaffie11d30102018-11-02 16:09:09 +0100466 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700467 return BAD_VALUE;
468 }
469
Eric Laurent0dd51852019-04-19 18:18:58 -0700470 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700471 // As the input device list can impact the output device selection, update
472 // getDeviceForStrategy() cache
473 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700474
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100475 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200476 // Reconnect Audio Source
477 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
478 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
479 checkAudioSourceForAttributes(attributes);
480 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700481 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100482 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700483 }
484
Eric Laurentb52c1522014-05-20 11:27:36 -0700485 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530486 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700487 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700488 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700489
François Gaffie11d30102018-11-02 16:09:09 +0100490 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700491 return BAD_VALUE;
492}
493
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100494status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
495 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800496 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700497 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
498 devDescr->setName(device_name);
499 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100500}
501
Eric Laurent736a1022019-03-27 18:28:46 -0700502void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
503 audio_policy_dev_state_t state) {
504
505 // the Engine does not have to know about remote submix devices used by dynamic audio policies
506 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
507 return;
508 }
509 mEngine->setDeviceConnectionState(device, state);
510}
511
512
Eric Laurente0720872014-03-11 09:30:41 -0700513audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100514 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700515{
Eric Laurent634b7142016-04-20 13:48:02 -0700516 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
518 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700519 (strlen(device_address) != 0)/*matchAddress*/);
520
521 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100522 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700523 device, device_address);
524 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
525 }
François Gaffie53615e22015-03-19 09:24:12 +0100526
Eric Laurent3a4311c2014-03-17 12:00:47 -0700527 DeviceVector *deviceVector;
528
Eric Laurente552edb2014-03-10 17:42:56 -0700529 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700530 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700531 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700532 deviceVector = &mAvailableInputDevices;
533 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100534 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700535 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700536 }
Eric Laurent634b7142016-04-20 13:48:02 -0700537
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 return (deviceVector->getDevice(
539 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700540 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800541}
542
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800543status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
544 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800545 const char *device_name,
546 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800547{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800548 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
549 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800550
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800551 // connect/disconnect only 1 device at a time
552 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
553
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800554 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700555 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800556 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800557 // Nothing to do: device is not connected
558 return NO_ERROR;
559 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800560 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700562 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800563 // configure codecs.
564 // Handle two specific cases by sending a set parameter to
565 // configure A2DP codecs. No need to toggle device state.
566 // Case 1: A2DP active device switches from primary to primary
567 // module
568 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100569 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700570 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800571 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
572 if (availablePrimaryOutputDevices().contains(devDesc) &&
573 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100574 bool isA2dp = audio_is_a2dp_out_device(device);
575 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
576 : String8(AudioParameter::keyReconfigLeSupported);
577 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800578 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100579 int isReconfigSupported;
580 repliedParameters.getInt(supportKey, isReconfigSupported);
581 if (isReconfigSupported) {
582 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
583 : String8(AudioParameter::keyReconfigLe);
584 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800585 param.add(key, String8("true"));
586 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
587 devDesc->setEncodedFormat(encodedFormat);
588 return NO_ERROR;
589 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700590 }
591 }
cnx421bd2dcc42020-07-11 14:58:44 +0800592 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000593 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800594 for (size_t i = 0; i < mOutputs.size(); i++) {
595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000596 // mute media strategies to avoid sending the music tail into
597 // the earpiece or headset.
598 if (desc->isStrategyActive(musicStrategy)) {
599 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
600 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
601 tempRecommendedMuteDuration : desc->latency() * 4;
602 if (muteWaitMs < tempMuteDurationMs) {
603 muteWaitMs = tempMuteDurationMs;
604 }
605 }
cnx421bd2dcc42020-07-11 14:58:44 +0800606 setStrategyMute(musicStrategy, true, desc);
607 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
608 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
609 nullptr, true /*fromCache*/).types());
610 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000611 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
612 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
613 // happens after the actual device switch.
614 if (muteWaitMs > 0) {
615 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
616 usleep(muteWaitMs * 1000);
617 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800618 // Toggle the device state: UNAVAILABLE -> AVAILABLE
619 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100620 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800621 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800622 device_address, device_name,
623 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800624 if (status != NO_ERROR) {
625 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
626 status);
627 return status;
628 }
629
630 status = setDeviceConnectionState(device,
631 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800632 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800633 if (status != NO_ERROR) {
634 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
635 status);
636 return status;
637 }
638
639 return NO_ERROR;
640}
641
Pattydd807582021-11-04 21:01:03 +0800642status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
643 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800644{
Pattydd807582021-11-04 21:01:03 +0800645 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800646 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800647 std::unordered_set<audio_format_t> formatSet;
648 sp<HwModule> primaryModule =
649 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700650 if (primaryModule == nullptr) {
651 ALOGE("%s() unable to get primary module", __func__);
652 return NO_INIT;
653 }
Pattydd807582021-11-04 21:01:03 +0800654
655 DeviceTypeSet audioDeviceSet;
656
657 switch(device) {
658 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
659 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
660 break;
661 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800662 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
663 break;
664 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
665 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800666 break;
667 default:
668 ALOGE("%s() device type 0x%08x not supported", __func__, device);
669 return BAD_VALUE;
670 }
671
jiabin9a3361e2019-10-01 09:38:30 -0700672 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800673 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800674 for (const auto& device : declaredDevices) {
675 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800676 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800677 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800678 return status;
679}
680
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100681DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
682{
683 DeviceVector rxSinkdevices{};
684 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
685 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
686 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
687 auto rxSinkDevice = rxSinkdevices.itemAt(0);
688 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
689 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
690 // retrieve Rx Source device descriptor
691 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
692 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
693
694 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
695 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
696 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
697 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
698 return DeviceVector(rxSinkDevice);
699 }
700 }
701 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
702 // the device returned is not necessarily reachable via this output
703 // (filter later by setOutputDevices())
704 return getNewOutputDevices(mPrimaryOutput, fromCache);
705}
706
707status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
708{
François Gaffiedb1755b2023-09-01 11:50:35 +0200709 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100710 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
711 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
712 }
713 return INVALID_OPERATION;
714}
715
716status_t AudioPolicyManager::updateCallRoutingInternal(
717 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700718{
719 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100720 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700721 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200722 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700723 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100724 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700725 }
François Gaffie11d30102018-11-02 16:09:09 +0100726
Francois Gaffie716e1432019-01-14 16:58:59 +0100727 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100728 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200729
Eric Laurentb2fb4102024-06-21 12:25:26 +0000730 if (!fix_call_audio_patch()) {
731 disconnectTelephonyAudioSource(mCallRxSourceClient);
732 disconnectTelephonyAudioSource(mCallTxSourceClient);
733 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200734
735 if (rxDevices.isEmpty()) {
736 ALOGW("%s() no selected output device", __func__);
737 return INVALID_OPERATION;
738 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000739 if (txSourceDevice == nullptr) {
740 ALOGE("%s() selected input device not available", __func__);
741 return INVALID_OPERATION;
742 }
François Gaffiec005e562018-11-06 15:04:49 +0100743
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100744 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100745 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700746
François Gaffie9eb18552018-11-05 10:33:26 +0100747 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700748 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100749 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700750 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100751 // retrieve Rx Source and Tx Sink device descriptors
752 sp<DeviceDescriptor> rxSourceDevice =
753 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
754 String8(),
755 AUDIO_FORMAT_DEFAULT);
756 sp<DeviceDescriptor> txSinkDevice =
757 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
758 String8(),
759 AUDIO_FORMAT_DEFAULT);
760
761 // RX and TX Telephony device are declared by Primary Audio HAL
762 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
763 (telephonyRxModule->getHalVersionMajor() >= 3)) {
764 if (rxSourceDevice == 0 || txSinkDevice == 0) {
765 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100766 ALOGE("%s() no telephony Tx and/or RX device", __func__);
767 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100768 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100769 // createAudioPatchInternal now supports both HW / SW bridging
770 createRxPatch = true;
771 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100772 } else {
773 // If the RX device is on the primary HW module, then use legacy routing method for
774 // voice calls via setOutputDevice() on primary output.
775 // Otherwise, create two audio patches for TX and RX path.
776 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
777 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700778 // If the TX device is also on the primary HW module, setOutputDevice() will take care
779 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100780 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
781 (txSinkDevice != 0);
782 }
783 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
784 // Otherwise, create two audio patches for TX and RX path.
785 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000786 if (fix_call_audio_patch()) {
787 disconnectTelephonyAudioSource(mCallRxSourceClient);
788 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200789 if (!hasPrimaryOutput()) {
790 ALOGW("%s() no primary output available", __func__);
791 return INVALID_OPERATION;
792 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530793 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700794 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000795 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800796 // If the TX device is on the primary HW module but RX device is
797 // on other HW module, SinkMetaData of telephony input should handle it
798 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700799 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700800 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100801 // terminate active capture if on the same HW module as the call TX source device
802 // FIXME: would be better to refine to only inputs whose profile connects to the
803 // call TX device but this information is not in the audio patch and logic here must be
804 // symmetric to the one in startInput()
805 for (const auto& activeDesc : mInputs.getActiveInputs()) {
806 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
807 closeActiveClients(activeDesc);
808 }
809 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200810 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000811 } else if (fix_call_audio_patch()) {
812 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800813 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100814 if (waitMs != nullptr) {
815 *waitMs = muteWaitMs;
816 }
817 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800818}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700819
Mikhail Naganov100f0122018-11-29 11:22:16 -0800820bool AudioPolicyManager::isDeviceOfModule(
821 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
822 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
823 if (module != 0) {
824 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
825 .indexOf(devDesc) != NAME_NOT_FOUND
826 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
827 .indexOf(devDesc) != NAME_NOT_FOUND;
828 }
829 return false;
830}
831
David Lif85c5e32024-07-01 13:14:10 +0000832void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200833{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000834 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
835
836 if (fix_call_audio_patch()) {
837 if (mCallRxSourceClient != nullptr) {
838 DeviceVector rxDevices =
839 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
840 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
841 "connectTelephonyRxAudioSource(): no device found for call RX source");
842 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
843 if (mCallRxSourceClient->isConnected()
844 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
845 return;
846 }
847 disconnectTelephonyAudioSource(mCallRxSourceClient);
848 }
849 } else {
850 disconnectTelephonyAudioSource(mCallRxSourceClient);
851 }
852
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200853 const struct audio_port_config source = {
854 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
855 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
856 };
Eric Laurent541a2002024-01-15 18:11:42 +0100857 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000858
Eric Laurentccbd7872024-06-20 12:34:15 +0000859 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000860 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100861 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
862 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000863 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
864 mCallRxSourceClient->srcDevice()->toString().c_str(),
865 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200866 ALOGE_IF(mCallRxSourceClient == nullptr,
867 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200868}
869
Francois Gaffie601801d2021-06-22 13:27:39 +0200870void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200871{
Francois Gaffie601801d2021-06-22 13:27:39 +0200872 if (clientDesc == nullptr) {
873 return;
874 }
875 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
876 "%s error stopping audio source", __func__);
877 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200878}
879
880void AudioPolicyManager::connectTelephonyTxAudioSource(
881 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
882 uint32_t delayMs)
883{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200884 if (srcDevice == nullptr || sinkDevice == nullptr) {
885 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
886 return;
887 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000888
889 if (fix_call_audio_patch()) {
890 if (mCallTxSourceClient != nullptr) {
891 if (mCallTxSourceClient->isConnected()
892 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
893 return;
894 }
895 disconnectTelephonyAudioSource(mCallTxSourceClient);
896 }
897 } else {
898 disconnectTelephonyAudioSource(mCallTxSourceClient);
899 }
900
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200901 PatchBuilder patchBuilder;
902 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000903
Francois Gaffie601801d2021-06-22 13:27:39 +0200904 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200905 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
906
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200907 struct audio_port_config source = {};
908 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100909 mCallTxSourceClient = new SourceClientDescriptor(
910 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000911 mCommunnicationStrategy, toVolumeSource(aa), true,
912 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100913 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
914
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200915 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
916 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200917 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
918 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200919 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000920 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
921 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200922 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200923 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200924 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200925}
926
Eric Laurente0720872014-03-11 09:30:41 -0700927void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700928{
929 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100930 // store previous phone state for management of sonification strategy below
931 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100932 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100933
934 if (mEngine->setPhoneState(state) != NO_ERROR) {
935 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700936 return;
937 }
François Gaffie2110e042015-03-24 08:41:51 +0100938 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700939 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700940 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700941 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800942 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700943 }
944
François Gaffie2110e042015-03-24 08:41:51 +0100945 /**
946 * Switching to or from incall state or switching between telephony and VoIP lead to force
947 * routing command.
948 */
Eric Laurent74b71512019-11-06 17:21:57 -0800949 bool force = ((isStateInCall(oldState) != isStateInCall(state))
950 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700951
952 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700953 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700954
Eric Laurente552edb2014-03-10 17:42:56 -0700955 int delayMs = 0;
956 if (isStateInCall(state)) {
957 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100958 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
959 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700960 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700961 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 // mute media and sonification strategies and delay device switch by the largest
963 // latency of any output where either strategy is active.
964 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100965 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
966 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
967 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700968 (delayMs < (int)desc->latency()*2)) {
969 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700970 }
François Gaffiec005e562018-11-06 15:04:49 +0100971 setStrategyMute(musicStrategy, true, desc);
972 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
973 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
974 nullptr, true /*fromCache*/).types());
975 setStrategyMute(sonificationStrategy, true, desc);
976 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
977 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
978 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
980 }
981
François Gaffiedb1755b2023-09-01 11:50:35 +0200982 if (state == AUDIO_MODE_IN_CALL) {
983 (void)updateCallRouting(false /*fromCache*/, delayMs);
984 } else {
985 if (oldState == AUDIO_MODE_IN_CALL) {
986 disconnectTelephonyAudioSource(mCallRxSourceClient);
987 disconnectTelephonyAudioSource(mCallTxSourceClient);
988 }
989 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100990 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
991 // force routing command to audio hardware when ending call
992 // even if no device change is needed
993 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
994 rxDevices = mPrimaryOutput->devices();
995 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530996 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700997 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700998 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700999
jiabin3ff8d7d2022-12-13 06:27:44 +00001000 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001001 // reevaluate routing on all outputs in case tracks have been started during the call
1002 for (size_t i = 0; i < mOutputs.size(); i++) {
1003 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01001004 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00001005 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
1006 && desc->mPreferredAttrInfo != nullptr) {
1007 // If the output is using preferred mixer attributes and the audio mode is not normal,
1008 // the output need to reopen with default configuration.
1009 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
1010 continue;
1011 }
Francois Gaffie601801d2021-06-22 13:27:39 +02001012 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
1013 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05301014 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +02001015 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001016 }
1017 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001018 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001019
Eric Laurent96d1dda2022-03-14 17:14:19 +01001020 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1021
Eric Laurente552edb2014-03-10 17:42:56 -07001022 if (isStateInCall(state)) {
1023 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001024 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001025 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
1027
1028 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001029 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1030 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001031}
1032
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001033audio_mode_t AudioPolicyManager::getPhoneState() {
1034 return mEngine->getPhoneState();
1035}
1036
Eric Laurente0720872014-03-11 09:30:41 -07001037void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001038 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001039{
François Gaffie2110e042015-03-24 08:41:51 +01001040 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001041 if (config == mEngine->getForceUse(usage)) {
1042 return;
1043 }
Eric Laurente552edb2014-03-10 17:42:56 -07001044
François Gaffie2110e042015-03-24 08:41:51 +01001045 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1046 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1047 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001048 }
François Gaffie2110e042015-03-24 08:41:51 +01001049 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1050 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1051 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001052
1053 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001054 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001055
Eric Laurent22fcda22019-05-17 16:28:47 -07001056 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1057 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001058 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001059 }
1060
Eric Laurentdc462862016-07-19 12:29:53 -07001061 //FIXME: workaround for truncated touch sounds
1062 // to be removed when the problem is handled by system UI
1063 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001064 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1065 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1066 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001067
1068 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001069 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001070}
1071
Eric Laurente0720872014-03-11 09:30:41 -07001072void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001073{
1074 ALOGV("setSystemProperty() property %s, value %s", property, value);
1075}
1076
Dorin Drimusecc9f422022-03-09 17:57:40 +01001077// Find an MSD output profile compatible with the parameters passed.
1078// When "directOnly" is set, restrict search to profiles for direct outputs.
1079sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1080 const DeviceVector& devices,
1081 uint32_t samplingRate,
1082 audio_format_t format,
1083 audio_channel_mask_t channelMask,
1084 audio_output_flags_t flags,
1085 bool directOnly)
1086{
1087 flags = getRelevantFlags(flags, directOnly);
1088
1089 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1090 if (msdModule != nullptr) {
1091 // for the msd module check if there are patches to the output devices
1092 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1093 HwModuleCollection modules;
1094 modules.add(msdModule);
1095 return searchCompatibleProfileHwModules(
1096 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1097 flags, directOnly);
1098 }
1099 }
1100 return nullptr;
1101}
1102
Michael Chana94fbb22018-04-24 14:31:19 +10001103// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1104// search to profiles for direct outputs.
1105sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001106 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001107 uint32_t samplingRate,
1108 audio_format_t format,
1109 audio_channel_mask_t channelMask,
1110 audio_output_flags_t flags,
1111 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001112{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001113 flags = getRelevantFlags(flags, directOnly);
1114
1115 return searchCompatibleProfileHwModules(
1116 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1117}
1118
1119audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1120 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001121 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001122 // only retain flags that will drive the direct output profile selection
1123 // if explicitly requested
1124 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001125 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1127 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001128 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001129 return flags;
1130}
Eric Laurent861a6282015-05-18 15:40:16 -07001131
Dorin Drimusecc9f422022-03-09 17:57:40 +01001132sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1133 const HwModuleCollection& hwModules,
1134 const DeviceVector& devices,
1135 uint32_t samplingRate,
1136 audio_format_t format,
1137 audio_channel_mask_t channelMask,
1138 audio_output_flags_t flags,
1139 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001140 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001141 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001142 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001143 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001144 samplingRate, NULL /*updatedSamplingRate*/,
1145 format, NULL /*updatedFormat*/,
1146 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001147 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001148 continue;
1149 }
1150 // reject profiles not corresponding to a device currently available
1151 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1152 continue;
1153 }
1154 // reject profiles if connected device does not support codec
1155 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1156 continue;
1157 }
1158 if (!directOnly) {
1159 return curProfile;
1160 }
1161
1162 // when searching for direct outputs, if several profiles are compatible, give priority
1163 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001164 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001165 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001166 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001167 }
1168 profile = curProfile;
1169 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1170 break;
1171 }
Eric Laurente552edb2014-03-10 17:42:56 -07001172 }
1173 }
Eric Laurent861a6282015-05-18 15:40:16 -07001174 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001175}
1176
Eric Laurentfa0f6742021-08-17 18:39:44 +02001177sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001178 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001179{
1180 for (const auto& hwModule : mHwModules) {
1181 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001182 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001183 continue;
1184 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001185 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001186 // reject profiles not corresponding to a device currently available
1187 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1188 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1189 continue;
1190 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001191 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1192 != devices.size()) {
1193 continue;
1194 }
1195 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001196 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1197 return curProfile;
1198 }
1199 }
1200 return nullptr;
1201}
1202
Eric Laurentf4e63452017-11-06 19:31:46 +00001203audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001204{
François Gaffiec005e562018-11-06 15:04:49 +01001205 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001206
1207 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1208 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1209 // format, flags, etc. This may result in some discrepancy for functions that utilize
1210 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1211 // and AudioSystem::getOutputSamplingRate().
1212
François Gaffie11d30102018-11-02 16:09:09 +01001213 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001214 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov806170e2024-09-05 17:26:50 -07001215 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001216 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1217 }
1218 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001219
François Gaffie11d30102018-11-02 16:09:09 +01001220 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1221 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001222 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001223}
1224
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001225status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1226 const audio_attributes_t *srcAttr,
1227 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001228{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001229 if (srcAttr != NULL) {
1230 if (!isValidAttributes(srcAttr)) {
1231 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1232 __func__,
1233 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1234 srcAttr->tags);
1235 return BAD_VALUE;
1236 }
1237 *dstAttr = *srcAttr;
1238 } else {
1239 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1240 ALOGE("%s: invalid stream type", __func__);
1241 return BAD_VALUE;
1242 }
François Gaffiec005e562018-11-06 15:04:49 +01001243 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001244 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001245
1246 // Only honor audibility enforced when required. The client will be
1247 // forced to reconnect if the forced usage changes.
1248 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001249 dstAttr->flags = static_cast<audio_flags_mask_t>(
1250 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001251 }
1252
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001253 return NO_ERROR;
1254}
1255
Kevin Rocard153f92d2018-12-18 18:33:28 -08001256status_t AudioPolicyManager::getOutputForAttrInt(
1257 audio_attributes_t *resultAttr,
1258 audio_io_handle_t *output,
1259 audio_session_t session,
1260 const audio_attributes_t *attr,
1261 audio_stream_type_t *stream,
1262 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001263 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001264 audio_output_flags_t *flags,
1265 audio_port_handle_t *selectedDeviceId,
1266 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001267 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001268 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001269 bool *isSpatialized,
1270 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001271{
François Gaffiec005e562018-11-06 15:04:49 +01001272 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001273 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001274 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001275 const sp<DeviceDescriptor> requestedDevice =
1276 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1277
Eric Laurent8a1095a2019-11-08 14:44:16 -08001278 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001279 *isSpatialized = false;
1280
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001281 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1282 if (status != NO_ERROR) {
1283 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001284 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001285 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001286 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001287 }
François Gaffiec005e562018-11-06 15:04:49 +01001288 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001289
François Gaffiec005e562018-11-06 15:04:49 +01001290 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1291 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001292
Oscar Azucena873d10f2023-01-12 18:34:42 -08001293 bool usePrimaryOutputFromPolicyMixes = false;
1294
Kevin Rocard153f92d2018-12-18 18:33:28 -08001295 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1296 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1297 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001298 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001299 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1300 .channel_mask = config->channel_mask,
1301 .format = config->format,
1302 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001303 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001304 mAvailableOutputDevices, requestedDevice, primaryMix,
1305 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001306 if (status != OK) {
1307 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001308 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001309
Kevin Rocard153f92d2018-12-18 18:33:28 -08001310 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001311 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001312 && (!audio_is_linear_pcm(config->format) ||
1313 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001314 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001315 return BAD_VALUE;
1316 }
1317 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001318 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001319 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1320 primaryMix->mDeviceAddress,
1321 AUDIO_FORMAT_DEFAULT);
1322 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001323 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001324 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1325 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001326 // if a direct output can be opened to deliver the track's multi-channel content to the
1327 // output rather than being downmixed by the primary output, then use this direct
1328 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1329 // mix.
1330 bool tryDirectForChannelMask = policyDesc != nullptr
1331 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1332 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001333 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001334 audio_io_handle_t newOutput;
1335 status = openDirectOutput(
1336 *stream, session, config,
1337 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001338 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001339 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001340 policyDesc = mOutputs.valueFor(newOutput);
1341 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001342 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001343 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001344 policyDesc = nullptr;
1345 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001346 }
1347 if (policyDesc != nullptr) {
1348 policyDesc->mPolicyMix = primaryMix;
1349 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001350 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1351 : AUDIO_PORT_HANDLE_NONE;
1352 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1353 // Remove direct flag as it is not on a direct output.
1354 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1355 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001356
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001357 ALOGV("getOutputForAttr() returns output %d", *output);
1358 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1359 *outputType = API_OUT_MIX_PLAYBACK;
1360 } else {
1361 *outputType = API_OUTPUT_LEGACY;
1362 }
1363 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001364 } else {
1365 if (policyMixDevice != nullptr) {
1366 ALOGE("%s, try to use primary mix but no output found", __func__);
1367 return INVALID_OPERATION;
1368 }
1369 // Fallback to default engine selection as the selected primary mix device is not
1370 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001371 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001372 }
François Gaffiec005e562018-11-06 15:04:49 +01001373 // Virtual sources must always be dynamicaly or explicitly routed
1374 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1375 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1376 return BAD_VALUE;
1377 }
1378 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1379 // in order to let the choice of the order to future vendor engine
1380 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001381
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001382 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001383 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001384 }
1385
Nadav Barb2f18162018-07-18 13:01:53 +03001386 // Set incall music only if device was explicitly set, and fallback to the device which is
1387 // chosen by the engine if not.
1388 // FIXME: provide a more generic approach which is not device specific and move this back
1389 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001390 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001391 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001392 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001393 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001394 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001395 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001396 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001397 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001398 }
1399 }
1400
François Gaffiec005e562018-11-06 15:04:49 +01001401 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1402 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1403 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001404
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001405 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001406 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001407 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001408 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001409 ALOGV("%s() Using MSD devices %s instead of devices %s",
1410 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001411 } else {
1412 *output = AUDIO_IO_HANDLE_NONE;
1413 }
1414 }
1415 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001416 sp<PreferredMixerAttributesInfo> info = nullptr;
1417 if (outputDevices.size() == 1) {
1418 info = getPreferredMixerAttributesInfo(
1419 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001420 mEngine->getProductStrategyForAttributes(*resultAttr),
1421 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001422 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1423 // and it is currently active.
1424 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001425 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001426 info = nullptr;
1427 }
jiabin8a096672024-09-18 18:20:24 +00001428
1429 if (info != nullptr && info->isBitPerfect() &&
1430 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1431 AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1432 // Reject direct request if a preferred mixer config in use is bit-perfect.
1433 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1434 __func__);
1435 return BAD_VALUE;
1436 }
1437
jiabin220eea12024-05-17 17:55:20 +00001438 if (com::android::media::audioserver::
1439 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1440 if (info != nullptr && info->getUid() == uid &&
1441 info->configMatches(*config) &&
1442 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1443 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1444 [this, &outputDevices](audio_usage_t usage) {
1445 return mOutputs.isUsageActiveOnDevice(
1446 usage, outputDevices[0]); }))) {
1447 // Bit-perfect request is not allowed when the phone mode is not normal or
1448 // there is any higher priority user case active.
1449 return INVALID_OPERATION;
1450 }
1451 }
jiabina84c3d32022-12-02 18:59:55 +00001452 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001453 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001454 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001455 // The client will be active if the client is currently preferred mixer owner and the
1456 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001457 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001458 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001459 && info->getUid() == uid
1460 && *output != AUDIO_IO_HANDLE_NONE
1461 // When bit-perfect output is selected for the preferred mixer attributes owner,
1462 // only need to consider the config matches.
1463 && mOutputs.valueFor(*output)->isConfigurationMatched(
1464 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001465
1466 if (*isBitPerfect) {
1467 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1468 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001469 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001470 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001471 AudioProfileVector profiles;
1472 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1473 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001474 const auto channels = profiles[0]->getChannels();
1475 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1476 config->channel_mask = *channels.begin();
1477 }
1478 const auto sampleRates = profiles[0]->getSampleRates();
1479 if (!sampleRates.empty() &&
1480 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1481 config->sample_rate = *sampleRates.begin();
1482 }
jiabinf1c73972022-04-14 16:28:52 -07001483 config->format = profiles[0]->getFormat();
1484 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001485 return INVALID_OPERATION;
1486 }
Paul McLeanaa981192015-03-21 09:55:15 -07001487
François Gaffiec005e562018-11-06 15:04:49 +01001488 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001489 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001490 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001491 *selectedDeviceId = outputDevice->getId();
1492 break;
1493 }
1494 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001495
Eric Laurent8a1095a2019-11-08 14:44:16 -08001496 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1497 *outputType = API_OUTPUT_TELEPHONY_TX;
1498 } else {
1499 *outputType = API_OUTPUT_LEGACY;
1500 }
1501
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001502 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1503
1504 return NO_ERROR;
1505}
1506
1507status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1508 audio_io_handle_t *output,
1509 audio_session_t session,
1510 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001511 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001512 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001513 audio_output_flags_t *flags,
1514 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001515 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001516 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001517 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001518 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001519 bool *isBitPerfect,
Vlad Popa1e865e62024-08-15 19:11:42 -07001520 float *volume,
1521 bool *muted)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001522{
1523 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1524 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1525 return INVALID_OPERATION;
1526 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001527 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001528 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001529 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001530 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001531 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001532 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001533 const sp<DeviceDescriptor> requestedDevice =
1534 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1535
1536 // Prevent from storing invalid requested device id in clients
1537 const audio_port_handle_t sanitizedRequestedPortId =
1538 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1539 *selectedDeviceId = sanitizedRequestedPortId;
1540
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001541 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001542 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001543 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1544 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001545 if (status != NO_ERROR) {
1546 return status;
1547 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001548 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001549 if (secondaryOutputs != nullptr) {
1550 for (auto &secondaryMix : secondaryMixes) {
1551 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1552 if (outputDesc != nullptr &&
1553 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1554 secondaryOutputs->push_back(outputDesc->mIoHandle);
1555 weakSecondaryOutputDescs.push_back(outputDesc);
1556 }
1557 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001558 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001559
Eric Laurent8fc147b2018-07-22 19:13:55 -07001560 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001561 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001562 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001563 };
jiabin4ef93452019-09-10 14:29:54 -07001564 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001565
Eric Laurentc209fe42020-06-05 18:11:23 -07001566 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001567 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001568 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001569 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001570 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001571 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001572 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001573 std::move(weakSecondaryOutputDescs),
1574 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001575 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001576
Andy Hung6b137d12024-08-27 22:35:17 +00001577 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
Vlad Popa1e865e62024-08-15 19:11:42 -07001578 *muted = outputDesc->isMutedByGroup(toVolumeSource(resultAttr));
Andy Hung6b137d12024-08-27 22:35:17 +00001579
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001580 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1581 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001582
Eric Laurente83b55d2014-11-14 10:06:21 -08001583 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001584}
1585
Eric Laurentc529cf62020-04-17 18:19:10 -07001586status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1587 audio_session_t session,
1588 const audio_config_t *config,
1589 audio_output_flags_t flags,
1590 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001591 audio_io_handle_t *output,
1592 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001593
1594 *output = AUDIO_IO_HANDLE_NONE;
1595
1596 // skip direct output selection if the request can obviously be attached to a mixed output
1597 // and not explicitly requested
1598 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1599 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1600 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1601 return NAME_NOT_FOUND;
1602 }
1603
Mikhail Naganov806170e2024-09-05 17:26:50 -07001604 // Reject flag combinations that do not make sense. Note that the requested flags might not
1605 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1606 // combine the requested flags with its own flags, yielding an unsupported combination.
1607 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1608 return NAME_NOT_FOUND;
1609 }
1610
Eric Laurentc529cf62020-04-17 18:19:10 -07001611 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1612 // This prevents creating an offloaded track and tearing it down immediately after start
1613 // when audioflinger detects there is an active non offloadable effect.
1614 // FIXME: We should check the audio session here but we do not have it in this context.
1615 // This may prevent offloading in rare situations where effects are left active by apps
1616 // in the background.
1617 sp<IOProfile> profile;
1618 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1619 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1620 profile = getProfileForOutput(
1621 devices, config->sample_rate, config->format, config->channel_mask,
1622 flags, true /* directOnly */);
1623 }
1624
1625 if (profile == nullptr) {
1626 return NAME_NOT_FOUND;
1627 }
1628
1629 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1630 for (size_t i = 0; i < mOutputs.size(); i++) {
1631 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1632 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1633 // reuse direct output if currently open by the same client
1634 // and configured with same parameters
1635 if ((config->sample_rate == desc->getSamplingRate()) &&
1636 (config->format == desc->getFormat()) &&
1637 (config->channel_mask == desc->getChannelMask()) &&
1638 (session == desc->mDirectClientSession)) {
1639 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301640 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001641 mOutputs.keyAt(i), session);
1642 *output = mOutputs.keyAt(i);
1643 return NO_ERROR;
1644 }
1645 }
1646 }
1647
1648 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001649 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301650 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1651 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001652 return NAME_NOT_FOUND;
1653 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1654 // MMAP gracefully handles lack of an exclusive track resource by mixing
1655 // above the audio framework. For AAudio to know that the limit is reached,
1656 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301657 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1658 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001659 return NAME_NOT_FOUND;
1660 } else {
1661 // Close outputs on this profile, if available, to free resources for this request
1662 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1663 const auto desc = mOutputs.valueAt(i);
1664 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301665 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1666 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001667 closeOutput(desc->mIoHandle);
1668 }
1669 }
1670 }
1671 }
1672
1673 // Unable to close streams to find free resources for this request
1674 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301675 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1676 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001677 return NAME_NOT_FOUND;
1678 }
1679
Atneya Nairb16666a2023-12-11 20:18:33 -08001680 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001681
Michael Chan6fb34492020-12-08 15:44:49 +11001682 // An MSD patch may be using the only output stream that can service this request. Release
1683 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001684 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001685
Eric Laurentf1f22e72021-07-13 14:04:14 +02001686 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001687 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001688 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001689
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001690 // only accept an output with the requested parameters, unless the format can be IEC61937
1691 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1692 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1693 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1694 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001695 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001696 (!ignoreRequestedParametersCheck &&
1697 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1698 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1699 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001700 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1701 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1702 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1703 config->channel_mask, outputDesc->getChannelMask());
1704 if (*output != AUDIO_IO_HANDLE_NONE) {
1705 outputDesc->close();
1706 }
1707 // fall back to mixer output if possible when the direct output could not be open
1708 if (audio_is_linear_pcm(config->format) &&
1709 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1710 return NAME_NOT_FOUND;
1711 }
1712 *output = AUDIO_IO_HANDLE_NONE;
1713 return BAD_VALUE;
1714 }
1715 outputDesc->mDirectOpenCount = 1;
1716 outputDesc->mDirectClientSession = session;
1717
1718 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001719 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1720 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1721 hwModule->getHalVersionMajor() >= 3) {
1722 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1723 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001724 mPreviousOutputs = mOutputs;
1725 ALOGV("%s returns new direct output %d", __func__, *output);
1726 mpClientInterface->onAudioPortListUpdate();
1727 return NO_ERROR;
1728}
1729
François Gaffie11d30102018-11-02 16:09:09 +01001730audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1731 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001732 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001733 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001734 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001735 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001736 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001737 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001738 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001739{
Andy Hungc88b0642018-04-27 15:42:35 -07001740 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001741
jiabine375d412019-02-26 12:54:53 -08001742 // Discard haptic channel mask when forcing muting haptic channels.
1743 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001744 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1745 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001746
Eric Laurente552edb2014-03-10 17:42:56 -07001747 // open a direct output if required by specified parameters
1748 //force direct flag if offload flag is set: offloading implies a direct output stream
1749 // and all common behaviors are driven by checking only the direct flag
1750 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001751 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1752 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001753 }
Nadav Bar766fb022018-01-07 12:18:03 +02001754 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1755 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001756 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001757
1758 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1759
Eric Laurente83b55d2014-11-14 10:06:21 -08001760 // only allow deep buffering for music stream type
1761 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001762 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001763 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001764 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001765 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001766 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001767 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001768 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001769 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001770 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001771 audio_is_linear_pcm(config->format) &&
1772 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001773 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001774 AUDIO_OUTPUT_FLAG_DIRECT);
1775 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001776 }
Eric Laurente552edb2014-03-10 17:42:56 -07001777
Carter Hsua3abb402021-10-26 11:11:20 +08001778 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1779 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1780 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1781 }
1782
Eric Laurentf9230d52024-01-26 18:49:09 +01001783 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001784 // was specified and offload or direct playback is not explicitly requested, and there is no
1785 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001786 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001787 if (mSpatializerOutput != nullptr &&
1788 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1789 prefMixerConfigInfo == nullptr &&
1790 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1791 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001792 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001793 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001794 }
1795
Eric Laurentc529cf62020-04-17 18:19:10 -07001796 audio_config_t directConfig = *config;
1797 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001798
1799 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1800 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001801 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001802 return output;
1803 }
1804
Eric Laurent14cbfca2016-03-17 09:42:16 -07001805 // A request for HW A/V sync cannot fallback to a mixed output because time
1806 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001807 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001808 return AUDIO_IO_HANDLE_NONE;
1809 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001810 // A request for Tuner cannot fallback to a mixed output
1811 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1812 return AUDIO_IO_HANDLE_NONE;
1813 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001814
Eric Laurente552edb2014-03-10 17:42:56 -07001815 // ignoring channel mask due to downmix capability in mixer
1816
1817 // open a non direct output
1818
1819 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001820 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001821 // get which output is suitable for the specified stream. The actual
1822 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001823 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001824 if (prefMixerConfigInfo != nullptr) {
1825 for (audio_io_handle_t outputHandle : outputs) {
1826 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1827 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1828 output = outputHandle;
1829 break;
1830 }
1831 }
1832 if (output == AUDIO_IO_HANDLE_NONE) {
1833 // No output open with the preferred profile. Open a new one.
1834 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1835 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1836 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1837 config.format = prefMixerConfigInfo->getConfigBase().format;
1838 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1839 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1840 &config, prefMixerConfigInfo->getFlags());
1841 if (preferredOutput == nullptr) {
1842 ALOGE("%s failed to open output with preferred mixer config", __func__);
1843 } else {
1844 output = preferredOutput->mIoHandle;
1845 }
1846 }
1847 } else {
1848 // at this stage we should ignore the DIRECT flag as no direct output could be
1849 // found earlier
1850 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001851 if (com::android::media::audioserver::
1852 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1853 // If the preferred mixer attributes is null, do not select the bit-perfect output
1854 // unless the bit-perfect output is the only output.
1855 // The bit-perfect output can exist while the passed in preferred mixer attributes
1856 // info is null when it is a high priority client. The high priority clients are
1857 // ringtone or alarm, which is not a bit-perfect use case.
1858 size_t i = 0;
1859 while (i < outputs.size() && outputs.size() > 1) {
1860 auto desc = mOutputs.valueFor(outputs[i]);
1861 // The output descriptor must not be null here.
1862 if (desc->isBitPerfect()) {
1863 outputs.removeItemsAt(i);
1864 } else {
1865 i += 1;
1866 }
1867 }
1868 }
jiabina84c3d32022-12-02 18:59:55 +00001869 output = selectOutput(
1870 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1871 }
Eric Laurente552edb2014-03-10 17:42:56 -07001872 }
François Gaffie11d30102018-11-02 16:09:09 +01001873 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001874 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001875 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001876
Eric Laurente552edb2014-03-10 17:42:56 -07001877 return output;
1878}
1879
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001880sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001881 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1882 mAvailableInputDevices);
1883 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1884}
1885
1886DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1887 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1888 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889}
1890
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001891const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001892 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001893 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1894 if (msdModule != 0) {
1895 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1896 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1897 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1898 const struct audio_port_config *source = &patch->mPatch.sources[j];
1899 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1900 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001901 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001902 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 }
1904 }
1905 }
1906 return msdPatches;
1907}
1908
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001909bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1910 ssize_t index = mAudioPatches.indexOfKey(handle);
1911 if (index < 0) {
1912 return false;
1913 }
1914 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1915 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1916 if (msdModule == nullptr) {
1917 return false;
1918 }
1919 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1920 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1921 return true;
1922 }
1923 index = getMsdOutputPatches().indexOfKey(handle);
1924 if (index < 0) {
1925 return false;
1926 }
1927 return true;
1928}
1929
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001930status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1931 const InputProfileCollection &inputProfiles,
1932 const OutputProfileCollection &outputProfiles,
1933 const sp<DeviceDescriptor> &sourceDevice,
1934 const sp<DeviceDescriptor> &sinkDevice,
1935 AudioProfileVector& sourceProfiles,
1936 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001937 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001938 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001939 return NO_INIT;
1940 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001941 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001942 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 return NO_INIT;
1944 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001945 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001946 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1947 inProfile->supportsDevice(sourceDevice)) {
1948 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001949 }
1950 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001952 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001953 outProfile->supportsDevice(sinkDevice)) {
1954 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001955 }
1956 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001957 return NO_ERROR;
1958}
1959
1960status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1961 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1962 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1963{
Dean Wheatley16809da2022-12-09 14:55:46 +11001964 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1965 static const std::vector<audio_format_t> formatsOrder = {{
1966 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001967 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1968 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001969 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1970 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1971 // preferred).
1972 std::vector<audio_channel_mask_t> masks = {{
1973 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1974 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1975 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1976 // insert index masks (higher counts most preferred) as preferred over position masks
1977 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1978 masks.insert(
1979 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1980 }
1981 return masks;
1982 }();
1983
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001984 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001985 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1986 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001987 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001988 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1989 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001990 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001991 }
1992 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1993 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1994 sinkConfig->format = bestSinkConfig.format;
1995 // For encoded streams force direct flag to prevent downstream mixing.
1996 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1997 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001998 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1999 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002000 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002001 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
2002 // raw and IEC61937 framed streams.
2003 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2004 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
2005 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002006 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2007 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11002008 sourceConfig->channel_mask =
2009 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2010 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2011 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002012 sourceConfig->format = bestSinkConfig.format;
2013 // Copy input stream directly without any processing (e.g. resampling).
2014 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2015 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2016 if (hwAvSync) {
2017 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2018 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2019 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2020 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2021 }
2022 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2023 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2024 sinkConfig->config_mask |= config_mask;
2025 sourceConfig->config_mask |= config_mask;
2026 return NO_ERROR;
2027}
2028
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002029PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2030 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002031{
2032 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002033 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2034 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2035 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2036 if (deviceModule == nullptr) {
2037 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2038 return patchBuilder;
2039 }
2040 const InputProfileCollection inputProfiles = msdIsSource ?
2041 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2042 const OutputProfileCollection outputProfiles = msdIsSource ?
2043 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2044
2045 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2046 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2047 device : getMsdAudioOutDevices().itemAt(0);
2048 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2049
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002050 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2051 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002052 AudioProfileVector sourceProfiles;
2053 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002054 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2055 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002056 for (auto hwAvSync : { true, false }) {
2057 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2058 sourceProfiles, sinkProfiles) != NO_ERROR) {
2059 continue;
2060 }
2061 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2062 &sinkConfig) == NO_ERROR) {
2063 // Found a matching config. Re-create PatchBuilder with this config.
2064 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2065 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002066 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002067 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002068 " supporting PCM format conversion.", __func__);
2069 return patchBuilder;
2070}
2071
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002072status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002073 DeviceVector devices;
2074 if (outputDevices != nullptr && outputDevices->size() > 0) {
2075 devices.add(*outputDevices);
2076 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002077 // Use media strategy for unspecified output device. This should only
2078 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2079 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002080 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002081 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002082 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002083 }
Michael Chan6fb34492020-12-08 15:44:49 +11002084 std::vector<PatchBuilder> patchesToCreate;
2085 for (auto i = 0u; i < devices.size(); ++i) {
2086 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002087 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002088 }
2089 // Retain only the MSD patches associated with outputDevices request.
2090 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002091 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002092 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2093 auto retainedPatch = false;
2094 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2095 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2096 patchesToRemove.removeItemsAt(i);
2097 retainedPatch = true;
2098 break;
2099 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002100 }
Michael Chan6fb34492020-12-08 15:44:49 +11002101 if (retainedPatch) {
2102 it = patchesToCreate.erase(it);
2103 continue;
2104 }
2105 ++it;
2106 }
2107 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2108 return NO_ERROR;
2109 }
2110 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2111 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002112 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002113 }
Michael Chan6fb34492020-12-08 15:44:49 +11002114 status_t status = NO_ERROR;
2115 for (const auto &p : patchesToCreate) {
2116 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2117 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2118 char message[256];
2119 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2120 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2121 currStatus == NO_ERROR ? "Success" : "Error",
2122 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2123 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2124 if (currStatus == NO_ERROR) {
2125 ALOGD("%s", message);
2126 } else {
2127 ALOGE("%s", message);
2128 if (status == NO_ERROR) {
2129 status = currStatus;
2130 }
2131 }
2132 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002133 return status;
2134}
2135
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002136void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2137 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002138 for (size_t i = 0; i < msdPatches.size(); i++) {
2139 const auto& patch = msdPatches[i];
2140 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2141 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2142 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2143 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2144 releaseAudioPatch(patch->getHandle(), mUidCached);
2145 break;
2146 }
2147 }
2148 }
2149}
2150
Dorin Drimus94d94412022-02-02 09:05:02 +01002151bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002152 DeviceVector devicesToCheck =
2153 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002154 AudioPatchCollection msdPatches = getMsdOutputPatches();
2155 for (size_t i = 0; i < msdPatches.size(); i++) {
2156 const auto& patch = msdPatches[i];
2157 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2158 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2159 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2160 const auto& foundDevice = devicesToCheck.getDevice(
2161 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2162 if (foundDevice != nullptr) {
2163 devicesToCheck.remove(foundDevice);
2164 if (devicesToCheck.isEmpty()) {
2165 return true;
2166 }
2167 }
2168 }
2169 }
2170 }
2171 return false;
2172}
2173
Eric Laurente0720872014-03-11 09:30:41 -07002174audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002175 audio_output_flags_t flags,
2176 audio_format_t format,
2177 audio_channel_mask_t channelMask,
2178 uint32_t samplingRate,
2179 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002180{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002181 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2182 "%s called with format %#x", __func__, format);
2183
jiabinebb6af42020-06-09 17:31:17 -07002184 // Return the output that haptic-generating attached to when 1) session id is specified,
2185 // 2) haptic-generating effect exists for given session id and 3) the output that
2186 // haptic-generating effect attached to is in given outputs.
2187 if (sessionId != AUDIO_SESSION_NONE) {
2188 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2189 sessionId, FX_IID_HAPTICGENERATOR);
2190 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2191 return hapticGeneratingOutput;
2192 }
2193 }
2194
Eric Laurent16c66dd2019-05-01 17:54:10 -07002195 // Flags disqualifying an output: the match must happen before calling selectOutput()
2196 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2197 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2198
2199 // Flags expressing a functional request: must be honored in priority over
2200 // other criteria
2201 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2202 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002203 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2204 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002205 // Flags expressing a performance request: have lower priority than serving
2206 // requested sampling rate or channel mask
2207 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2208 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2209 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2210
2211 const audio_output_flags_t functionalFlags =
2212 (audio_output_flags_t)(flags & kFunctionalFlags);
2213 const audio_output_flags_t performanceFlags =
2214 (audio_output_flags_t)(flags & kPerformanceFlags);
2215
2216 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2217
Eric Laurente552edb2014-03-10 17:42:56 -07002218 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002219 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002220 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002221 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002222 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002223 // with tiebreak preferring the minimum number of extra functional flags
2224 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002225 // 3: the output supporting the exact channel mask
2226 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002227 // 5: the output with the highest sampling rate if the requested sample rate is
2228 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002229 // 6: the output with the highest number of requested performance flags
2230 // 7: the output with the bit depth the closest to the requested one
2231 // 8: the primary output
2232 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002233
Eric Laurent16c66dd2019-05-01 17:54:10 -07002234 // matching criteria values in priority order for best matching output so far
2235 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002236
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002237 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002238 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2239 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2240 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002241
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002242 for (audio_io_handle_t output : outputs) {
2243 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002244 // matching criteria values in priority order for current output
2245 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002246
Eric Laurent16c66dd2019-05-01 17:54:10 -07002247 if (outputDesc->isDuplicated()) {
2248 continue;
2249 }
2250 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2251 continue;
2252 }
Eric Laurent8838a382014-09-08 16:44:28 -07002253
Eric Laurent16c66dd2019-05-01 17:54:10 -07002254 // If haptic channel is specified, use the haptic output if present.
2255 // When using haptic output, same audio format and sample rate are required.
2256 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002257 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002258 // skip if haptic channel specified but output does not support it, or output support haptic
2259 // but there is no haptic channel requested AND no orphan haptic effect exist
2260 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2261 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002262 continue;
2263 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002264 // In the case of audio-coupled-haptic playback, there is no format conversion and
2265 // resampling in the framework, same format/channel/sampleRate for client and the output
2266 // thread is required. In the case of HapticGenerator effect, do not require format
2267 // matching.
2268 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2269 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002270 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002271 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002272 }
2273
2274 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002275 const int matchingFunctionalFlags =
2276 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2277 const int totalFunctionalFlags =
2278 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2279 // Prefer matching functional flags, but subtract unnecessary functional flags.
2280 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002281
2282 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002283 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2284 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002285 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2286 channelCount <= outputChannelCount) {
2287 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002288 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2289 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002290 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002291 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002292 currentMatchCriteria[3] = outputChannelCount;
2293 }
2294
2295 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002296 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002297 int diff; // avoid unsigned integer overflow.
2298 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2299
2300 // prefer the closest output sampling rate greater than or equal to target
2301 // if none exists, prefer the closest output sampling rate less than target.
2302 //
2303 // criteria is offset to make non-negative.
2304 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002305 }
2306
2307 // performance flags match
2308 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2309
2310 // format match
2311 if (format != AUDIO_FORMAT_INVALID) {
2312 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002313 PolicyAudioPort::kFormatDistanceMax -
2314 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002315 }
2316
2317 // primary output match
2318 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2319
2320 // compare match criteria by priority then value
2321 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2322 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2323 bestMatchCriteria = currentMatchCriteria;
2324 bestOutput = output;
2325
2326 std::stringstream result;
2327 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2328 std::ostream_iterator<int>(result, " "));
2329 ALOGV("%s new bestOutput %d criteria %s",
2330 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002331 }
2332 }
2333
Eric Laurent16c66dd2019-05-01 17:54:10 -07002334 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002335}
2336
Eric Laurent8fc147b2018-07-22 19:13:55 -07002337status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002338{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002339 ALOGV("%s portId %d", __FUNCTION__, portId);
2340
2341 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2342 if (outputDesc == 0) {
2343 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002344 return BAD_VALUE;
2345 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002346 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002347
Eric Laurent8fc147b2018-07-22 19:13:55 -07002348 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002349 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002350
jiabin220eea12024-05-17 17:55:20 +00002351 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2352 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2353 && outputDesc->isBitPerfect()) {
2354 // Usually, APM selects bit-perfect output for high priority use cases only when
2355 // bit-perfect output is the only output that can be routed to the selected device.
2356 // However, here is no need to play high priority use cases such as ringtone and alarm
2357 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2358 // can attach to new output.
2359 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2360 __func__, client->stream());
2361 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2362 return DEAD_OBJECT;
2363 }
2364
Eric Laurent733ce942017-12-07 12:18:25 -08002365 status_t status = outputDesc->start();
2366 if (status != NO_ERROR) {
2367 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002368 }
2369
Eric Laurent97ac8712018-07-27 18:59:02 -07002370 uint32_t delayMs;
2371 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002372
2373 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002374 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002375 if (status == DEAD_OBJECT) {
2376 sp<SwAudioOutputDescriptor> desc =
2377 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2378 if (desc == nullptr) {
2379 // This is not common, it may indicate something wrong with the HAL.
2380 ALOGE("%s unable to open output with default config", __func__);
2381 return status;
2382 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002383 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002384 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002385 }
jiabina84c3d32022-12-02 18:59:55 +00002386
2387 // If the client is the first one active on preferred mixer parameters, reopen the output
2388 // if the current mixer parameters doesn't match the preferred one.
2389 if (outputDesc->devices().size() == 1) {
2390 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2391 outputDesc->devices()[0]->getId(), client->strategy());
2392 if (info != nullptr && info->getUid() == client->uid()) {
2393 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2394 info->getConfigBase(), info->getFlags())) {
2395 stopSource(outputDesc, client);
2396 outputDesc->stop();
2397 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2398 config.channel_mask = info->getConfigBase().channel_mask;
2399 config.sample_rate = info->getConfigBase().sample_rate;
2400 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002401 sp<SwAudioOutputDescriptor> desc =
2402 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2403 if (desc == nullptr) {
2404 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002405 }
jiabin220eea12024-05-17 17:55:20 +00002406 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002407 // Intentionally return error to let the client side resending request for
2408 // creating and starting.
2409 return DEAD_OBJECT;
2410 }
2411 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002412 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002413 // If it is first bit-perfect client, reroute all clients that will be routed to
2414 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2415 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002416 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002417 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002418 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2419 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002420 continue;
2421 }
jiabine6b87492024-09-18 23:36:14 +00002422 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2423 outputsToResetDevice.push_back(mOutputs[i]);
2424 }
jiabine3d1f552023-06-14 17:42:17 +00002425 for (const auto& c : mOutputs[i]->getClientIterable()) {
2426 clientsToInvalidate.push_back(c->portId());
2427 }
2428 }
2429 if (!clientsToInvalidate.empty()) {
2430 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2431 __func__);
2432 mpClientInterface->invalidateTracks(clientsToInvalidate);
2433 }
jiabine6b87492024-09-18 23:36:14 +00002434 for (const auto& output : outputsToResetDevice) {
2435 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2436 }
jiabine3d1f552023-06-14 17:42:17 +00002437 }
jiabina84c3d32022-12-02 18:59:55 +00002438 }
2439 }
2440
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002441 if (client->hasPreferredDevice()) {
2442 // playback activity with preferred device impacts routing occurred, inform upper layers
2443 mpClientInterface->onRoutingUpdated();
2444 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002445 if (delayMs != 0) {
2446 usleep(delayMs * 1000);
2447 }
2448
jiabin220eea12024-05-17 17:55:20 +00002449 if (status == NO_ERROR &&
2450 outputDesc->mPreferredAttrInfo != nullptr &&
2451 outputDesc->isBitPerfect() &&
2452 com::android::media::audioserver::
2453 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2454 // A new client is started on bit-perfect output, update all clients internal mute.
2455 updateClientsInternalMute(outputDesc);
2456 }
2457
Eric Laurentc75307b2015-03-17 15:29:32 -07002458 return status;
2459}
2460
Eric Laurent96d1dda2022-03-14 17:14:19 +01002461bool AudioPolicyManager::isLeUnicastActive() const {
2462 if (isInCall()) {
2463 return true;
2464 }
2465 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2466}
2467
2468bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2469 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2470 return false;
2471 }
2472 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2473 ALOGV("%s active %d", __func__, active);
2474 return active;
2475}
2476
Eric Laurent97ac8712018-07-27 18:59:02 -07002477status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2478 const sp<TrackClientDescriptor>& client,
2479 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002480{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002481 // cannot start playback of STREAM_TTS if any other output is being used
2482 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002483
2484 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002485 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002486 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002487 auto clientStrategy = client->strategy();
2488 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002489 if (stream == AUDIO_STREAM_TTS) {
2490 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002491 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002492 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002493 return INVALID_OPERATION;
2494 } else {
2495 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2496 }
2497 } else {
2498 // some playback other than beacon starts
2499 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2500 }
2501
Eric Laurent77305a62016-07-25 16:39:22 -07002502 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002503 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002504 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002505
François Gaffie11d30102018-11-02 16:09:09 +01002506 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002507 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002508 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002509 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002510 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002511 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002512 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002513 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002514 } else {
2515 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002516 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002517 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2518 AUDIO_FORMAT_DEFAULT);
2519 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2520 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002521 }
2522
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002523 // requiresMuteCheck is false when we can bypass mute strategy.
2524 // It covers a common case when there is no materially active audio
2525 // and muting would result in unnecessary delay and dropped audio.
2526 const uint32_t outputLatencyMs = outputDesc->latency();
2527 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002528 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002529
Eric Laurente552edb2014-03-10 17:42:56 -07002530 // increment usage count for this stream on the requested output:
2531 // NOTE that the usage count is the same for duplicated output and hardware output which is
2532 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002533 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002534
2535 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002536 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002537 // Preferred device may be exclusive, use only if no other active clients on this output
2538 devices = DeviceVector(
2539 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2540 } else {
2541 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2542 }
François Gaffie11d30102018-11-02 16:09:09 +01002543 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002544 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002545 }
2546 }
Eric Laurente552edb2014-03-10 17:42:56 -07002547
François Gaffiec005e562018-11-06 15:04:49 +01002548 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002549 selectOutputForMusicEffects();
2550 }
2551
François Gaffie1c878552018-11-22 16:53:21 +01002552 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002553 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002554 if (devices.isEmpty()) {
2555 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002556 }
François Gaffiec005e562018-11-06 15:04:49 +01002557 bool shouldWait =
2558 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2559 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2560 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002561 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002562 const bool needToCloseBitPerfectOutput =
2563 (com::android::media::audioserver::
2564 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2565 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2566 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002567 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002568 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002569 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002570 // An output has a shared device if
2571 // - managed by the same hw module
2572 // - supports the currently selected device
2573 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002574 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002575
Eric Laurent77305a62016-07-25 16:39:22 -07002576 // force a device change if any other output is:
2577 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002578 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002579 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002580 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002581 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002582 // change the device currently selected by the other output.
2583 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002584 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002585 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002586 force = true;
2587 }
2588 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002589 // a notification so that audio focus effect can propagate, or that a mute/unmute
2590 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002591 const uint32_t latencyMs = desc->latency();
2592 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2593
2594 if (shouldWait && isActive && (waitMs < latencyMs)) {
2595 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002596 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002597
2598 // Require mute check if another output is on a shared device
2599 // and currently active to have proper drain and avoid pops.
2600 // Note restoring AudioTracks onto this output needs to invoke
2601 // a volume ramp if there is no mute.
2602 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002603
2604 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2605 outputsToReopen.push_back(desc);
2606 }
Eric Laurente552edb2014-03-10 17:42:56 -07002607 }
2608 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002609
jiabin220eea12024-05-17 17:55:20 +00002610 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002611 // If the output is open with preferred mixer attributes, but the routed device is
2612 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2613 // changed.
2614 return DEAD_OBJECT;
2615 }
jiabin220eea12024-05-17 17:55:20 +00002616 for (auto& outputToReopen : outputsToReopen) {
2617 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2618 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002619 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302620 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2621 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002622
Eric Laurente552edb2014-03-10 17:42:56 -07002623 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002624 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002625 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002626 curves.getVolumeIndex(outputDesc->devices().types()),
Vlad Popa1e865e62024-08-15 19:11:42 -07002627 outputDesc, outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002628 outputDesc->useHwGain() /*force*/)) {
2629 // request AudioService to reinitialize the volume curves asynchronously
2630 ALOGE("checkAndSetVolume failed, requesting volume range init");
2631 mpClientInterface->onVolumeRangeInitRequest();
2632 };
Eric Laurente552edb2014-03-10 17:42:56 -07002633
2634 // update the outputs if starting an output with a stream that can affect notification
2635 // routing
2636 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002637
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002638 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002639 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002640 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002641 }
Eric Laurentdc462862016-07-19 12:29:53 -07002642
2643 if (waitMs > muteWaitMs) {
2644 *delayMs = waitMs - muteWaitMs;
2645 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002646
2647 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2648 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2649 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2650 // change occurs after the MixerThread starts and causes a stream volume
2651 // glitch.
2652 //
2653 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002654 }
Eric Laurentdc462862016-07-19 12:29:53 -07002655
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002656 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002657 mEngine->getForceUse(
2658 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002659 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002660 }
2661
Eric Laurent97ac8712018-07-27 18:59:02 -07002662 // Automatically enable the remote submix input when output is started on a re routing mix
2663 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002664 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2665 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002666 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2667 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2668 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002669 "remote-submix",
2670 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002671 }
2672
Eric Laurent96d1dda2022-03-14 17:14:19 +01002673 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2674
Eric Laurente552edb2014-03-10 17:42:56 -07002675 return NO_ERROR;
2676}
2677
Eric Laurent96d1dda2022-03-14 17:14:19 +01002678void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2679 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2680 bool isUnicastActive = isLeUnicastActive();
2681
2682 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002683 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002684 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2685 for (size_t i = 0; i < mOutputs.size(); i++) {
2686 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2687 if (desc != ignoredOutput && desc->isActive()
2688 && ((isUnicastActive &&
2689 !desc->devices().
2690 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2691 || (wasUnicastActive &&
2692 !desc->devices().getDevicesFromTypes(
2693 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2694 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2695 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002696 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002697 // If the device is using preferred mixer attributes, the output need to reopen
2698 // with default configuration when the new selected devices are different from
2699 // current routing devices.
2700 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2701 continue;
2702 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302703 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002704 // re-apply device specific volume if not done by setOutputDevice()
2705 if (!force) {
2706 applyStreamVolumes(desc, newDevices.types(), delayMs);
2707 }
2708 }
2709 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002710 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002711 }
2712}
2713
Eric Laurent8fc147b2018-07-22 19:13:55 -07002714status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002715{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002716 ALOGV("%s portId %d", __FUNCTION__, portId);
2717
2718 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2719 if (outputDesc == 0) {
2720 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002721 return BAD_VALUE;
2722 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002723 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002724
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002725 if (client->hasPreferredDevice(true)) {
2726 // playback activity with preferred device impacts routing occurred, inform upper layers
2727 mpClientInterface->onRoutingUpdated();
2728 }
2729
Eric Laurent97ac8712018-07-27 18:59:02 -07002730 ALOGV("stopOutput() output %d, stream %d, session %d",
2731 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002732
Eric Laurent97ac8712018-07-27 18:59:02 -07002733 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002734
Eric Laurent733ce942017-12-07 12:18:25 -08002735 if (status == NO_ERROR ) {
2736 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002737 } else {
2738 return status;
2739 }
2740
2741 if (outputDesc->devices().size() == 1) {
2742 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2743 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002744 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002745 if (info != nullptr && info->getUid() == client->uid()) {
2746 info->decreaseActiveClient();
2747 if (info->getActiveClientCount() == 0) {
2748 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002749 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002750 }
2751 }
jiabin220eea12024-05-17 17:55:20 +00002752 if (com::android::media::audioserver::
2753 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2754 !outputReopened && outputDesc->isBitPerfect()) {
2755 // Only need to update the clients' internal mute when the output is bit-perfect and it
2756 // is not reopened.
2757 updateClientsInternalMute(outputDesc);
2758 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002759 }
2760 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002761}
2762
Eric Laurent97ac8712018-07-27 18:59:02 -07002763status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2764 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002765{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002766 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002767 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002768 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002769 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002770
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002771 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2772
François Gaffie1c878552018-11-22 16:53:21 +01002773 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2774 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002775 // Automatically disable the remote submix input when output is stopped on a
2776 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002777 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002778 if (isSingleDeviceType(
2779 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002780 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002781 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002782 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2783 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002784 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002785 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002786 }
2787 }
2788 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002789 if (client->hasPreferredDevice(true) &&
2790 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002791 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002792 forceDeviceUpdate = true;
2793 }
2794
Eric Laurente552edb2014-03-10 17:42:56 -07002795 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002796 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002797
Eric Laurente552edb2014-03-10 17:42:56 -07002798 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002799 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002800 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002801 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002802
2803 // If the routing does not change, if an output is routed on a device using HwGain
2804 // (aka setAudioPortConfig) and there are still active clients following different
2805 // volume group(s), force reapply volume
2806 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2807 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2808
Eric Laurente552edb2014-03-10 17:42:56 -07002809 // delay the device switch by twice the latency because stopOutput() is executed when
2810 // the track stop() command is received and at that time the audio track buffer can
2811 // still contain data that needs to be drained. The latency only covers the audio HAL
2812 // and kernel buffers. Also the latency does not always include additional delay in the
2813 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302814 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002815 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002816
2817 // force restoring the device selection on other active outputs if it differs from the
2818 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002819 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002820 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002821 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002822 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002823 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002824 desc->isActive() &&
2825 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002826 (newDevices != desc->devices())) {
2827 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2828 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002829
jiabin220eea12024-05-17 17:55:20 +00002830 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002831 // If the device is using preferred mixer attributes, the output need to
2832 // reopen with default configuration when the new selected devices are
2833 // different from current routing devices.
2834 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2835 continue;
2836 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302837 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002838
Eric Laurent57de36c2016-09-28 16:59:11 -07002839 // re-apply device specific volume if not done by setOutputDevice()
2840 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002841 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002842 }
Eric Laurente552edb2014-03-10 17:42:56 -07002843 }
2844 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002845 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002846 // update the outputs if stopping one with a stream that can affect notification routing
2847 handleNotificationRoutingForStream(stream);
2848 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002849
2850 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2851 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002852 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002853 }
2854
François Gaffiec005e562018-11-06 15:04:49 +01002855 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002856 selectOutputForMusicEffects();
2857 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002858
2859 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2860
Eric Laurente552edb2014-03-10 17:42:56 -07002861 return NO_ERROR;
2862 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002863 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002864 return INVALID_OPERATION;
2865 }
2866}
2867
jiabinbce0c1d2020-10-05 11:20:18 -07002868bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002869{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002870 ALOGV("%s portId %d", __FUNCTION__, portId);
2871
2872 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2873 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002874 // If an output descriptor is closed due to a device routing change,
2875 // then there are race conditions with releaseOutput from tracks
2876 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2877 // destroyed shortly thereafter.
2878 //
2879 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002880 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002881 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002882 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002883
2884 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002885
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302886 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2887 if (outputDesc->isClientActive(client)) {
2888 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2889 stopOutput(portId);
2890 }
2891
Eric Laurent8fc147b2018-07-22 19:13:55 -07002892 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2893 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002894 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002895 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002896 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002897 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002898 if (--outputDesc->mDirectOpenCount == 0) {
2899 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002900 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002901 }
2902 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302903
Andy Hung39efb7a2018-09-26 15:39:28 -07002904 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002905 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2906 // The output is pending reopened to query dynamic profiles and
2907 // there is no active clients
2908 closeOutput(outputDesc->mIoHandle);
2909 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2910 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2911 if (newOutputDesc == nullptr) {
2912 ALOGE("%s failed to open output", __func__);
2913 }
2914 return true;
2915 }
2916 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002917}
2918
Eric Laurentcaf7f482014-11-25 17:50:47 -08002919status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2920 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002921 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002922 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002923 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002924 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002925 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002926 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002927 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002928 audio_port_handle_t *portId,
2929 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002930{
François Gaffiec005e562018-11-06 15:04:49 +01002931 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002932 "flags %#x attributes=%s requested device ID %d",
2933 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2934 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002935
Eric Laurentad2e7b92017-09-14 20:06:42 -07002936 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002937 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002938 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002939 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002940 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002941 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002942 sp<RecordClientDescriptor> clientDesc;
2943 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002944 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002945 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002946
2947 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2948 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2949 return INVALID_OPERATION;
2950 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002951
Francois Gaffie716e1432019-01-14 16:58:59 +01002952 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2953 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002954 }
2955
Paul McLean466dc8e2015-04-17 13:15:36 -06002956 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002957 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002958 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002959
Eric Laurentad2e7b92017-09-14 20:06:42 -07002960 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2961 // possible
2962 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2963 *input != AUDIO_IO_HANDLE_NONE) {
2964 ssize_t index = mInputs.indexOfKey(*input);
2965 if (index < 0) {
2966 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2967 status = BAD_VALUE;
2968 goto error;
2969 }
2970 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002971 RecordClientVector clients = inputDesc->getClientsForSession(session);
2972 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002973 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2974 status = BAD_VALUE;
2975 goto error;
2976 }
2977 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2978 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002979 // corresponds to a new client and is only permitted from the same UID.
2980 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002981 if (clients.size() > 1) {
2982 for (const auto& client : clients) {
2983 // The client map is ordered by key values (portId) and portIds are allocated
2984 // incrementaly. So the first client in this list is the one opened by audio flinger
2985 // when the mmap stream is created and should be ignored as it does not correspond
2986 // to an actual client
2987 if (client == *clients.cbegin()) {
2988 continue;
2989 }
2990 if (uid != client->uid() && !client->isSilenced()) {
2991 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2992 uid, client->portId(), client->uid());
2993 status = INVALID_OPERATION;
2994 goto error;
2995 }
Eric Laurent331679c2018-04-16 17:03:16 -07002996 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002997 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002998 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002999 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07003000
Eric Laurentfecbceb2021-02-09 14:46:43 +01003001 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003002 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003003 }
3004
3005 *input = AUDIO_IO_HANDLE_NONE;
3006 *inputType = API_INPUT_INVALID;
3007
Francois Gaffie716e1432019-01-14 16:58:59 +01003008 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02003009 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003010 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003011 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003012 ALOGW("%s could not find input mix for attr %s",
3013 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07003014 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01003015 }
jiabinc1de2df2019-05-07 14:26:40 -07003016 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3017 String8(attr->tags + strlen("addr=")),
3018 AUDIO_FORMAT_DEFAULT);
3019 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003020 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07003021 __func__, attributes.source, attributes.tags);
3022 status = BAD_VALUE;
3023 goto error;
3024 }
3025
Kevin Rocard25f9b052019-02-27 15:08:54 -08003026 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
3027 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
3028 } else {
3029 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
3030 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01003031 if (virtualDeviceId) {
3032 *virtualDeviceId = policyMix->mVirtualDeviceId;
3033 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003034 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003035 if (explicitRoutingDevice != nullptr) {
3036 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07003037 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01003038 // Prevent from storing invalid requested device id in clients
3039 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003040 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08003041 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3042 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07003043 }
François Gaffie11d30102018-11-02 16:09:09 +01003044 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003045 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003046 status = BAD_VALUE;
3047 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003048 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003049 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3050 *inputType = API_INPUT_MIX_CAPTURE;
3051 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003052 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3053 // there is an external policy, but this input is attached to a mix of recorders,
3054 // meaning it receives audio injected into the framework, so the recorder doesn't
3055 // know about it and is therefore considered "legacy"
3056 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003057
3058 if (virtualDeviceId) {
3059 *virtualDeviceId = policyMix->mVirtualDeviceId;
3060 }
François Gaffie11d30102018-11-02 16:09:09 +01003061 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003062 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003063 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003064 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003065 } else {
3066 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003067 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003068
Eric Laurent599c7582015-12-07 18:05:55 -08003069 }
3070
François Gaffiec005e562018-11-06 15:04:49 +01003071 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003072 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003073 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003074 AudioProfileVector profiles;
3075 status_t ret = getProfilesForDevices(
3076 DeviceVector(device), profiles, flags, true /*isInput*/);
3077 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003078 const auto channels = profiles[0]->getChannels();
3079 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3080 config->channel_mask = *channels.begin();
3081 }
3082 const auto sampleRates = profiles[0]->getSampleRates();
3083 if (!sampleRates.empty() &&
3084 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3085 config->sample_rate = *sampleRates.begin();
3086 }
jiabinf1c73972022-04-14 16:28:52 -07003087 config->format = profiles[0]->getFormat();
3088 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003089 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003090 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003091
Marvin Ramine5a122d2023-12-07 13:57:59 +01003092
3093 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3094 *virtualDeviceId = policyMix->mVirtualDeviceId;
3095 }
3096
Eric Laurent8f42ea12018-08-08 09:08:25 -07003097exit:
3098
François Gaffiec005e562018-11-06 15:04:49 +01003099 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3100 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003101
Francois Gaffie716e1432019-01-14 16:58:59 +01003102 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003103 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003104 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105
Mikhail Naganov2996f672019-04-18 12:29:59 -07003106 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003107 requestedDeviceId, attributes.source, flags,
3108 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003109 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003110 // Move (if found) effect for the client session to its input
3111 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003112 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003113
3114 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3115 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003116
Eric Laurent599c7582015-12-07 18:05:55 -08003117 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003118
3119error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003120 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003121}
3122
3123
François Gaffie11d30102018-11-02 16:09:09 +01003124audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003125 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003126 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003127 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003128 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003129 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003130{
3131 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003132 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003133 bool isSoundTrigger = false;
3134
François Gaffiec005e562018-11-06 15:04:49 +01003135 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003136 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3137 if (index >= 0) {
3138 input = mSoundTriggerSessions.valueFor(session);
3139 isSoundTrigger = true;
3140 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3141 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3142 } else {
3143 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003144 }
François Gaffiec005e562018-11-06 15:04:49 +01003145 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003146 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003147 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003148 }
3149
Carter Hsua3abb402021-10-26 11:11:20 +08003150 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3151 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3152 }
3153
Eric Laurentfe231122017-11-17 17:48:06 -08003154 // sampling rate and flags may be updated by getInputProfile
3155 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3156 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003157 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003158 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003159 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003160 // find a compatible input profile (not necessarily identical in parameters)
3161 sp<IOProfile> profile = getInputProfile(
3162 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3163 if (profile == nullptr) {
3164 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003165 }
jiabin2fd710d2022-05-02 23:20:22 +00003166
Glenn Kasten05ddca52016-02-11 08:17:12 -08003167 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003168 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003169 if (samplingRate == 0) {
3170 samplingRate = profileSamplingRate;
3171 }
Eric Laurente552edb2014-03-10 17:42:56 -07003172
Eric Laurent322b4d22015-04-03 15:57:54 -07003173 if (profile->getModuleHandle() == 0) {
3174 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003175 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003176 }
3177
Eric Laurentec376dc2021-04-08 20:41:22 +02003178 // Reuse an already opened input if a client with the same session ID already exists
3179 // on that input
3180 for (size_t i = 0; i < mInputs.size(); i++) {
3181 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3182 if (desc->mProfile != profile) {
3183 continue;
3184 }
3185 RecordClientVector clients = desc->clientsList();
3186 for (const auto &client : clients) {
3187 if (session == client->session()) {
3188 return desc->mIoHandle;
3189 }
3190 }
3191 }
3192
Eric Laurentc71b11b2024-06-03 12:54:53 +00003193 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003194 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003195 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3196 // First pick best candidate for preemption (there may not be any):
3197 // - Preempt and input if:
3198 // - It has only strictly lower priority use cases than the new client
3199 // - It has equal priority use cases than the new client, was not
3200 // opened thanks to preemption or has been active since opened.
3201 // - Order the preemption candidates by inactive first and priority second
3202 sp<AudioInputDescriptor> closeCandidate;
3203 int leastCloseRank = INT_MAX;
3204 static const int sCloseActive = 0x100;
3205
3206 for (size_t i = 0; i < mInputs.size(); i++) {
3207 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3208 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003209 continue;
3210 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003211 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3212 if (topPrioClient == nullptr) {
3213 continue;
3214 }
3215 int topPrio = source_priority(topPrioClient->source());
3216 if (topPrio < source_priority(attributes.source)
3217 || (topPrio == source_priority(attributes.source)
3218 && !desc->isPreemptor())) {
3219 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3220 if (closeRank < leastCloseRank) {
3221 leastCloseRank = closeRank;
3222 closeCandidate = desc;
3223 }
3224 }
3225 }
3226
3227 if (closeCandidate != nullptr) {
3228 closeInput(closeCandidate->mIoHandle);
3229 // Mark the new input as being issued from a preemption
3230 // so that is will not be preempted later
3231 isPreemptor = true;
3232 } else {
3233 // Then pick the best reusable input (There is always one)
3234 // The order of preference is:
3235 // 1) active inputs with same use case as the new client
3236 // 2) inactive inputs with same use case
3237 // 3) active inputs with different use cases
3238 // 4) inactive inputs with different use cases
3239 sp<AudioInputDescriptor> reuseCandidate;
3240 int leastReuseRank = INT_MAX;
3241 static const int sReuseDifferentUseCase = 0x100;
3242
3243 for (size_t i = 0; i < mInputs.size(); i++) {
3244 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3245 if (desc->mProfile != profile) {
3246 continue;
3247 }
3248 int reuseRank = sReuseDifferentUseCase;
3249 for (const auto& client: desc->getClientIterable()) {
3250 if (client->source() == attributes.source) {
3251 reuseRank = 0;
3252 break;
3253 }
3254 }
3255 reuseRank += desc->isActive() ? 0 : 1;
3256 if (reuseRank < leastReuseRank) {
3257 leastReuseRank = reuseRank;
3258 reuseCandidate = desc;
3259 }
3260 }
3261 return reuseCandidate->mIoHandle;
3262 }
3263 } else { // fix_input_sharing_logic()
3264 for (size_t i = 0; i < mInputs.size(); ) {
3265 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3266 if (desc->mProfile != profile) {
3267 i++;
3268 continue;
3269 }
3270 // if sound trigger, reuse input if used by other sound trigger on same session
3271 // else
3272 // reuse input if active client app is not in IDLE state
3273 //
3274 RecordClientVector clients = desc->clientsList();
3275 bool doClose = false;
3276 for (const auto& client : clients) {
3277 if (isSoundTrigger != client->isSoundTrigger()) {
3278 continue;
3279 }
3280 if (client->isSoundTrigger()) {
3281 if (session == client->session()) {
3282 return desc->mIoHandle;
3283 }
3284 continue;
3285 }
3286 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003287 return desc->mIoHandle;
3288 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003289 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003290 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003291 if (doClose) {
3292 closeInput(desc->mIoHandle);
3293 } else {
3294 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003295 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003296 }
3297 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003298 }
3299
Eric Laurentc71b11b2024-06-03 12:54:53 +00003300 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3301 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003302
Eric Laurentfe231122017-11-17 17:48:06 -08003303 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3304 lConfig.sample_rate = profileSamplingRate;
3305 lConfig.channel_mask = profileChannelMask;
3306 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003307
François Gaffie11d30102018-11-02 16:09:09 +01003308 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003309
3310 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003311 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003312 (profileSamplingRate != lConfig.sample_rate) ||
3313 !audio_formats_match(profileFormat, lConfig.format) ||
3314 (profileChannelMask != lConfig.channel_mask)) {
3315 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003316 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003317 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003318 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003319 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003320 }
Eric Laurent599c7582015-12-07 18:05:55 -08003321 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003322 }
3323
Eric Laurentc722f302014-12-10 11:21:49 -08003324 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003325
Eric Laurent599c7582015-12-07 18:05:55 -08003326 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003327 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003328
Eric Laurent599c7582015-12-07 18:05:55 -08003329 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003330}
3331
Eric Laurent4eb58f12018-12-07 16:41:02 -08003332status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003333{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003334 ALOGV("%s portId %d", __FUNCTION__, portId);
3335
3336 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3337 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003338 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003339 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003340 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003341 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003342 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003343 if (client->active()) {
3344 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3345 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003346 }
3347
Eric Laurent8f42ea12018-08-08 09:08:25 -07003348 audio_session_t session = client->session();
3349
Eric Laurent4eb58f12018-12-07 16:41:02 -08003350 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003351
Eric Laurent4eb58f12018-12-07 16:41:02 -08003352 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003353
Eric Laurent4eb58f12018-12-07 16:41:02 -08003354 status_t status = inputDesc->start();
3355 if (status != NO_ERROR) {
3356 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003357 }
Eric Laurente552edb2014-03-10 17:42:56 -07003358
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003359 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003360 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003361 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003362
Eric Laurent8f42ea12018-08-08 09:08:25 -07003363 // indicate active capture to sound trigger service if starting capture from a mic on
3364 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003365 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003366 if (device != nullptr) {
3367 status = setInputDevice(input, device, true /* force */);
3368 } else {
3369 ALOGW("%s no new input device can be found for descriptor %d",
3370 __FUNCTION__, inputDesc->getId());
3371 status = BAD_VALUE;
3372 }
Eric Laurente552edb2014-03-10 17:42:56 -07003373
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003374 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003375 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003376 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003377 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003378 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3379 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003380 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003381 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003382
François Gaffie11d30102018-11-02 16:09:09 +01003383 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3384 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003385 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003386 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003387 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003388
Eric Laurent8f42ea12018-08-08 09:08:25 -07003389 // automatically enable the remote submix output when input is started if not
3390 // used by a policy mix of type MIX_TYPE_RECORDERS
3391 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003392 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003393 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003394 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003395 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003396 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3397 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003398 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003399 if (address != "") {
3400 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3401 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003402 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003403 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003404 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003405 } else if (status != NO_ERROR) {
3406 // Restore client activity state.
3407 inputDesc->setClientActive(client, false);
3408 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003409 }
3410
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003411 ALOGV("%s input %d source = %d status = %d exit",
3412 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003413
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003414 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003415}
3416
Eric Laurent8fc147b2018-07-22 19:13:55 -07003417status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003418{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003419 ALOGV("%s portId %d", __FUNCTION__, portId);
3420
3421 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3422 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003423 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003424 return BAD_VALUE;
3425 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003426 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003427 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003428 if (!client->active()) {
3429 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003430 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003431 }
Carter Hsue6139d52021-07-08 10:30:20 +08003432 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003433 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003434
Eric Laurent8f42ea12018-08-08 09:08:25 -07003435 inputDesc->stop();
3436 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003437 auto current_source = inputDesc->source();
3438 setInputDevice(input, getNewInputDevice(inputDesc),
3439 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003440 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003441 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003442 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003443 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003444 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3445 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003446 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003447 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003448
3449 // automatically disable the remote submix output when input is stopped if not
3450 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003451 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003452 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003453 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003454 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003455 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3456 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003457 }
3458 if (address != "") {
3459 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3460 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003461 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003462 }
3463 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003464 resetInputDevice(input);
3465
3466 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3467 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003468 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3469 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003470 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003471 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003472 }
3473 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003474 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003475 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003476}
3477
Eric Laurent8fc147b2018-07-22 19:13:55 -07003478void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003479{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003480 ALOGV("%s portId %d", __FUNCTION__, portId);
3481
3482 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3483 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003484 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003485 return;
3486 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003487 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003488 audio_io_handle_t input = inputDesc->mIoHandle;
3489
Eric Laurent8f42ea12018-08-08 09:08:25 -07003490 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003491
Andy Hung39efb7a2018-09-26 15:39:28 -07003492 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003493
3494 // If no more clients are present in this session, park effects to an orphan chain
3495 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3496 if (clientsOnSession.size() == 0) {
3497 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3498 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003499 if (inputDesc->getClientCount() > 0) {
3500 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003501 return;
3502 }
3503
Eric Laurent05b90f82014-08-27 15:32:29 -07003504 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003505 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003506 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003507}
3508
Eric Laurent8f42ea12018-08-08 09:08:25 -07003509void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003510{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003511 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003512
3513 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003514 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003515 }
3516}
3517
Eric Laurent8f42ea12018-08-08 09:08:25 -07003518void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3519{
3520 stopInput(portId);
3521 releaseInput(portId);
3522}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003523
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003524bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3525 if (input->clientsList().size() == 0
3526 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3527 return true;
3528 }
3529 for (const auto& client : input->clientsList()) {
3530 sp<DeviceDescriptor> device =
3531 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3532 client->session());
3533 if (!input->supportedDevices().contains(device)) {
3534 return true;
3535 }
3536 }
3537 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3538 return false;
3539}
3540
Eric Laurent0dd51852019-04-19 18:18:58 -07003541void AudioPolicyManager::checkCloseInputs() {
3542 // After connecting or disconnecting an input device, close input if:
3543 // - it has no client (was just opened to check profile) OR
3544 // - none of its supported devices are connected anymore OR
3545 // - one of its clients cannot be routed to one of its supported
3546 // devices anymore. Otherwise update device selection
3547 std::vector<audio_io_handle_t> inputsToClose;
3548 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003549 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003550 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003551 }
3552 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003553 for (const audio_io_handle_t handle : inputsToClose) {
3554 ALOGV("%s closing input %d", __func__, handle);
3555 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003556 }
Eric Laurentd4692962014-05-05 18:13:44 -07003557}
3558
Vlad Popa87e0e582024-05-20 18:49:20 -07003559status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3560 const char *address __unused,
3561 bool enabled,
3562 audio_stream_type_t streamToDriveAbs)
3563{
Vlad Popa08502d82024-10-22 20:17:47 -07003564 ALOGI("%s: deviceType 0x%X, enabled %d, streamToDriveAbs %d", __func__, deviceType, enabled,
3565 streamToDriveAbs);
3566
Vlad Popa87e0e582024-05-20 18:49:20 -07003567 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
Vlad Popafb0af7c2024-10-29 16:38:37 -07003568 if (enabled) {
3569 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3570 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3571 toString(streamToDriveAbs).c_str());
3572 return BAD_VALUE;
3573 }
3574
3575 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3576 } else {
3577 mAbsoluteVolumeDrivingStreams.erase(deviceType);
Vlad Popa87e0e582024-05-20 18:49:20 -07003578 }
3579
Vlad Popafb0af7c2024-10-29 16:38:37 -07003580 // apply the stream volumes regarding the new absolute mode to all the outputs
3581 for (size_t i = 0; i < mOutputs.size(); i++) {
3582 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3583 ALOGV("%s: apply stream volumes for portId %d", __func__, desc->getId());
3584 applyStreamVolumes(desc, {deviceType}, static_cast<int>(desc->latency()) * 2);
3585 }
3586
Vlad Popa87e0e582024-05-20 18:49:20 -07003587 return NO_ERROR;
3588}
3589
François Gaffie251c7f02018-11-07 10:41:08 +01003590void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003591{
3592 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003593 if (indexMin < 0 || indexMax < 0) {
3594 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3595 return;
3596 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003597 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003598
3599 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003600 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3601 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003602 continue;
3603 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003604 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003605 }
Eric Laurente552edb2014-03-10 17:42:56 -07003606}
3607
Eric Laurente0720872014-03-11 09:30:41 -07003608status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003609 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003610 bool muted,
François Gaffie53615e22015-03-19 09:24:12 +01003611 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003612{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003613 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003614 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3615 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3616 return NO_ERROR;
3617 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303618 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3619 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Vlad Popa1e865e62024-08-15 19:11:42 -07003620 return setVolumeIndexForAttributes(attributes, index, muted, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003621}
3622
Eric Laurente0720872014-03-11 09:30:41 -07003623status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003624 int *index,
3625 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003626{
François Gaffiec005e562018-11-06 15:04:49 +01003627 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3628 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003629 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003630 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003631 deviceTypes = mEngine->getOutputDevicesForStream(
3632 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003633 }
jiabin9a3361e2019-10-01 09:38:30 -07003634 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003635}
3636
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003637status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003638 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003639 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003640 audio_devices_t device)
3641{
3642 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003643 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3644 if (group == VOLUME_GROUP_NONE) {
3645 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003646 return BAD_VALUE;
3647 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003648 ALOGV("%s: group %d matching with %s index %d",
3649 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003650 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3651 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3652 __FUNCTION__, toString(attributes).c_str());
3653 return NO_ERROR;
3654 }
François Gaffiecfe17322018-11-07 13:41:29 +01003655 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003656 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003657 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003658 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3659 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3660 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3661 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003662 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3663
Vlad Popa1e865e62024-08-15 19:11:42 -07003664
3665 status = setVolumeCurveIndex(index, muted, device, curves);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003666 if (status != NO_ERROR) {
3667 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3668 return status;
3669 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003670
jiabin9a3361e2019-10-01 09:38:30 -07003671 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003672 auto curCurvAttrs = curves.getAttributes();
3673 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3674 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003675 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003676 } else if (!curves.getStreamTypes().empty()) {
3677 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003678 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003679 } else {
3680 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3681 return BAD_VALUE;
3682 }
jiabin9a3361e2019-10-01 09:38:30 -07003683 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3684 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003685
François Gaffiecfe17322018-11-07 13:41:29 +01003686 // update volume on all outputs and streams matching the following:
3687 // - The requested stream (or a stream matching for volume control) is active on the output
3688 // - The device (or devices) selected by the engine for this stream includes
3689 // the requested device
3690 // - For non default requested device, currently selected device on the output is either the
3691 // requested device or one of the devices selected by the engine for this stream
3692 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3693 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003694 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003695 for (size_t i = 0; i < mOutputs.size(); i++) {
3696 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003697 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003698
jiabin9a3361e2019-10-01 09:38:30 -07003699 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3700 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003701 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003702
3703 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003704 continue;
3705 }
3706 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3707 curDevices.find(device) == curDevices.end()) {
3708 continue;
3709 }
3710 bool applyVolume = false;
3711 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3712 curSrcDevices.insert(device);
3713 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003714 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3715 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003716 } else {
3717 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3718 }
3719 if (!applyVolume) {
3720 continue; // next output
3721 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003722 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3723 // If a higher priority strategy is active, and the output is routed to a device with a
3724 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003725 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003726 applyVolume = false;
Vlad Popa1e865e62024-08-15 19:11:42 -07003727 bool swMute = com_android_media_audio_ring_my_car() ? curves.isMuted() : (index == 0);
Francois Gaffie593634d2021-06-22 13:31:31 +02003728 // If the volume source is active with higher priority source, ensure at least Sw Muted
Vlad Popa1e865e62024-08-15 19:11:42 -07003729 desc->setSwMute(swMute, vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003730 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3731 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3732 false /*preferredDevice*/);
3733 if (activeClients.empty()) {
3734 continue;
3735 }
3736 bool isPreempted = false;
3737 bool isHigherPriority = productStrategy < strategy;
3738 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003739 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003740 ALOGV("%s: Strategy=%d (\nrequester:\n"
3741 " group %d, volumeGroup=%d attributes=%s)\n"
3742 " higher priority source active:\n"
3743 " volumeGroup=%d attributes=%s) \n"
3744 " on output %zu, bailing out", __func__, productStrategy,
3745 group, group, toString(attributes).c_str(),
3746 client->volumeSource(), toString(client->attributes()).c_str(), i);
3747 applyVolume = false;
3748 isPreempted = true;
3749 break;
3750 }
3751 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003752 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003753 applyVolume = true;
3754 }
3755 }
3756 if (isPreempted || applyVolume) {
3757 break;
3758 }
3759 }
3760 if (!applyVolume) {
3761 continue; // next output
3762 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003763 }
François Gaffieed91f582020-01-31 10:35:37 +01003764 //FIXME: workaround for truncated touch sounds
3765 // delayed volume change for system stream to be removed when the problem is
3766 // handled by system UI
Vlad Popa1e865e62024-08-15 19:11:42 -07003767 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003768 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003769 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3770 if (volStatus != NO_ERROR) {
3771 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003772 }
3773 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003774
3775 // update voice volume if the an active call route exists
3776 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3777 && (curSrcDevices.find(
3778 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3779 != curSrcDevices.end())) {
3780 bool isVoiceVolSrc;
3781 bool isBtScoVolSrc;
3782 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3783 isVoiceVolSrc, isBtScoVolSrc, __func__)
3784 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003785 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3786 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3787 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003788 }
3789 }
3790
François Gaffiecfe17322018-11-07 13:41:29 +01003791 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3792 return status;
3793}
3794
François Gaffieaaac0fd2018-11-22 17:56:39 +01003795status_t AudioPolicyManager::setVolumeCurveIndex(int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003796 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003797 audio_devices_t device,
3798 IVolumeCurves &volumeCurves)
3799{
3800 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3801 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003802 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3803 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003804 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303805 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3806 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003807 return BAD_VALUE;
3808 }
3809 if (!audio_is_output_device(device)) {
3810 return BAD_VALUE;
3811 }
3812
3813 // Force max volume if stream cannot be muted
3814 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3815
Vlad Popa1e865e62024-08-15 19:11:42 -07003816 ALOGV("%s device %08x, index %d, muted %d", __FUNCTION__ , device, index, muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003817 volumeCurves.addCurrentVolumeIndex(device, index);
Vlad Popa1e865e62024-08-15 19:11:42 -07003818 volumeCurves.setIsMuted(muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003819 return NO_ERROR;
3820}
3821
3822status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3823 int &index,
3824 audio_devices_t device)
3825{
3826 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3827 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003828 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003829 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003830 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003831 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003832 }
jiabin9a3361e2019-10-01 09:38:30 -07003833 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003834}
3835
3836status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3837 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003838 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003839{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003840 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003841 return BAD_VALUE;
3842 }
jiabin9a3361e2019-10-01 09:38:30 -07003843 index = curves.getVolumeIndex(deviceTypes);
3844 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003845 return NO_ERROR;
3846}
3847
3848status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3849 int &index)
3850{
3851 index = getVolumeCurves(attr).getVolumeIndexMin();
3852 return NO_ERROR;
3853}
3854
3855status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3856 int &index)
3857{
3858 index = getVolumeCurves(attr).getVolumeIndexMax();
3859 return NO_ERROR;
3860}
3861
Eric Laurent36829f92017-04-07 19:04:42 -07003862audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003863{
3864 // select one output among several suitable for global effects.
3865 // The priority is as follows:
3866 // 1: An offloaded output. If the effect ends up not being offloadable,
3867 // AudioFlinger will invalidate the track and the offloaded output
3868 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003869 // 2: Spatializer output if the stereo spatializer feature enabled
3870 // 3: A deep buffer output
3871 // 4: The primary output
3872 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003873
François Gaffiec005e562018-11-06 15:04:49 +01003874 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3875 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003876 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003877
Eric Laurent36829f92017-04-07 19:04:42 -07003878 if (outputs.size() == 0) {
3879 return AUDIO_IO_HANDLE_NONE;
3880 }
Eric Laurente552edb2014-03-10 17:42:56 -07003881
Eric Laurent36829f92017-04-07 19:04:42 -07003882 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3883 bool activeOnly = true;
3884
3885 while (output == AUDIO_IO_HANDLE_NONE) {
3886 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003887 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003888 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3889 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3890
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003891 for (audio_io_handle_t outputLoop : outputs) {
3892 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003893 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003894 continue;
3895 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003896 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003897 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003898 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003899 outputOffloaded = outputLoop;
3900 }
3901 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3902 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3903 outputSpatializer = outputLoop;
3904 }
Eric Laurent36829f92017-04-07 19:04:42 -07003905 }
3906 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003907 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003908 }
3909 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003910 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003911 }
3912 }
3913 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3914 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003915 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3916 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003917 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3918 output = outputDeepBuffer;
3919 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3920 output = outputPrimary;
3921 } else {
3922 output = outputs[0];
3923 }
3924 activeOnly = false;
3925 }
3926
3927 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003928 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3929 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003930 mMusicEffectOutput = output;
3931 }
3932
3933 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003934 return output;
3935}
3936
Eric Laurent36829f92017-04-07 19:04:42 -07003937audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3938{
3939 return selectOutputForMusicEffects();
3940}
3941
Eric Laurente0720872014-03-11 09:30:41 -07003942status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003943 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003944 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003945 int session,
3946 int id)
3947{
Shunkai Yao29d10572024-03-19 04:31:47 +00003948 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003949 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003950 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003951 index = mInputs.indexOfKey(io);
3952 if (index < 0) {
3953 ALOGW("registerEffect() unknown io %d", io);
3954 return INVALID_OPERATION;
3955 }
Eric Laurente552edb2014-03-10 17:42:56 -07003956 }
3957 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003958 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3959 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3960 || strategy == PRODUCT_STRATEGY_NONE));
3961 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003962}
3963
Eric Laurentc241b0d2018-11-28 09:08:49 -08003964status_t AudioPolicyManager::unregisterEffect(int id)
3965{
3966 if (mEffects.getEffect(id) == nullptr) {
3967 return INVALID_OPERATION;
3968 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003969 if (mEffects.isEffectEnabled(id)) {
3970 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3971 setEffectEnabled(id, false);
3972 }
3973 return mEffects.unregisterEffect(id);
3974}
3975
3976status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3977{
3978 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3979 if (effect == nullptr) {
3980 return INVALID_OPERATION;
3981 }
3982
3983 status_t status = mEffects.setEffectEnabled(id, enabled);
3984 if (status == NO_ERROR) {
3985 mInputs.trackEffectEnabled(effect, enabled);
3986 }
3987 return status;
3988}
3989
Eric Laurent6c796322019-04-09 14:13:17 -07003990
3991status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3992{
3993 mEffects.moveEffects(ids, io);
3994 return NO_ERROR;
3995}
3996
Eric Laurentc75307b2015-03-17 15:29:32 -07003997bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3998{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003999 auto vs = toVolumeSource(stream, false);
4000 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004001}
4002
4003bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
4004{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004005 auto vs = toVolumeSource(stream, false);
4006 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004007}
4008
Eric Laurente0720872014-03-11 09:30:41 -07004009bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07004010{
4011 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004012 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08004013 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004014 return true;
4015 }
4016 }
4017 return false;
4018}
4019
Eric Laurent275e8e92014-11-30 15:14:47 -08004020// Register a list of custom mixes with their attributes and format.
4021// When a mix is registered, corresponding input and output profiles are
4022// added to the remote submix hw module. The profile contains only the
4023// parameters (sampling rate, format...) specified by the mix.
4024// The corresponding input remote submix device is also connected.
4025//
4026// When a remote submix device is connected, the address is checked to select the
4027// appropriate profile and the corresponding input or output stream is opened.
4028//
4029// When capture starts, getInputForAttr() will:
4030// - 1 look for a mix matching the address passed in attribtutes tags if any
4031// - 2 if none found, getDeviceForInputSource() will:
4032// - 2.1 look for a mix matching the attributes source
4033// - 2.2 if none found, default to device selection by policy rules
4034// At this time, the corresponding output remote submix device is also connected
4035// and active playback use cases can be transferred to this mix if needed when reconnecting
4036// after AudioTracks are invalidated
4037//
4038// When playback starts, getOutputForAttr() will:
4039// - 1 look for a mix matching the address passed in attribtutes tags if any
4040// - 2 if none found, look for a mix matching the attributes usage
4041// - 3 if none found, default to device and output selection by policy rules.
4042
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004043status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004044{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004045 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4046 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004047 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004048 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004049 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004050 // examine each mix's route type
4051 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004052 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004053 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4054 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4055 ALOGE("Unsupported Policy Mix %zu of %zu: "
4056 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4057 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004058 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004059 break;
4060 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004061 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4062 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004063 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004064 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4065 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004066 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004067 rSubmixModule = mHwModules.getModuleFromName(
4068 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4069 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004070 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004071 i);
4072 res = INVALID_OPERATION;
4073 break;
4074 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004075 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004076
Eric Laurent97ac8712018-07-27 18:59:02 -07004077 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004078 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004079 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004080 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004081 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4082 } else {
4083 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4084 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004085 }
François Gaffie036e1e92015-03-19 10:16:24 +01004086
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004087 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004088 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004089 res = INVALID_OPERATION;
4090 break;
4091 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004092 audio_config_t outputConfig = mix.mFormat;
4093 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004094 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4095 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004096 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4097 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004098 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004099 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4100 audio_is_linear_pcm(outputConfig.format)
4101 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004102 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004103 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4104 audio_is_linear_pcm(inputConfig.format)
4105 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004106
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004107 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004108 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004109 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004110 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004111 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004112 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004113 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004114 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4115 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004116 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004117 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004118 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004119
4120 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4121 mix.mDeviceType, mix.mDeviceAddress,
4122 String8(), AUDIO_FORMAT_DEFAULT);
4123 if (device == nullptr) {
4124 res = INVALID_OPERATION;
4125 break;
4126 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004127
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004128 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004129 // First try to find an already opened output supporting the device
4130 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004131 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004132
Eric Laurentc529cf62020-04-17 18:19:10 -07004133 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004134 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004135 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004136 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004137 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004138 } else {
4139 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004140 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004141 }
4142 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004143 // If no output found, try to find a direct output profile supporting the device
4144 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4145 sp<HwModule> module = mHwModules[i];
4146 for (size_t j = 0;
4147 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4148 j++) {
4149 sp<IOProfile> profile = module->getOutputProfiles()[j];
4150 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4151 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4152 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004153 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004154 res = INVALID_OPERATION;
4155 } else {
4156 foundOutput = true;
4157 }
4158 }
4159 }
4160 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004161 if (res != NO_ERROR) {
4162 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004163 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004164 res = INVALID_OPERATION;
4165 break;
4166 } else if (!foundOutput) {
4167 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004168 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004169 res = INVALID_OPERATION;
4170 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004171 } else {
4172 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004173 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004174 }
Eric Laurentc722f302014-12-10 11:21:49 -08004175 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004176 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004177 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004178 if (audio_flags::audio_mix_ownership()) {
4179 // Only unregister mixes that were actually registered to not accidentally unregister
4180 // mixes that already existed previously.
4181 unregisterPolicyMixes(registeredMixes);
4182 registeredMixes.clear();
4183 } else {
4184 unregisterPolicyMixes(mixes);
4185 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004186 } else if (checkOutputs) {
4187 checkForDeviceAndOutputChanges();
4188 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004189 }
4190 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004191}
4192
4193status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4194{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004195 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004196 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004197 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004198 sp<HwModule> rSubmixModule;
4199 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004200 for (const auto& mix : mixes) {
4201 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004202
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004203 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004204 rSubmixModule = mHwModules.getModuleFromName(
4205 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4206 if (rSubmixModule == 0) {
4207 res = INVALID_OPERATION;
4208 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004209 }
4210 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004211
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004212 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004213
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004214 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004215 res = INVALID_OPERATION;
4216 continue;
4217 }
4218
Marvin Ramin0783e202024-03-05 12:45:50 +01004219 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004220 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004221 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4222 status_t currentRes =
4223 setDeviceConnectionStateInt(device,
4224 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4225 address.c_str(),
4226 "remote-submix",
4227 AUDIO_FORMAT_DEFAULT);
4228 if (!audio_flags::audio_mix_ownership()) {
4229 res = currentRes;
4230 }
4231 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004232 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004233 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004234 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004235 }
4236 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004237 }
jiabin5740f082019-08-19 15:08:30 -07004238 rSubmixModule->removeOutputProfile(address.c_str());
4239 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004240
Kevin Rocard153f92d2018-12-18 18:33:28 -08004241 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004242 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004243 res = INVALID_OPERATION;
4244 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004245 } else {
4246 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004247 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004248 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004249 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004250
4251 if (res == NO_ERROR && checkOutputs) {
4252 checkForDeviceAndOutputChanges();
4253 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004254 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004255 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004256}
4257
Marvin Raminbdefaf02023-11-01 09:10:32 +01004258status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4259 if (!audio_flags::audio_mix_test_api()) {
4260 return INVALID_OPERATION;
4261 }
4262
4263 _aidl_return.clear();
4264 _aidl_return.reserve(mPolicyMixes.size());
4265 for (const auto &policyMix: mPolicyMixes) {
4266 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4267 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4268 policyMix->mCbFlags);
4269 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004270 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004271 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004272 }
4273
Vlad Popaa5d73f32024-03-08 16:05:38 -08004274 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004275 return OK;
4276}
4277
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004278status_t AudioPolicyManager::updatePolicyMix(
4279 const AudioMix& mix,
4280 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4281 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4282 if (res == NO_ERROR) {
4283 checkForDeviceAndOutputChanges();
4284 updateCallAndOutputRouting();
4285 }
4286 return res;
4287}
4288
Mikhail Naganov100f0122018-11-29 11:22:16 -08004289void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4290{
4291 size_t i = 0;
4292 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4293 for (const auto& fmt : mManualSurroundFormats) {
4294 if (i++ != 0) dst->append(", ");
4295 std::string sfmt;
4296 FormatConverter::toString(fmt, sfmt);
4297 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4298 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4299 }
4300}
4301
Eric Laurentc529cf62020-04-17 18:19:10 -07004302// Returns true if all devices types match the predicate and are supported by one HW module
4303bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004304 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004305 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004306 const char *context,
4307 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004308 for (size_t i = 0; i < devices.size(); i++) {
4309 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004310 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004311 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004312 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004313 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004314 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004315 return false;
4316 }
4317 }
4318 return true;
4319}
4320
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004321void AudioPolicyManager::changeOutputDevicesMuteState(
4322 const AudioDeviceTypeAddrVector& devices) {
4323 ALOGVV("%s() num devices %zu", __func__, devices.size());
4324
4325 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4326 getSoftwareOutputsForDevices(devices);
4327
4328 for (size_t i = 0; i < outputs.size(); i++) {
4329 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4330 DeviceVector prevDevices = outputDesc->devices();
4331 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4332 }
4333}
4334
4335std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4336 const AudioDeviceTypeAddrVector& devices) const
4337{
4338 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4339 DeviceVector deviceDescriptors;
4340 for (size_t j = 0; j < devices.size(); j++) {
4341 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4342 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4343 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4344 ALOGE("%s: device type %#x address %s not supported or not an output device",
4345 __func__, devices[j].mType, devices[j].getAddress());
4346 continue;
4347 }
4348 deviceDescriptors.add(desc);
4349 }
4350 for (size_t i = 0; i < mOutputs.size(); i++) {
4351 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4352 continue;
4353 }
4354 outputs.push_back(mOutputs.valueAt(i));
4355 }
4356 return outputs;
4357}
4358
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004359status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004360 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004361 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004362 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4363 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004364 }
4365 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004366 if (res != NO_ERROR) {
4367 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4368 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004369 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004370
4371 checkForDeviceAndOutputChanges();
4372 updateCallAndOutputRouting();
4373
4374 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004375}
4376
4377status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4378 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004379 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4380 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004381 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004382 __FUNCTION__, uid);
4383 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004384 }
4385
Eric Laurentc529cf62020-04-17 18:19:10 -07004386 checkForDeviceAndOutputChanges();
4387 updateCallAndOutputRouting();
4388
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004389 return res;
4390}
4391
Eric Laurent2517af32020-11-25 15:31:27 +01004392
jiabin0a488932020-08-07 17:32:40 -07004393status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4394 device_role_t role,
4395 const AudioDeviceTypeAddrVector &devices) {
4396 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4397 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004398
Eric Laurentc529cf62020-04-17 18:19:10 -07004399 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004400 return BAD_VALUE;
4401 }
jiabin0a488932020-08-07 17:32:40 -07004402 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004403 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004404 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4405 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004406 return status;
4407 }
4408
4409 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004410
4411 bool forceVolumeReeval = false;
4412 // FIXME: workaround for truncated touch sounds
4413 // to be removed when the problem is handled by system UI
4414 uint32_t delayMs = 0;
4415 if (strategy == mCommunnicationStrategy) {
4416 forceVolumeReeval = true;
4417 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4418 updateInputRouting();
4419 }
4420 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004421
4422 return NO_ERROR;
4423}
4424
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004425void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4426 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004427{
4428 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004429 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004430 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004431 // Only apply special touch sound delay once
4432 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004433 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004434 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004435 for (size_t i = 0; i < mOutputs.size(); i++) {
4436 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4437 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004438 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4439 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004440 // As done in setDeviceConnectionState, we could also fix default device issue by
4441 // preventing the force re-routing in case of default dev that distinguishes on address.
4442 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004443 bool newDevicesNotEmpty = !newDevices.isEmpty();
4444 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4445 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004446 // If the device is using preferred mixer attributes, the output need to reopen
4447 // with default configuration when the new selected devices are different from
4448 // current routing devices.
4449 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4450 continue;
4451 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304452
jiabin2361ed82024-09-20 17:36:31 +00004453 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4454 newDevicesNotEmpty /*force*/, delayMs,
4455 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4456 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004457 // Only apply special touch sound delay once
4458 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004459 }
4460 if (forceVolumeReeval && !newDevices.isEmpty()) {
4461 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4462 }
4463 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004464 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004465 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004466}
4467
Eric Laurent2517af32020-11-25 15:31:27 +01004468void AudioPolicyManager::updateInputRouting() {
4469 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304470 // Skip for hotword recording as the input device switch
4471 // is handled within sound trigger HAL
4472 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4473 continue;
4474 }
Eric Laurent2517af32020-11-25 15:31:27 +01004475 auto newDevice = getNewInputDevice(activeDesc);
4476 // Force new input selection if the new device can not be reached via current input
4477 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4478 setInputDevice(activeDesc->mIoHandle, newDevice);
4479 } else {
4480 closeInput(activeDesc->mIoHandle);
4481 }
4482 }
4483}
4484
Paul Wang5d7cdb52022-11-22 09:45:06 +00004485status_t
4486AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4487 device_role_t role,
4488 const AudioDeviceTypeAddrVector &devices) {
4489 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4490 dumpAudioDeviceTypeAddrVector(devices).c_str());
4491
Eric Laurent78fedbf2023-03-09 14:40:44 +01004492 if (!areAllDevicesSupported(
4493 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004494 return BAD_VALUE;
4495 }
4496 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4497 if (status != NO_ERROR) {
4498 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4499 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4500 return status;
4501 }
4502
4503 checkForDeviceAndOutputChanges();
4504
4505 bool forceVolumeReeval = false;
4506 // TODO(b/263479999): workaround for truncated touch sounds
4507 // to be removed when the problem is handled by system UI
4508 uint32_t delayMs = 0;
4509 if (strategy == mCommunnicationStrategy) {
4510 forceVolumeReeval = true;
4511 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4512 updateInputRouting();
4513 }
4514 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4515
4516 return NO_ERROR;
4517}
4518
4519status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4520 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004521{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004522 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004523
Paul Wang5d7cdb52022-11-22 09:45:06 +00004524 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004525 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004526 ALOGW_IF(status != NAME_NOT_FOUND,
4527 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004528 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004529 return status;
4530 }
4531
4532 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004533
4534 bool forceVolumeReeval = false;
4535 // FIXME: workaround for truncated touch sounds
4536 // to be removed when the problem is handled by system UI
4537 uint32_t delayMs = 0;
4538 if (strategy == mCommunnicationStrategy) {
4539 forceVolumeReeval = true;
4540 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4541 updateInputRouting();
4542 }
4543 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004544
4545 return NO_ERROR;
4546}
4547
jiabin0a488932020-08-07 17:32:40 -07004548status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4549 device_role_t role,
4550 AudioDeviceTypeAddrVector &devices) {
4551 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004552}
4553
Jiabin Huang3b98d322020-09-03 17:54:16 +00004554status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4555 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4556 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4557 dumpAudioDeviceTypeAddrVector(devices).c_str());
4558
Mikhail Naganov55773032020-10-01 15:08:13 -07004559 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004560 return BAD_VALUE;
4561 }
4562 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4563 ALOGW_IF(status != NO_ERROR,
4564 "Engine could not set preferred devices %s for audio source %d role %d",
4565 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4566
Wenyu Zhang47655d22024-10-01 12:24:53 +00004567 if (status == NO_ERROR) {
4568 updateInputRouting();
4569 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004570 return status;
4571}
4572
4573status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4574 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4575 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4576 dumpAudioDeviceTypeAddrVector(devices).c_str());
4577
Mikhail Naganov55773032020-10-01 15:08:13 -07004578 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004579 return BAD_VALUE;
4580 }
4581 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4582 ALOGW_IF(status != NO_ERROR,
4583 "Engine could not add preferred devices %s for audio source %d role %d",
4584 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4585
Eric Laurent2517af32020-11-25 15:31:27 +01004586 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004587 return status;
4588}
4589
4590status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4591 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4592{
4593 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4594 dumpAudioDeviceTypeAddrVector(devices).c_str());
4595
Eric Laurent78fedbf2023-03-09 14:40:44 +01004596 if (!areAllDevicesSupported(
4597 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004598 return BAD_VALUE;
4599 }
4600
4601 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4602 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004603 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004604 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004605 if (status == NO_ERROR) {
4606 updateInputRouting();
4607 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004608 return status;
4609}
4610
4611status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4612 device_role_t role) {
4613 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4614
4615 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004616 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004617 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004618 if (status == NO_ERROR) {
4619 updateInputRouting();
4620 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004621 return status;
4622}
4623
4624status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4625 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4626 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4627}
4628
Oscar Azucena90e77632019-11-27 17:12:28 -08004629status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004630 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004631 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004632 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4633 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004634 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004635 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4636 if (status != NO_ERROR) {
4637 ALOGE("%s() could not set device affinity for userId %d",
4638 __FUNCTION__, userId);
4639 return status;
4640 }
4641
4642 // reevaluate outputs for all devices
4643 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004644 changeOutputDevicesMuteState(devices);
4645 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4646 true /* skipDelays */);
4647 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004648
4649 return NO_ERROR;
4650}
4651
4652status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004653 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004654 AudioDeviceTypeAddrVector devices;
4655 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004656 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4657 if (status != NO_ERROR) {
4658 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4659 __FUNCTION__, userId);
4660 return status;
4661 }
4662
4663 // reevaluate outputs for all devices
4664 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004665 changeOutputDevicesMuteState(devices);
4666 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4667 true /* skipDelays */);
4668 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004669
4670 return NO_ERROR;
4671}
4672
Andy Hungc29d82b2018-10-05 12:23:17 -07004673void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004674{
Andy Hungc29d82b2018-10-05 12:23:17 -07004675 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004676 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004677 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004678 std::string stateLiteral;
4679 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004680 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004681 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4682 "communications", "media", "record", "dock", "system",
4683 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4684 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4685 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004686 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4687 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4688 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4689 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4690 dst->append(" (MANUAL: ");
4691 dumpManualSurroundFormats(dst);
4692 dst->append(")");
4693 }
4694 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004695 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004696 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4697 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004698 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004699 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004700
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004701 dst->append("\n");
4702 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4703 dst->append("\n");
4704 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004705 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004706 mOutputs.dump(dst);
4707 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004708 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004709 mAudioPatches.dump(dst);
4710 mPolicyMixes.dump(dst);
4711 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004712
Kevin Rocardb99cc752019-03-21 20:52:24 -07004713 dst->appendFormat(" AllowedCapturePolicies:\n");
4714 for (auto& policy : mAllowedCapturePolicies) {
4715 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4716 }
4717
jiabina84c3d32022-12-02 18:59:55 +00004718 dst->appendFormat(" Preferred mixer audio configuration:\n");
4719 for (const auto it : mPreferredMixerAttrInfos) {
4720 dst->appendFormat(" - device port id: %d\n", it.first);
4721 for (const auto preferredMixerInfoIt : it.second) {
4722 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4723 preferredMixerInfoIt.second->dump(dst);
4724 }
4725 }
4726
François Gaffiec005e562018-11-06 15:04:49 +01004727 dst->appendFormat("\nPolicy Engine dump:\n");
4728 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004729
4730 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4731 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4732 dst->appendFormat(" - device type: %s, driving stream %d\n",
4733 dumpDeviceTypes({it.first}).c_str(),
4734 mEngine->getVolumeGroupForAttributes(it.second));
4735 }
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00004736
4737 // dump mmap policy by device
4738 dst->appendFormat("\nMmap policy:\n");
4739 for (const auto& [policyType, policyByDevice] : mMmapPolicyByDeviceType) {
4740 std::stringstream ss;
4741 ss << '{';
4742 for (const auto& [deviceType, policy] : policyByDevice) {
4743 ss << deviceType.toString() << ":" << toString(policy) << " ";
4744 }
4745 ss << '}';
4746 dst->appendFormat(" - %s: %s\n", toString(policyType).c_str(), ss.str().c_str());
4747 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004748}
4749
4750status_t AudioPolicyManager::dump(int fd)
4751{
4752 String8 result;
4753 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004754 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004755 return NO_ERROR;
4756}
4757
Kevin Rocardb99cc752019-03-21 20:52:24 -07004758status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4759{
4760 mAllowedCapturePolicies[uid] = capturePolicy;
4761 return NO_ERROR;
4762}
4763
Eric Laurente552edb2014-03-10 17:42:56 -07004764// This function checks for the parameters which can be offloaded.
4765// This can be enhanced depending on the capability of the DSP and policy
4766// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004767audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004768{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004769 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004770 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004771 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004772 offloadInfo.format,
4773 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4774 offloadInfo.has_video);
4775
jiabin2b9d5a12021-12-10 01:06:29 +00004776 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004777 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004778 }
4779
4780 // See if there is a profile to support this.
4781 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004782 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004783 offloadInfo.sample_rate,
4784 offloadInfo.format,
4785 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004786 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4787 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004788 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4789 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4790 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004791 if (profile == nullptr) {
4792 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4793 }
4794 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4795 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4796 }
4797 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004798}
4799
Michael Chana94fbb22018-04-24 14:31:19 +10004800bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4801 const audio_attributes_t& attributes) {
4802 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004803 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004804 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4805 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004806 config.sample_rate,
4807 config.format,
4808 config.channel_mask,
4809 output_flags,
4810 true /* directOnly */);
4811 ALOGV("%s() profile %sfound with name: %s, "
4812 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4813 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004814 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004815 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004816
4817 // also try the MSD module if compatible profile not found
4818 if (profile == nullptr) {
4819 profile = getMsdProfileForOutput(outputDevices,
4820 config.sample_rate,
4821 config.format,
4822 config.channel_mask,
4823 output_flags,
4824 true /* directOnly */);
4825 ALOGV("%s() MSD profile %sfound with name: %s, "
4826 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4827 __FUNCTION__, profile != 0 ? "" : "NOT ",
4828 (profile != 0 ? profile->getTagName().c_str() : "null"),
4829 config.sample_rate, config.format, config.channel_mask, output_flags);
4830 }
4831 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004832}
4833
jiabin2b9d5a12021-12-10 01:06:29 +00004834bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4835 bool durationIgnored) {
4836 if (mMasterMono) {
4837 return false; // no offloading if mono is set.
4838 }
4839
4840 // Check if offload has been disabled
4841 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4842 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4843 return false;
4844 }
4845
4846 // Check if stream type is music, then only allow offload as of now.
4847 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4848 {
4849 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4850 return false;
4851 }
4852
4853 //TODO: enable audio offloading with video when ready
4854 const bool allowOffloadWithVideo =
4855 property_get_bool("audio.offload.video", false /* default_value */);
4856 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4857 ALOGV("%s: has_video == true, returning false", __func__);
4858 return false;
4859 }
4860
4861 //If duration is less than minimum value defined in property, return false
4862 const int min_duration_secs = property_get_int32(
4863 "audio.offload.min.duration.secs", -1 /* default_value */);
4864 if (!durationIgnored) {
4865 if (min_duration_secs >= 0) {
4866 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4867 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4868 __func__, min_duration_secs);
4869 return false;
4870 }
4871 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4872 ALOGV("%s: Offload denied by duration < default min(=%u)",
4873 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4874 return false;
4875 }
4876 }
4877
4878 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4879 // creating an offloaded track and tearing it down immediately after start when audioflinger
4880 // detects there is an active non offloadable effect.
4881 // FIXME: We should check the audio session here but we do not have it in this context.
4882 // This may prevent offloading in rare situations where effects are left active by apps
4883 // in the background.
4884 if (mEffects.isNonOffloadableEffectEnabled()) {
4885 return false;
4886 }
4887
4888 return true;
4889}
4890
4891audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4892 const audio_config_t *config) {
4893 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4894 offloadInfo.format = config->format;
4895 offloadInfo.sample_rate = config->sample_rate;
4896 offloadInfo.channel_mask = config->channel_mask;
4897 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4898 offloadInfo.has_video = false;
4899 offloadInfo.is_streaming = false;
4900 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4901
4902 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4903 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4904 audio_flags_to_audio_output_flags(attr->flags, &flags);
4905 // only retain flags that will drive compressed offload or passthrough
4906 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4907 if (offloadPossible) {
4908 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4909 }
4910 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4911
Dorin Drimusfae3c642022-03-17 18:36:30 +01004912 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004913 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4914 [this, attr](sp<DeviceDescriptor> device) {
4915 return getPreferredMixerAttributesInfo(
4916 device->getId(),
4917 mEngine->getProductStrategyForAttributes(*attr),
4918 true /*activeBitPerfectPreferred*/) != nullptr;
4919 })) {
4920 // Bit-perfect playback is active on one of the selected devices, direct output will
4921 // be rejected at this instant.
4922 return AUDIO_DIRECT_NOT_SUPPORTED;
4923 }
jiabin2b9d5a12021-12-10 01:06:29 +00004924 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004925 DeviceVector outputDevices = engineOutputDevices;
4926 // the MSD module checks for different conditions and output devices
4927 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4928 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4929 continue;
4930 }
4931 outputDevices = getMsdAudioOutDevices();
4932 }
jiabin2b9d5a12021-12-10 01:06:29 +00004933 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004934 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004935 config->sample_rate, nullptr /*updatedSamplingRate*/,
4936 config->format, nullptr /*updatedFormat*/,
4937 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004938 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004939 continue;
4940 }
4941 // reject profiles not corresponding to a device currently available
4942 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4943 continue;
4944 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004945 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4946 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004947 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004948 != AUDIO_DIRECT_NOT_SUPPORTED) {
4949 // Already reports offload gapless supported. No need to report offload support.
4950 continue;
4951 }
4952 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4953 != AUDIO_OUTPUT_FLAG_NONE) {
4954 // If offload gapless is reported, no need to report offload support.
4955 directMode = (audio_direct_mode_t) ((directMode &
4956 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4957 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4958 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004959 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004960 }
4961 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004962 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004963 }
4964 }
4965 }
4966 return directMode;
4967}
4968
Dorin Drimusf2196d82022-01-03 12:11:18 +01004969status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4970 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004971 if (mEffects.isNonOffloadableEffectEnabled()) {
4972 return OK;
4973 }
jiabinf1c73972022-04-14 16:28:52 -07004974 DeviceVector devices;
4975 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004976 if (status != OK) {
4977 return status;
4978 }
4979 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4980 if (devices.empty()) {
4981 return OK; // no output devices for the attributes
4982 }
jiabinf1c73972022-04-14 16:28:52 -07004983 return getProfilesForDevices(devices, audioProfilesVector,
4984 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004985}
4986
jiabina84c3d32022-12-02 18:59:55 +00004987status_t AudioPolicyManager::getSupportedMixerAttributes(
4988 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4989 ALOGV("%s, portId=%d", __func__, portId);
4990 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4991 if (deviceDescriptor == nullptr) {
4992 ALOGE("%s the requested device is currently unavailable", __func__);
4993 return BAD_VALUE;
4994 }
jiabin96daffc2023-05-11 17:51:55 +00004995 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4996 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4997 deviceDescriptor->type());
4998 return BAD_VALUE;
4999 }
jiabina84c3d32022-12-02 18:59:55 +00005000 for (const auto& hwModule : mHwModules) {
5001 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5002 if (curProfile->supportsDevice(deviceDescriptor)) {
5003 curProfile->toSupportedMixerAttributes(&mixerAttrs);
5004 }
5005 }
5006 }
5007 return NO_ERROR;
5008}
5009
5010status_t AudioPolicyManager::setPreferredMixerAttributes(
5011 const audio_attributes_t *attr,
5012 audio_port_handle_t portId,
5013 uid_t uid,
5014 const audio_mixer_attributes_t *mixerAttributes) {
5015 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
5016 "mixerBehavior=%d}, uid=%d, portId=%u",
5017 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
5018 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
5019 mixerAttributes->mixer_behavior, uid, portId);
5020 if (attr->usage != AUDIO_USAGE_MEDIA) {
5021 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
5022 return BAD_VALUE;
5023 }
5024 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5025 if (deviceDescriptor == nullptr) {
5026 ALOGE("%s the requested device is currently unavailable", __func__);
5027 return BAD_VALUE;
5028 }
5029 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5030 ALOGE("%s(%d), type=%d, is not a usb output device",
5031 __func__, portId, deviceDescriptor->type());
5032 return BAD_VALUE;
5033 }
5034
5035 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5036 audio_flags_to_audio_output_flags(attr->flags, &flags);
5037 flags = (audio_output_flags_t) (flags |
5038 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5039 sp<IOProfile> profile = nullptr;
5040 DeviceVector devices(deviceDescriptor);
5041 for (const auto& hwModule : mHwModules) {
5042 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5043 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005044 && curProfile->getCompatibilityScore(
5045 devices,
5046 mixerAttributes->config.sample_rate,
5047 nullptr /*updatedSamplingRate*/,
5048 mixerAttributes->config.format,
5049 nullptr /*updatedFormat*/,
5050 mixerAttributes->config.channel_mask,
5051 nullptr /*updatedChannelMask*/,
jiabin91beb492024-10-16 21:53:36 +00005052 flags)
jiabin66acc432024-02-06 00:57:36 +00005053 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005054 profile = curProfile;
5055 break;
5056 }
5057 }
5058 }
5059 if (profile == nullptr) {
5060 ALOGE("%s, there is no compatible profile found", __func__);
5061 return BAD_VALUE;
5062 }
5063
5064 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5065 sp<PreferredMixerAttributesInfo>::make(
5066 uid, portId, profile, flags, *mixerAttributes);
5067 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5068 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5069
5070 // If 1) there is any client from the preferred mixer configuration owner that is currently
5071 // active and matches the strategy and 2) current output is on the preferred device and the
5072 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5073 // configuration.
5074 std::vector<audio_io_handle_t> outputsToReopen;
5075 for (size_t i = 0; i < mOutputs.size(); i++) {
5076 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005077 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5078 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005079 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005080 } else {
5081 for (const auto &client: output->getActiveClients()) {
5082 if (client->uid() == uid && client->strategy() == strategy) {
5083 client->setIsInvalid();
5084 outputsToReopen.push_back(output->mIoHandle);
5085 }
jiabina84c3d32022-12-02 18:59:55 +00005086 }
5087 }
5088 }
5089 }
5090 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5091 config.sample_rate = mixerAttributes->config.sample_rate;
5092 config.channel_mask = mixerAttributes->config.channel_mask;
5093 config.format = mixerAttributes->config.format;
5094 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005095 sp<SwAudioOutputDescriptor> desc =
5096 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5097 if (desc == nullptr) {
5098 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5099 continue;
5100 }
jiabin220eea12024-05-17 17:55:20 +00005101 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005102 }
5103
5104 return NO_ERROR;
5105}
5106
5107sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005108 audio_port_handle_t devicePortId,
5109 product_strategy_t strategy,
5110 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005111 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5112 if (it == mPreferredMixerAttrInfos.end()) {
5113 return nullptr;
5114 }
jiabind9a58d32023-06-01 17:57:30 +00005115 if (activeBitPerfectPreferred) {
5116 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005117 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005118 return info;
5119 }
5120 }
jiabina84c3d32022-12-02 18:59:55 +00005121 }
jiabind9a58d32023-06-01 17:57:30 +00005122 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5123 return strategyMatchedMixerAttrInfoIt == it->second.end()
5124 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005125}
5126
5127status_t AudioPolicyManager::getPreferredMixerAttributes(
5128 const audio_attributes_t *attr,
5129 audio_port_handle_t portId,
5130 audio_mixer_attributes_t* mixerAttributes) {
5131 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5132 portId, mEngine->getProductStrategyForAttributes(*attr));
5133 if (info == nullptr) {
5134 return NAME_NOT_FOUND;
5135 }
5136 *mixerAttributes = info->getMixerAttributes();
5137 return NO_ERROR;
5138}
5139
5140status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5141 audio_port_handle_t portId,
5142 uid_t uid) {
5143 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5144 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5145 if (preferredMixerAttrInfo == nullptr) {
5146 return NAME_NOT_FOUND;
5147 }
5148 if (preferredMixerAttrInfo->getUid() != uid) {
5149 ALOGE("%s, requested uid=%d, owned uid=%d",
5150 __func__, uid, preferredMixerAttrInfo->getUid());
5151 return PERMISSION_DENIED;
5152 }
5153 mPreferredMixerAttrInfos[portId].erase(strategy);
5154 if (mPreferredMixerAttrInfos[portId].empty()) {
5155 mPreferredMixerAttrInfos.erase(portId);
5156 }
5157
5158 // Reconfig existing output
5159 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5160 for (size_t i = 0; i < mOutputs.size(); i++) {
5161 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5162 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5163 }
5164 }
5165 for (const auto output : potentialOutputsToReopen) {
5166 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5167 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5168 preferredMixerAttrInfo->getFlags())) {
5169 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5170 }
5171 }
5172 return NO_ERROR;
5173}
5174
Eric Laurent6a94d692014-05-20 11:18:06 -07005175status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5176 audio_port_type_t type,
5177 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005178 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 unsigned int *generation)
5180{
jiabin19cdba52020-11-24 11:28:58 -08005181 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5182 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005183 return BAD_VALUE;
5184 }
5185 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005186 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005187 *num_ports = 0;
5188 }
5189
5190 size_t portsWritten = 0;
5191 size_t portsMax = *num_ports;
5192 *num_ports = 0;
5193 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005194 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5195 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005197 for (const auto& dev : mAvailableOutputDevices) {
5198 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005199 continue;
5200 }
5201 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005202 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005203 }
5204 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005206 }
5207 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005208 for (const auto& dev : mAvailableInputDevices) {
5209 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005210 continue;
5211 }
5212 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005213 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005214 }
5215 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005216 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 }
5218 }
5219 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5220 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5221 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5222 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5223 }
5224 *num_ports += mInputs.size();
5225 }
5226 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005227 size_t numOutputs = 0;
5228 for (size_t i = 0; i < mOutputs.size(); i++) {
5229 if (!mOutputs[i]->isDuplicated()) {
5230 numOutputs++;
5231 if (portsWritten < portsMax) {
5232 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5233 }
5234 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 }
Eric Laurent84c70242014-06-23 08:46:27 -07005236 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 }
5238 }
jiabina84c3d32022-12-02 18:59:55 +00005239
Eric Laurent6a94d692014-05-20 11:18:06 -07005240 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005241 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005242 return NO_ERROR;
5243}
5244
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005245status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5246 std::vector<media::AudioPortFw>* _aidl_return) {
5247 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5248 audio_port_v7 port;
5249 dev->toAudioPort(&port);
5250 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5251 _aidl_return->push_back(std::move(aidlPort));
5252 return OK;
5253 };
5254
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005255 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005256 for (const auto& dev : module->getDeclaredDevices()) {
5257 if (role == media::AudioPortRole::NONE ||
5258 ((role == media::AudioPortRole::SOURCE)
5259 == audio_is_input_device(dev->type()))) {
5260 RETURN_STATUS_IF_ERROR(pushPort(dev));
5261 }
5262 }
5263 }
5264 return OK;
5265}
5266
jiabin19cdba52020-11-24 11:28:58 -08005267status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005268{
Eric Laurent99fcae42018-05-17 16:59:18 -07005269 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5270 return BAD_VALUE;
5271 }
5272 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5273 if (dev != 0) {
5274 dev->toAudioPort(port);
5275 return NO_ERROR;
5276 }
5277 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5278 if (dev != 0) {
5279 dev->toAudioPort(port);
5280 return NO_ERROR;
5281 }
5282 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5283 if (out != 0) {
5284 out->toAudioPort(port);
5285 return NO_ERROR;
5286 }
5287 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5288 if (in != 0) {
5289 in->toAudioPort(port);
5290 return NO_ERROR;
5291 }
5292 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005293}
5294
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005295status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5296 audio_patch_handle_t *handle,
5297 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005298{
François Gaffieafd4cea2019-11-18 15:50:22 +01005299 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 if (handle == NULL || patch == NULL) {
5301 return BAD_VALUE;
5302 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005303 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005304 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005305 return BAD_VALUE;
5306 }
5307 // only one source per audio patch supported for now
5308 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 return INVALID_OPERATION;
5310 }
Eric Laurent874c42872014-08-08 15:13:39 -07005311 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005312 return INVALID_OPERATION;
5313 }
Eric Laurent874c42872014-08-08 15:13:39 -07005314 for (size_t i = 0; i < patch->num_sinks; i++) {
5315 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5316 return INVALID_OPERATION;
5317 }
5318 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005319
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005320 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5321 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5322 if (srcDevice == nullptr || sinkDevice == nullptr) {
5323 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5324 return BAD_VALUE;
5325 }
5326 ALOGV("%s between source %s and sink %s", __func__,
5327 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5328 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5329 // Default attributes, default volume priority, not to infer with non raw audio patches.
5330 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5331 const struct audio_port_config *source = &patch->sources[0];
5332 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005333 new SourceClientDescriptor(
5334 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5335 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005336 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005337 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005338
5339 status_t status =
5340 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5341
5342 if (status != NO_ERROR) {
5343 return INVALID_OPERATION;
5344 }
5345 mAudioSources.add(portId, sourceDesc);
5346 return NO_ERROR;
5347}
5348
5349status_t AudioPolicyManager::connectAudioSourceToSink(
5350 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5351 const struct audio_patch *patch,
5352 audio_patch_handle_t &handle,
5353 uid_t uid, uint32_t delayMs)
5354{
5355 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5356 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5357 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5358 return INVALID_OPERATION;
5359 }
5360 sourceDesc->connect(handle, sinkDevice);
5361 if (isMsdPatch(handle)) {
5362 return NO_ERROR;
5363 }
5364 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5365 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5366 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5367 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5368 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5369 goto FailurePatchAdded;
5370 }
5371 status = swOutput->start();
5372 if (status != NO_ERROR) {
5373 goto FailureSourceAdded;
5374 }
5375 swOutput->addClient(sourceDesc);
5376 status = startSource(swOutput, sourceDesc, &delayMs);
5377 if (status != NO_ERROR) {
5378 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5379 goto FailureSourceActive;
5380 }
5381 if (delayMs != 0) {
5382 usleep(delayMs * 1000);
5383 }
5384 return NO_ERROR;
5385
5386FailureSourceActive:
5387 swOutput->stop();
5388 releaseOutput(sourceDesc->portId());
5389FailureSourceAdded:
5390 sourceDesc->setSwOutput(nullptr);
5391FailurePatchAdded:
5392 releaseAudioPatchInternal(handle);
5393 return INVALID_OPERATION;
5394}
5395
5396status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5397 audio_patch_handle_t *handle,
5398 uid_t uid, uint32_t delayMs,
5399 const sp<SourceClientDescriptor>& sourceDesc)
5400{
5401 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005402 sp<AudioPatch> patchDesc;
5403 ssize_t index = mAudioPatches.indexOfKey(*handle);
5404
François Gaffieafd4cea2019-11-18 15:50:22 +01005405 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5406 patch->sources[0].role,
5407 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005408#if LOG_NDEBUG == 0
5409 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005410 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5411 patch->sinks[i].role,
5412 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005413 }
5414#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005415
5416 if (index >= 0) {
5417 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005418 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5419 __func__, mUidCached, patchDesc->getUid(), uid);
5420 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 return INVALID_OPERATION;
5422 }
5423 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005424 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005425 }
5426
5427 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005428 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005429 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005430 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005431 return BAD_VALUE;
5432 }
Eric Laurent84c70242014-06-23 08:46:27 -07005433 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5434 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005435 if (patchDesc != 0) {
5436 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005437 ALOGV("%s source id differs for patch current id %d new id %d",
5438 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005439 return BAD_VALUE;
5440 }
5441 }
Eric Laurent874c42872014-08-08 15:13:39 -07005442 DeviceVector devices;
5443 for (size_t i = 0; i < patch->num_sinks; i++) {
5444 // Only support mix to devices connection
5445 // TODO add support for mix to mix connection
5446 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005447 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005448 return INVALID_OPERATION;
5449 }
5450 sp<DeviceDescriptor> devDesc =
5451 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5452 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005453 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005454 return BAD_VALUE;
5455 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005456
jiabin66acc432024-02-06 00:57:36 +00005457 if (outputDesc->mProfile->getCompatibilityScore(
5458 DeviceVector(devDesc),
5459 patch->sources[0].sample_rate,
5460 nullptr, // updatedSamplingRate
5461 patch->sources[0].format,
5462 nullptr, // updatedFormat
5463 patch->sources[0].channel_mask,
5464 nullptr, // updatedChannelMask
5465 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005466 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005467 return INVALID_OPERATION;
5468 }
5469 devices.add(devDesc);
5470 }
5471 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005472 return INVALID_OPERATION;
5473 }
Eric Laurent874c42872014-08-08 15:13:39 -07005474
Eric Laurent6a94d692014-05-20 11:18:06 -07005475 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005476 ALOGV("%s setting device %s on output %d",
5477 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305478 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005479 index = mAudioPatches.indexOfKey(*handle);
5480 if (index >= 0) {
5481 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005482 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005483 }
5484 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005485 patchDesc->setUid(uid);
5486 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005487 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005488 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005489 return INVALID_OPERATION;
5490 }
5491 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5492 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5493 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005494 // only one sink supported when connecting an input device to a mix
5495 if (patch->num_sinks > 1) {
5496 return INVALID_OPERATION;
5497 }
François Gaffie53615e22015-03-19 09:24:12 +01005498 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005499 if (inputDesc == NULL) {
5500 return BAD_VALUE;
5501 }
5502 if (patchDesc != 0) {
5503 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5504 return BAD_VALUE;
5505 }
5506 }
François Gaffie11d30102018-11-02 16:09:09 +01005507 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005508 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005509 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 return BAD_VALUE;
5511 }
5512
jiabin66acc432024-02-06 00:57:36 +00005513 if (inputDesc->mProfile->getCompatibilityScore(
5514 DeviceVector(device),
5515 patch->sinks[0].sample_rate,
5516 nullptr, /*updatedSampleRate*/
5517 patch->sinks[0].format,
5518 nullptr, /*updatedFormat*/
5519 patch->sinks[0].channel_mask,
5520 nullptr, /*updatedChannelMask*/
5521 // FIXME for the parameter type,
5522 // and the NONE
5523 (audio_output_flags_t)
5524 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005525 return INVALID_OPERATION;
5526 }
5527 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005528 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005529 device->toString().c_str(), inputDesc->mIoHandle);
5530 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005531 index = mAudioPatches.indexOfKey(*handle);
5532 if (index >= 0) {
5533 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005534 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005535 }
5536 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005537 patchDesc->setUid(uid);
5538 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005539 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005540 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005541 return INVALID_OPERATION;
5542 }
5543 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5544 // device to device connection
5545 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005546 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005547 return BAD_VALUE;
5548 }
5549 }
François Gaffie11d30102018-11-02 16:09:09 +01005550 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005551 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005552 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005553 return BAD_VALUE;
5554 }
Eric Laurent874c42872014-08-08 15:13:39 -07005555
Eric Laurent6a94d692014-05-20 11:18:06 -07005556 //update source and sink with our own data as the data passed in the patch may
5557 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005558 PatchBuilder patchBuilder;
5559 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005560
5561 // if first sink is to MSD, establish single MSD patch
5562 if (getMsdAudioOutDevices().contains(
5563 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5564 ALOGV("%s patching to MSD", __FUNCTION__);
5565 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5566 goto installPatch;
5567 }
5568
François Gaffieafd4cea2019-11-18 15:50:22 +01005569 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5570 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005571
Eric Laurent874c42872014-08-08 15:13:39 -07005572 for (size_t i = 0; i < patch->num_sinks; i++) {
5573 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005574 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005575 return INVALID_OPERATION;
5576 }
François Gaffie11d30102018-11-02 16:09:09 +01005577 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005578 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005579 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005580 return BAD_VALUE;
5581 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005582 audio_port_config sinkPortConfig = {};
5583 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5584 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005585
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005586 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5587 // volume management purpose (tracking activity)
5588 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5589 // in config XML to reach the sink so that is can be declared as available.
5590 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005591 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005592 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005593 // take care of dynamic routing for SwOutput selection,
5594 audio_attributes_t attributes = sourceDesc->attributes();
5595 audio_stream_type_t stream = sourceDesc->stream();
5596 audio_attributes_t resultAttr;
5597 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5598 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005599 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5600 config.channel_mask =
5601 (audio_channel_mask_get_representation(sourceMask)
5602 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5603 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005604 config.format = sourceDesc->config().format;
5605 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5606 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5607 bool isRequestedDeviceForExclusiveUse = false;
5608 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005609 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005610 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005611 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5612 &stream, sourceDesc->uid(), &config, &flags,
5613 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005614 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005615 if (output == AUDIO_IO_HANDLE_NONE) {
5616 ALOGV("%s no output for device %s",
5617 __FUNCTION__, sinkDevice->toString().c_str());
5618 return INVALID_OPERATION;
5619 }
5620 outputDesc = mOutputs.valueFor(output);
5621 if (outputDesc->isDuplicated()) {
5622 ALOGE("%s output is duplicated", __func__);
5623 return INVALID_OPERATION;
5624 }
François Gaffie7e39df22022-04-26 12:48:49 +02005625 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5626 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005627 } else {
5628 // Same for "raw patches" aka created from createAudioPatch API
5629 SortedVector<audio_io_handle_t> outputs =
5630 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5631 // if the sink device is reachable via an opened output stream, request to
5632 // go via this output stream by adding a second source to the patch
5633 // description
5634 output = selectOutput(outputs);
5635 if (output == AUDIO_IO_HANDLE_NONE) {
5636 ALOGE("%s no output available for internal patch sink", __func__);
5637 return INVALID_OPERATION;
5638 }
5639 outputDesc = mOutputs.valueFor(output);
5640 if (outputDesc->isDuplicated()) {
5641 ALOGV("%s output for device %s is duplicated",
5642 __func__, sinkDevice->toString().c_str());
5643 return INVALID_OPERATION;
5644 }
François Gaffie7e39df22022-04-26 12:48:49 +02005645 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005646 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005647 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005648 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005649 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005650 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005651 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5652 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005653 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5654 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005655 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005656 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005657 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005658 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005659 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005660 return INVALID_OPERATION;
5661 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005662 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005663 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005664 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005665 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005666 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005667 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005668 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005669 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5670 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005671 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005672 }
Eric Laurent83b88082014-06-20 18:31:16 -07005673 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005674 }
5675 // TODO: check from routing capabilities in config file and other conflicting patches
5676
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005677installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005678 status_t status = installPatch(
5679 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005680 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005681 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005682 return INVALID_OPERATION;
5683 }
5684 } else {
5685 return BAD_VALUE;
5686 }
5687 } else {
5688 return BAD_VALUE;
5689 }
5690 return NO_ERROR;
5691}
5692
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005693status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005694{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005695 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005696 ssize_t index = mAudioPatches.indexOfKey(handle);
5697
5698 if (index < 0) {
5699 return BAD_VALUE;
5700 }
5701 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005702 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5703 __func__, mUidCached, patchDesc->getUid(), uid);
5704 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005705 return INVALID_OPERATION;
5706 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005707 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5708 for (size_t i = 0; i < mAudioSources.size(); i++) {
5709 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5710 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5711 portId = sourceDesc->portId();
5712 break;
5713 }
5714 }
5715 return portId != AUDIO_PORT_HANDLE_NONE ?
5716 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005717}
Eric Laurent6a94d692014-05-20 11:18:06 -07005718
François Gaffieafd4cea2019-11-18 15:50:22 +01005719status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005720 uint32_t delayMs,
5721 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005722{
5723 ALOGV("%s patch %d", __func__, handle);
5724 if (mAudioPatches.indexOfKey(handle) < 0) {
5725 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5726 return BAD_VALUE;
5727 }
5728 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005729 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005730 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005731 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005732 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005733 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005734 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005735 return BAD_VALUE;
5736 }
5737
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305738 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005739 getNewOutputDevices(outputDesc, true /*fromCache*/),
5740 true,
5741 0,
5742 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005743 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5744 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005745 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005746 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005747 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005748 return BAD_VALUE;
5749 }
5750 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005751 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005752 true,
5753 NULL);
5754 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005755 status_t status =
5756 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5757 ALOGV("%s patch panel returned %d patchHandle %d",
5758 __func__, status, patchDesc->getAfHandle());
5759 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005760 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005761 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005762 // SW or HW Bridge
5763 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5764 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005765 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005766 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5767 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5768 outputDesc = sourceDesc->swOutput().promote();
5769 }
5770 if (outputDesc == nullptr) {
5771 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5772 // releaseOutput has already called closeOutput in case of direct output
5773 return NO_ERROR;
5774 }
François Gaffie7e39df22022-04-26 12:48:49 +02005775 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005776 // While using a HwBridge, force reconsidering device only if not reusing an existing
5777 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005778 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005779 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5780 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5781 // Reconsider device only for cases:
5782 // 1 / Active Output
5783 // 2 / Inactive Output previously hosting HwBridge
5784 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5785 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5786 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305787 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005788 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5789 outputDesc->devices(),
5790 force,
5791 0,
5792 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005793 } else {
5794 return BAD_VALUE;
5795 }
5796 } else {
5797 return BAD_VALUE;
5798 }
5799 return NO_ERROR;
5800}
5801
5802status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5803 struct audio_patch *patches,
5804 unsigned int *generation)
5805{
François Gaffie53615e22015-03-19 09:24:12 +01005806 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005807 return BAD_VALUE;
5808 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005809 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005810 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005811}
5812
Eric Laurente1715a42014-05-20 11:30:42 -07005813status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005814{
Eric Laurente1715a42014-05-20 11:30:42 -07005815 ALOGV("setAudioPortConfig()");
5816
5817 if (config == NULL) {
5818 return BAD_VALUE;
5819 }
5820 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5821 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005822 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5823 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005824 }
5825
Eric Laurenta121f902014-06-03 13:32:54 -07005826 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005827 if (config->type == AUDIO_PORT_TYPE_MIX) {
5828 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005829 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005830 if (outputDesc == NULL) {
5831 return BAD_VALUE;
5832 }
Eric Laurent84c70242014-06-23 08:46:27 -07005833 ALOG_ASSERT(!outputDesc->isDuplicated(),
5834 "setAudioPortConfig() called on duplicated output %d",
5835 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005836 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005837 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005838 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005839 if (inputDesc == NULL) {
5840 return BAD_VALUE;
5841 }
Eric Laurenta121f902014-06-03 13:32:54 -07005842 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005843 } else {
5844 return BAD_VALUE;
5845 }
5846 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5847 sp<DeviceDescriptor> deviceDesc;
5848 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5849 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5850 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5851 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5852 } else {
5853 return BAD_VALUE;
5854 }
5855 if (deviceDesc == NULL) {
5856 return BAD_VALUE;
5857 }
Eric Laurenta121f902014-06-03 13:32:54 -07005858 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005859 } else {
5860 return BAD_VALUE;
5861 }
5862
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005863 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005864 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5865 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005866 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005867 audioPortConfig->toAudioPortConfig(&newConfig, config);
5868 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005869 }
Eric Laurenta121f902014-06-03 13:32:54 -07005870 if (status != NO_ERROR) {
5871 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005872 }
Eric Laurente1715a42014-05-20 11:30:42 -07005873
5874 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005875}
5876
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005877void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5878{
Eric Laurentd60560a2015-04-10 11:31:20 -07005879 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005880 clearAudioPatches(uid);
5881 clearSessionRoutes(uid);
5882}
5883
Eric Laurent6a94d692014-05-20 11:18:06 -07005884void AudioPolicyManager::clearAudioPatches(uid_t uid)
5885{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005886 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005887 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005888 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005889 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005890 }
5891 }
5892}
5893
François Gaffiec005e562018-11-06 15:04:49 +01005894void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005895{
François Gaffiec005e562018-11-06 15:04:49 +01005896 // Take the first attributes following the product strategy as it is used to retrieve the routed
5897 // device. All attributes wihin a strategy follows the same "routing strategy"
5898 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5899 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005900 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005901 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005902 for (size_t j = 0; j < mOutputs.size(); j++) {
5903 if (mOutputs.keyAt(j) == ouptutToSkip) {
5904 continue;
5905 }
5906 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005907 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005908 continue;
5909 }
5910 // If the default device for this strategy is on another output mix,
5911 // invalidate all tracks in this strategy to force re connection.
5912 // Otherwise select new device on the output mix.
5913 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005914 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005915 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005916 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005917 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005918 // If the device is using preferred mixer attributes, the output need to reopen
5919 // with default configuration when the new selected devices are different from
5920 // current routing devices.
5921 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5922 continue;
5923 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305924 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005925 }
5926 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005927 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005928}
5929
5930void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5931{
5932 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005933 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005934 for (size_t i = 0; i < mOutputs.size(); i++) {
5935 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005936 for (const auto& client : outputDesc->getClientIterable()) {
5937 if (client->hasPreferredDevice() && client->uid() == uid) {
5938 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005939 auto clientStrategy = client->strategy();
5940 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5941 end(affectedStrategies)) {
5942 continue;
5943 }
5944 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005945 }
5946 }
5947 }
5948 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005949 for (const auto& strategy : affectedStrategies) {
5950 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005951 }
5952
5953 // remove input routes associated with this uid
5954 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005955 for (size_t i = 0; i < mInputs.size(); i++) {
5956 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005957 for (const auto& client : inputDesc->getClientIterable()) {
5958 if (client->hasPreferredDevice() && client->uid() == uid) {
5959 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5960 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005961 }
5962 }
5963 }
5964 // reroute inputs if necessary
5965 SortedVector<audio_io_handle_t> inputsToClose;
5966 for (size_t i = 0; i < mInputs.size(); i++) {
5967 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005968 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005969 inputsToClose.add(inputDesc->mIoHandle);
5970 }
5971 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005972 for (const auto& input : inputsToClose) {
5973 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005974 }
5975}
5976
Eric Laurentd60560a2015-04-10 11:31:20 -07005977void AudioPolicyManager::clearAudioSources(uid_t uid)
5978{
5979 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005980 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5981 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005982 stopAudioSource(mAudioSources.keyAt(i));
5983 }
5984 }
5985}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005986
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005987status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5988 audio_io_handle_t *ioHandle,
5989 audio_devices_t *device)
5990{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005991 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5992 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005993 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005994 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5995 if (deviceDesc == nullptr) {
5996 return INVALID_OPERATION;
5997 }
5998 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005999
François Gaffiedf372692015-03-19 10:43:27 +01006000 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006001}
6002
Eric Laurentd60560a2015-04-10 11:31:20 -07006003status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006004 const audio_attributes_t *attributes,
6005 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00006006 uid_t uid) {
6007 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00006008 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00006009}
6010
6011status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
6012 const audio_attributes_t *attributes,
6013 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00006014 uid_t uid, bool internal, bool isCallRx,
6015 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07006016{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006017 ALOGV("%s", __FUNCTION__);
6018 *portId = AUDIO_PORT_HANDLE_NONE;
6019
6020 if (source == NULL || attributes == NULL || portId == NULL) {
6021 ALOGW("%s invalid argument: source %p attributes %p handle %p",
6022 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006023 return BAD_VALUE;
6024 }
6025
Eric Laurentd60560a2015-04-10 11:31:20 -07006026 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6027 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006028 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6029 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006030 return INVALID_OPERATION;
6031 }
6032
François Gaffie11d30102018-11-02 16:09:09 +01006033 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006034 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006035 String8(source->ext.device.address),
6036 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006037 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006038 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006039 return BAD_VALUE;
6040 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006041
jiabin4ef93452019-09-10 14:29:54 -07006042 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006043
François Gaffieaaac0fd2018-11-22 17:56:39 +01006044 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006045 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006046 mEngine->getStreamTypeForAttributes(*attributes),
6047 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006048 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006049
David Lif85c5e32024-07-01 13:14:10 +00006050 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006051 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006052 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006053 }
6054 return status;
6055}
6056
David Lif85c5e32024-07-01 13:14:10 +00006057status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6058 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006059{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006060 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006061
6062 // make sure we only have one patch per source.
6063 disconnectAudioSource(sourceDesc);
6064
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006065 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006066 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6067 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6068 sourceDesc->srcDevice()->type(),
6069 String8(sourceDesc->srcDevice()->address().c_str()),
6070 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006071 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006072 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006073 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006074 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006075 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6076 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6077 return INVALID_OPERATION;
6078 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006079 PatchBuilder patchBuilder;
6080 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6081 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006082
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006083 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006084 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006085}
6086
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006087status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006088{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006089 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6090 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006091 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006092 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006093 return BAD_VALUE;
6094 }
6095 status_t status = disconnectAudioSource(sourceDesc);
6096
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006097 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006098 return status;
6099}
6100
Andy Hung2ddee192015-12-18 17:34:44 -08006101status_t AudioPolicyManager::setMasterMono(bool mono)
6102{
6103 if (mMasterMono == mono) {
6104 return NO_ERROR;
6105 }
6106 mMasterMono = mono;
6107 // if enabling mono we close all offloaded devices, which will invalidate the
6108 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6109 // for recreating the new AudioTrack as non-offloaded PCM.
6110 //
6111 // If disabling mono, we leave all tracks as is: we don't know which clients
6112 // and tracks are able to be recreated as offloaded. The next "song" should
6113 // play back offloaded.
6114 if (mMasterMono) {
6115 Vector<audio_io_handle_t> offloaded;
6116 for (size_t i = 0; i < mOutputs.size(); ++i) {
6117 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6118 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6119 offloaded.push(desc->mIoHandle);
6120 }
6121 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006122 for (const auto& handle : offloaded) {
6123 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006124 }
6125 }
6126 // update master mono for all remaining outputs
6127 for (size_t i = 0; i < mOutputs.size(); ++i) {
6128 updateMono(mOutputs.keyAt(i));
6129 }
6130 return NO_ERROR;
6131}
6132
6133status_t AudioPolicyManager::getMasterMono(bool *mono)
6134{
6135 *mono = mMasterMono;
6136 return NO_ERROR;
6137}
6138
Eric Laurentac9cef52017-06-09 15:46:26 -07006139float AudioPolicyManager::getStreamVolumeDB(
6140 audio_stream_type_t stream, int index, audio_devices_t device)
6141{
Vlad Popa9d482762024-06-21 16:40:23 -07006142 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6143 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006144}
6145
jiabin81772902018-04-02 17:52:27 -07006146status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6147 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006148 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006149{
Kriti Dang6537def2021-03-02 13:46:59 +01006150 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6151 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006152 return BAD_VALUE;
6153 }
Kriti Dang6537def2021-03-02 13:46:59 +01006154 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6155 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006156
6157 size_t formatsWritten = 0;
6158 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006159
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006160 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006161 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6162 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006163 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006164 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006165 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006166 bool formatEnabled = true;
6167 switch (forceUse) {
6168 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006169 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006170 break;
6171 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6172 formatEnabled = false;
6173 break;
6174 default: // AUTO or ALWAYS => true
6175 break;
jiabin81772902018-04-02 17:52:27 -07006176 }
6177 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6178 }
jiabin81772902018-04-02 17:52:27 -07006179 }
6180 return NO_ERROR;
6181}
6182
Kriti Dang6537def2021-03-02 13:46:59 +01006183status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6184 audio_format_t *surroundFormats) {
6185 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6186 return BAD_VALUE;
6187 }
6188 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6189 __func__, *numSurroundFormats, surroundFormats);
6190
6191 size_t formatsWritten = 0;
6192 size_t formatsMax = *numSurroundFormats;
6193 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6194
6195 // Return formats from all device profiles that have already been resolved by
6196 // checkOutputsForDevice().
6197 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6198 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6199 audio_devices_t deviceType = device->type();
6200 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6201 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006202 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6203 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006204 continue;
6205 }
6206 // Formats reported by sink devices
6207 std::unordered_set<audio_format_t> formatset;
6208 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6209 formatset.insert(it->second.begin(), it->second.end());
6210 }
6211
6212 // Formats hard-coded in the in policy configuration file (if any).
6213 FormatVector encodedFormats = device->encodedFormats();
6214 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6215 // Filter the formats which are supported by the vendor hardware.
6216 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006217 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006218 formats.insert(*it);
6219 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006220 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006221 if (pair.second.count(*it) != 0) {
6222 formats.insert(pair.first);
6223 break;
6224 }
6225 }
6226 }
6227 }
6228 }
6229 *numSurroundFormats = formats.size();
6230 for (const auto& format: formats) {
6231 if (formatsWritten < formatsMax) {
6232 surroundFormats[formatsWritten++] = format;
6233 }
6234 }
6235 return NO_ERROR;
6236}
6237
jiabin81772902018-04-02 17:52:27 -07006238status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6239{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006240 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006241 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6242 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006243 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006244 return BAD_VALUE;
6245 }
6246
Mikhail Naganov100f0122018-11-29 11:22:16 -08006247 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6248 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006249 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006250 return INVALID_OPERATION;
6251 }
6252
Mikhail Naganov100f0122018-11-29 11:22:16 -08006253 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006254 return NO_ERROR;
6255 }
6256
Mikhail Naganov100f0122018-11-29 11:22:16 -08006257 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006258 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006259 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006260 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006261 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006262 }
6263 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006264 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006265 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006266 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006267 }
6268 }
6269
6270 sp<SwAudioOutputDescriptor> outputDesc;
6271 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006272 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6273 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006274 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6275 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006276 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006277 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006278 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006279 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6280 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006281 name.c_str(),
6282 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006283 if (status != NO_ERROR) {
6284 continue;
6285 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006286 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006287 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6288 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006289 name.c_str(),
6290 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006291 profileUpdated |= (status == NO_ERROR);
6292 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006293 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006294 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006295 AUDIO_DEVICE_IN_HDMI);
6296 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6297 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006298 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006299 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006300 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6301 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6302 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006303 name.c_str(),
6304 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006305 if (status != NO_ERROR) {
6306 continue;
6307 }
6308 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6309 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6310 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006311 name.c_str(),
6312 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006313 profileUpdated |= (status == NO_ERROR);
6314 }
6315
jiabin81772902018-04-02 17:52:27 -07006316 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006317 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006318 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006319 }
6320
6321 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6322}
6323
Eric Laurent5ada82e2019-08-29 17:53:54 -07006324void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006325{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006326 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006327 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006328 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006329 }
6330}
6331
jiabin6012f912018-11-02 17:06:30 -07006332bool AudioPolicyManager::isHapticPlaybackSupported()
6333{
6334 for (const auto& hwModule : mHwModules) {
6335 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6336 for (const auto &outProfile : outputProfiles) {
6337 struct audio_port audioPort;
6338 outProfile->toAudioPort(&audioPort);
6339 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6340 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6341 return true;
6342 }
6343 }
6344 }
6345 }
6346 return false;
6347}
6348
Carter Hsu325a8eb2022-01-19 19:56:51 +08006349bool AudioPolicyManager::isUltrasoundSupported()
6350{
6351 bool hasUltrasoundOutput = false;
6352 bool hasUltrasoundInput = false;
6353 for (const auto& hwModule : mHwModules) {
6354 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6355 if (!hasUltrasoundOutput) {
6356 for (const auto &outProfile : outputProfiles) {
6357 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6358 hasUltrasoundOutput = true;
6359 break;
6360 }
6361 }
6362 }
6363
6364 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6365 if (!hasUltrasoundInput) {
6366 for (const auto &inputProfile : inputProfiles) {
6367 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6368 hasUltrasoundInput = true;
6369 break;
6370 }
6371 }
6372 }
6373
6374 if (hasUltrasoundOutput && hasUltrasoundInput)
6375 return true;
6376 }
6377 return false;
6378}
6379
Atneya Nair698f5ef2022-12-15 16:15:09 -08006380bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6381{
6382 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6383 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6384 for (const auto& hwModule : mHwModules) {
6385 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6386 for (const auto &inputProfile : inputProfiles) {
6387 if ((inputProfile->getFlags() & mask) == mask) {
6388 return true;
6389 }
6390 }
6391 }
6392 return false;
6393}
6394
Eric Laurent8340e672019-11-06 11:01:08 -08006395bool AudioPolicyManager::isCallScreenModeSupported()
6396{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006397 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006398}
6399
6400
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006401status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006402{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006403 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006404 if (!sourceDesc->isConnected()) {
6405 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6406 return NO_ERROR;
6407 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006408 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6409 if (swOutput != 0) {
6410 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006411 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006412 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006413 }
jiabinbce0c1d2020-10-05 11:20:18 -07006414 if (releaseOutput(sourceDesc->portId())) {
6415 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6416 // no need to release audio patch here but just return NO_ERROR.
6417 return NO_ERROR;
6418 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006419 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006420 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006421 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006422 // close Hwoutput and remove from mHwOutputs
6423 } else {
6424 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6425 }
6426 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006427 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006428 sourceDesc->disconnect();
6429 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006430}
6431
François Gaffiec005e562018-11-06 15:04:49 +01006432sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6433 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006434{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006435 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006436 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006437 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006438 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006439 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6440 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006441 source = sourceDesc;
6442 break;
6443 }
6444 }
6445 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006446}
6447
Eric Laurentb4f42a92022-01-17 17:37:31 +01006448bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006449 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006450 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006451{
6452 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6453 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006454 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006455 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006456 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6457 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6458 return false;
6459 }
6460 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6461 return false;
6462 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006463 }
6464
Eric Laurentd332bc82023-08-04 11:45:23 +02006465 // The caller can have the audio config criteria ignored by either passing a null ptr or
6466 // the AUDIO_CONFIG_INITIALIZER value.
6467 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006468 // some positional channel masks and PCM format and for stereo if low latency performance
6469 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006470
6471 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006472 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006473 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6474 ? audio_channel_mask_contains_stereo(config->channel_mask)
6475 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006476 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006477 return false;
6478 }
6479 if (!audio_is_linear_pcm(config->format)) {
6480 return false;
6481 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006482 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6483 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6484 return false;
6485 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006486 }
6487
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006488 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006489 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006490 if (profile == nullptr) {
6491 return false;
6492 }
6493
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006494 return true;
6495}
6496
Shunkai Yao4c3af932024-04-26 04:12:21 +00006497// The Spatializer output is compatible with Haptic use cases if:
6498// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6499// with client if client haptic channel bits were set, or
6500// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6501// including the haptic bits or creating the HapticGenerator effect for same session.
6502bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6503 const audio_config_t* config, audio_session_t sessionId) const {
6504 const auto clientHapticChannel =
6505 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6506 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6507 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6508
6509 if (threadOutputHapticChannel) {
6510 // check format and sampleRate match if client haptic channel mask exist
6511 if (clientHapticChannel) {
6512 return mSpatializerOutput->getFormat() == config->format &&
6513 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6514 }
6515 return true;
6516 } else {
6517 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6518 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6519 // HapticGenerator effect for this session) are not supported.
6520 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006521 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006522 }
6523}
6524
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006525void AudioPolicyManager::checkVirtualizerClientRoutes() {
6526 std::set<audio_stream_type_t> streamsToInvalidate;
6527 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006528 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6529 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006530 audio_attributes_t attr = client->attributes();
6531 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6532 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6533 audio_config_base_t clientConfig = client->config();
6534 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006535 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006536 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006537 streamsToInvalidate.insert(client->stream());
6538 }
6539 }
6540 }
6541
jiabinc44b3462022-12-08 12:52:31 -08006542 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006543}
6544
Eric Laurente191d1b2022-04-15 11:59:25 +02006545
6546bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6547 const sp<SwAudioOutputDescriptor>& outputDesc) {
6548 if (outputDesc->isDuplicated()) {
6549 return false;
6550 }
6551 DeviceVector devices = outputDesc->supportedDevices();
6552 for (size_t i = 0; i < mOutputs.size(); i++) {
6553 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6554 if (desc == outputDesc || desc->isDuplicated()) {
6555 continue;
6556 }
6557 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6558 if (!sharedDevices.isEmpty()
6559 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6560 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6561 return false;
6562 }
6563 }
6564 return true;
6565}
6566
6567
Eric Laurentfa0f6742021-08-17 18:39:44 +02006568status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006569 const audio_attributes_t *attr,
6570 audio_io_handle_t *output) {
6571 *output = AUDIO_IO_HANDLE_NONE;
6572
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006573 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6574 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6575 audio_config_t *configPtr = nullptr;
6576 audio_config_t config;
6577 if (mixerConfig != nullptr) {
6578 config = audio_config_initializer(mixerConfig);
6579 configPtr = &config;
6580 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006581 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006582 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006583 return BAD_VALUE;
6584 }
6585
6586 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006587 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006588 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006589 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006590 return BAD_VALUE;
6591 }
6592
Eric Laurente191d1b2022-04-15 11:59:25 +02006593 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006594 for (size_t i = 0; i < mOutputs.size(); i++) {
6595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006596 if (!desc->isDuplicated()
6597 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6598 spatializerOutputs.push_back(desc);
6599 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006600 }
6601 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006602 mSpatializerOutput.clear();
6603 bool outputsChanged = false;
6604 for (const auto& desc : spatializerOutputs) {
6605 if (desc->mProfile == profile
6606 && (configPtr == nullptr
6607 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6608 mSpatializerOutput = desc;
6609 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6610 } else {
6611 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6612 " and devices %s", __func__, desc->mIoHandle,
6613 configPtr != nullptr ? configPtr->channel_mask : 0,
6614 devices.toString().c_str());
6615 closeOutput(desc->mIoHandle);
6616 outputsChanged = true;
6617 }
Eric Laurent39095982021-08-24 18:29:27 +02006618 }
6619
Eric Laurente191d1b2022-04-15 11:59:25 +02006620 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006621 sp<SwAudioOutputDescriptor> desc =
6622 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006623 if (desc != nullptr) {
6624 mSpatializerOutput = desc;
6625 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006626 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006627 }
6628
6629 checkVirtualizerClientRoutes();
6630
Eric Laurente191d1b2022-04-15 11:59:25 +02006631 if (outputsChanged) {
6632 mPreviousOutputs = mOutputs;
6633 mpClientInterface->onAudioPortListUpdate();
6634 }
6635
6636 if (mSpatializerOutput == nullptr) {
6637 ALOGV("%s could not open spatializer output with requested config", __func__);
6638 return BAD_VALUE;
6639 }
Eric Laurent39095982021-08-24 18:29:27 +02006640 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006641 ALOGV("%s returning new spatializer output %d", __func__, *output);
6642 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006643}
6644
Eric Laurentfa0f6742021-08-17 18:39:44 +02006645status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6646 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006647 return INVALID_OPERATION;
6648 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006649 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006650 return BAD_VALUE;
6651 }
Eric Laurent39095982021-08-24 18:29:27 +02006652
Eric Laurente191d1b2022-04-15 11:59:25 +02006653 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6654 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6655 closeOutput(mSpatializerOutput->mIoHandle);
6656 //from now on mSpatializerOutput is null
6657 checkVirtualizerClientRoutes();
6658 }
Eric Laurent39095982021-08-24 18:29:27 +02006659
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006660 return NO_ERROR;
6661}
6662
Eric Laurente552edb2014-03-10 17:42:56 -07006663// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006664// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006665// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006666uint32_t AudioPolicyManager::nextAudioPortGeneration()
6667{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006668 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006669}
6670
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006671AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006672 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006673 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006674 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006675 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006676 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006677 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006678 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006679 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006680 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006681 mAudioPortGeneration(1),
6682 mBeaconMuteRefCount(0),
6683 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006684 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006685 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006686 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006687 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006688{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006689}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006690
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006691status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006692 if (mEngine == nullptr) {
6693 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006694 }
6695 mEngine->setObserver(this);
6696 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006697 if (status != NO_ERROR) {
6698 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6699 return status;
6700 }
François Gaffie2110e042015-03-24 08:41:51 +01006701
jiabin29230182023-04-04 21:02:36 +00006702 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6703 // at the end of this function.
6704 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006705 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6706 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6707
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006708 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006709 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006710 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006711
Eric Laurent3a4311c2014-03-17 12:00:47 -07006712 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006713 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6714 defaultOutputDevice == nullptr ||
6715 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6716 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6717 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006718 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006719 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006720 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006721
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006722 // Silence ALOGV statements
6723 property_set("log.tag." LOG_TAG, "D");
6724
Eric Laurente552edb2014-03-10 17:42:56 -07006725 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006726 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006727}
6728
Eric Laurente0720872014-03-11 09:30:41 -07006729AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006730{
Eric Laurente552edb2014-03-10 17:42:56 -07006731 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006732 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006733 }
6734 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006735 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006736 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006737 mAvailableOutputDevices.clear();
6738 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006739 mOutputs.clear();
6740 mInputs.clear();
6741 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006742 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006743 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006744}
6745
Eric Laurente0720872014-03-11 09:30:41 -07006746status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006747{
Eric Laurent87ffa392015-05-22 10:32:38 -07006748 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006749}
6750
Eric Laurente552edb2014-03-10 17:42:56 -07006751// ---
6752
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006753void AudioPolicyManager::onNewAudioModulesAvailable()
6754{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006755 DeviceVector newDevices;
6756 onNewAudioModulesAvailableInt(&newDevices);
6757 if (!newDevices.empty()) {
6758 nextAudioPortGeneration();
6759 mpClientInterface->onAudioPortListUpdate();
6760 }
6761}
6762
6763void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6764{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006765 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006766 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6767 continue;
6768 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006769 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006770 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6771 handle != AUDIO_MODULE_HANDLE_NONE) {
6772 hwModule->setHandle(handle);
6773 } else {
6774 ALOGW("could not load HW module %s", hwModule->getName());
6775 continue;
6776 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006777 }
6778 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006779 // open all output streams needed to access attached devices.
6780 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006781 // This also validates mAvailableOutputDevices list
6782 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6783 if (!outProfile->canOpenNewIo()) {
6784 ALOGE("Invalid Output profile max open count %u for profile %s",
6785 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6786 continue;
6787 }
6788 if (!outProfile->hasSupportedDevices()) {
6789 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6790 continue;
6791 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006792 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6793 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006794 mTtsOutputAvailable = true;
6795 }
6796
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006797 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006798 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006799 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006800 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6801 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006802 } else {
6803 // choose first device present in profile's SupportedDevices also part of
6804 // mAvailableOutputDevices.
6805 if (availProfileDevices.isEmpty()) {
6806 continue;
6807 }
6808 supportedDevice = availProfileDevices.itemAt(0);
6809 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006810 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006811 continue;
6812 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306813
6814 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6815 && availProfileDevices.areAllDevicesAttached()) {
6816 ALOGV("%s skip opening output for mmap profile %s", __func__,
6817 outProfile->getTagName().c_str());
6818 continue;
6819 }
6820
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006821 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6822 mpClientInterface);
6823 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006824 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006825 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006826 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6827 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006828 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006829 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006830 if (status != NO_ERROR) {
6831 ALOGW("Cannot open output stream for devices %s on hw module %s",
6832 supportedDevice->toString().c_str(), hwModule->getName());
6833 continue;
6834 }
6835 for (const auto &device : availProfileDevices) {
6836 // give a valid ID to an attached device once confirmed it is reachable
6837 if (!device->isAttached()) {
6838 device->attach(hwModule);
6839 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006840 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006841 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006842 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6843 }
6844 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006845 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006846 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6847 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006848 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006849 }
Eric Laurent39095982021-08-24 18:29:27 +02006850 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006851 outputDesc->close();
6852 } else {
6853 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306854 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006855 DeviceVector(supportedDevice),
6856 true,
6857 0,
6858 NULL);
6859 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006860 }
6861 // open input streams needed to access attached devices to validate
6862 // mAvailableInputDevices list
6863 for (const auto& inProfile : hwModule->getInputProfiles()) {
6864 if (!inProfile->canOpenNewIo()) {
6865 ALOGE("Invalid Input profile max open count %u for profile %s",
6866 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6867 continue;
6868 }
6869 if (!inProfile->hasSupportedDevices()) {
6870 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6871 continue;
6872 }
6873 // chose first device present in profile's SupportedDevices also part of
6874 // available input devices
6875 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006876 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006877 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006878 ALOGV("%s: Input device list is empty! for profile %s",
6879 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006880 continue;
6881 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306882
6883 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6884 && availProfileDevices.areAllDevicesAttached()) {
6885 ALOGV("%s skip opening input for mmap profile %s", __func__,
6886 inProfile->getTagName().c_str());
6887 continue;
6888 }
6889
Eric Laurentc71b11b2024-06-03 12:54:53 +00006890 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6891 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006892
6893 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6894 status_t status = inputDesc->open(nullptr,
6895 availProfileDevices.itemAt(0),
6896 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306897 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006898 &input);
6899 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306900 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6901 __func__, availProfileDevices.toString().c_str(),
6902 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006903 continue;
6904 }
6905 for (const auto &device : availProfileDevices) {
6906 // give a valid ID to an attached device once confirmed it is reachable
6907 if (!device->isAttached()) {
6908 device->attach(hwModule);
6909 device->importAudioPortAndPickAudioProfile(inProfile, true);
6910 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006911 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006912 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6913 }
6914 }
6915 inputDesc->close();
6916 }
6917 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006918
6919 // Check if spatializer outputs can be closed until used.
6920 // mOutputs vector never contains duplicated outputs at this point.
6921 std::vector<audio_io_handle_t> outputsClosed;
6922 for (size_t i = 0; i < mOutputs.size(); i++) {
6923 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6924 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6925 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6926 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006927 nextAudioPortGeneration();
6928 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6929 if (index >= 0) {
6930 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6931 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6932 patchDesc->getAfHandle(), 0);
6933 mAudioPatches.removeItemsAt(index);
6934 mpClientInterface->onAudioPatchListUpdate();
6935 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006936 desc->close();
6937 }
6938 }
6939 for (auto output : outputsClosed) {
6940 removeOutput(output);
6941 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006942}
6943
Eric Laurent98e38192018-02-15 18:31:53 -08006944void AudioPolicyManager::addOutput(audio_io_handle_t output,
6945 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006946{
Eric Laurent1c333e22014-05-20 10:48:17 -07006947 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006948 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006949 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006950 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006951 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006952}
6953
François Gaffie53615e22015-03-19 09:24:12 +01006954void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6955{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006956 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6957 ALOGV("%s: removing primary output", __func__);
6958 mPrimaryOutput = nullptr;
6959 }
François Gaffie53615e22015-03-19 09:24:12 +01006960 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006961 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006962}
6963
Eric Laurent98e38192018-02-15 18:31:53 -08006964void AudioPolicyManager::addInput(audio_io_handle_t input,
6965 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006966{
Eric Laurent1c333e22014-05-20 10:48:17 -07006967 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006968 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006969}
Eric Laurente552edb2014-03-10 17:42:56 -07006970
François Gaffie11d30102018-11-02 16:09:09 +01006971status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006972 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006973 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006974{
François Gaffie11d30102018-11-02 16:09:09 +01006975 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006976 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006977 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006978
François Gaffie11d30102018-11-02 16:09:09 +01006979 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006980 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006981 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006982 }
Eric Laurente552edb2014-03-10 17:42:56 -07006983
Eric Laurent3b73df72014-03-11 09:06:29 -07006984 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006985 // first call getAudioPort to get the supported attributes from the HAL
6986 struct audio_port_v7 port = {};
6987 device->toAudioPort(&port);
6988 status_t status = mpClientInterface->getAudioPort(&port);
6989 if (status == NO_ERROR) {
6990 device->importAudioPort(port);
6991 }
6992
6993 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006994 for (size_t i = 0; i < mOutputs.size(); i++) {
6995 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006996 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006997 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006998 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6999 mOutputs.keyAt(i), device->toString().c_str());
7000 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007001 }
7002 }
7003 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007004 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007005 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007006 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7007 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01007008 if (profile->supportsDevice(device)) {
7009 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307010 ALOGV("%s(): adding profile %s from module %s",
7011 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07007012 }
7013 }
7014 }
7015
Eric Laurent7b279bb2015-12-14 10:18:23 -08007016 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007017
Eric Laurente552edb2014-03-10 17:42:56 -07007018 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007019 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007020 return BAD_VALUE;
7021 }
7022
7023 // open outputs for matching profiles if needed. Direct outputs are also opened to
7024 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7025 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007026 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007027
7028 // nothing to do if one output is already opened for this profile
7029 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007030 for (j = 0; j < outputs.size(); j++) {
7031 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007032 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007033 // matching profile: save the sample rates, format and channel masks supported
7034 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007035 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007036 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007037 }
Eric Laurente552edb2014-03-10 17:42:56 -07007038 break;
7039 }
7040 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007041 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007042 continue;
7043 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307044 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7045 ALOGV("%s skip opening output for mmap profile %s",
7046 __func__, profile->getTagName().c_str());
7047 continue;
7048 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007049 if (!profile->canOpenNewIo()) {
7050 ALOGW("Max Output number %u already opened for this profile %s",
7051 profile->maxOpenCount, profile->getTagName().c_str());
7052 continue;
7053 }
7054
Eric Laurent83efe1c2017-07-09 16:51:08 -07007055 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007056 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007057 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7058 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007059 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007060 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007061 profiles.removeAt(profile_index);
7062 profile_index--;
7063 } else {
7064 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007065 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007066 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007067 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7068 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007069 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007070 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007071
François Gaffie11d30102018-11-02 16:09:09 +01007072 if (device_distinguishes_on_address(deviceType)) {
7073 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7074 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307075 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7076 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007077 }
Eric Laurente552edb2014-03-10 17:42:56 -07007078 ALOGV("checkOutputsForDevice(): adding output %d", output);
7079 }
7080 }
7081
7082 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007083 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007084 return BAD_VALUE;
7085 }
Eric Laurentd4692962014-05-05 18:13:44 -07007086 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007087 // check if one opened output is not needed any more after disconnecting one device
7088 for (size_t i = 0; i < mOutputs.size(); i++) {
7089 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007090 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007091 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007092 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007093 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007094 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007095 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007096 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7097 mOutputs.keyAt(i));
7098 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007099 }
Eric Laurente552edb2014-03-10 17:42:56 -07007100 }
7101 }
Eric Laurentd4692962014-05-05 18:13:44 -07007102 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007103 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007104 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7105 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007106 if (!profile->supportsDevice(device)) {
7107 continue;
7108 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307109 ALOGV("%s(): clearing direct output profile %s on module %s",
7110 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007111 profile->clearAudioProfiles();
7112 if (!profile->hasDynamicAudioProfile()) {
7113 continue;
7114 }
7115 // When a device is disconnected, if there is an IOProfile that contains dynamic
7116 // profiles and supports the disconnected device, call getAudioPort to repopulate
7117 // the capabilities of the devices that is supported by the IOProfile.
7118 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7119 if (supportedDevice == device ||
7120 !mAvailableOutputDevices.contains(supportedDevice)) {
7121 continue;
7122 }
7123 struct audio_port_v7 port;
7124 supportedDevice->toAudioPort(&port);
7125 status_t status = mpClientInterface->getAudioPort(&port);
7126 if (status == NO_ERROR) {
7127 supportedDevice->importAudioPort(port);
7128 }
Eric Laurente552edb2014-03-10 17:42:56 -07007129 }
7130 }
7131 }
7132 }
7133 return NO_ERROR;
7134}
7135
François Gaffie11d30102018-11-02 16:09:09 +01007136status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007137 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007138{
François Gaffie11d30102018-11-02 16:09:09 +01007139 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007140 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007141 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007142 }
7143
Eric Laurentd4692962014-05-05 18:13:44 -07007144 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007145 sp<AudioInputDescriptor> desc;
7146
jiabinbf5f4262023-04-12 21:48:34 +00007147 // first call getAudioPort to get the supported attributes from the HAL
7148 struct audio_port_v7 port = {};
7149 device->toAudioPort(&port);
7150 status_t status = mpClientInterface->getAudioPort(&port);
7151 if (status == NO_ERROR) {
7152 device->importAudioPort(port);
7153 }
7154
Eric Laurent0dd51852019-04-19 18:18:58 -07007155 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007156 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007157 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007158 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007159 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007160 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007161 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007162
François Gaffie11d30102018-11-02 16:09:09 +01007163 if (profile->supportsDevice(device)) {
7164 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307165 ALOGV("%s : adding profile %s from module %s", __func__,
7166 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007167 }
7168 }
7169 }
7170
Eric Laurent0dd51852019-04-19 18:18:58 -07007171 if (profiles.isEmpty()) {
7172 ALOGW("%s: No input profile available for device %s",
7173 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007174 return BAD_VALUE;
7175 }
7176
7177 // open inputs for matching profiles if needed. Direct inputs are also opened to
7178 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7179 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7180
Eric Laurent1c333e22014-05-20 10:48:17 -07007181 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007182
Eric Laurentd4692962014-05-05 18:13:44 -07007183 // nothing to do if one input is already opened for this profile
7184 size_t input_index;
7185 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7186 desc = mInputs.valueAt(input_index);
7187 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007188 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007189 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007190 }
Eric Laurentd4692962014-05-05 18:13:44 -07007191 break;
7192 }
7193 }
7194 if (input_index != mInputs.size()) {
7195 continue;
7196 }
7197
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307198 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7199 ALOGV("%s skip opening input for mmap profile %s",
7200 __func__, profile->getTagName().c_str());
7201 continue;
7202 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007203 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307204 ALOGW("%s Max Input number %u already opened for this profile %s",
7205 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007206 continue;
7207 }
7208
Eric Laurentc71b11b2024-06-03 12:54:53 +00007209 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007210 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307211 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307212 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7213 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007214
Eric Laurentcf2c0212014-07-25 16:20:43 -07007215 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007216 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007217 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007218 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007219 mpClientInterface->setParameters(input, String8(param));
7220 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007221 }
jiabin12537fc2023-10-12 17:56:08 +00007222 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007223 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307224 ALOGW("%s direct input missing param for profile %s", __func__,
7225 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007226 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007227 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007228 }
7229
Eric Laurent0dd51852019-04-19 18:18:58 -07007230 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007231 addInput(input, desc);
7232 }
7233 } // endif input != 0
7234
Eric Laurentcf2c0212014-07-25 16:20:43 -07007235 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307236 ALOGW("%s could not open input for device %s on profile %s", __func__,
7237 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007238 profiles.removeAt(profile_index);
7239 profile_index--;
7240 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007241 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007242 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007243 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307244 ALOGV("%s: adding input %d for profile %s", __func__,
7245 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007246
7247 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307248 ALOGV("%s: closing input %d for profile %s", __func__,
7249 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007250 closeInput(input);
7251 }
Eric Laurentd4692962014-05-05 18:13:44 -07007252 }
7253 } // end scan profiles
7254
7255 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007256 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007257 return BAD_VALUE;
7258 }
7259 } else {
7260 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007261 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007262 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007263 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007264 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007265 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007266 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007267 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307268 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7269 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007270 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007271 }
7272 }
7273 }
7274 } // end disconnect
7275
7276 return NO_ERROR;
7277}
7278
7279
Eric Laurente0720872014-03-11 09:30:41 -07007280void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007281{
7282 ALOGV("closeOutput(%d)", output);
7283
François Gaffie1c878552018-11-22 16:53:21 +01007284 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7285 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007286 ALOGW("closeOutput() unknown output %d", output);
7287 return;
7288 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007289 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007290 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007291
Eric Laurente552edb2014-03-10 17:42:56 -07007292 // look for duplicated outputs connected to the output being removed.
7293 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007294 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7295 if (dupOutput->isDuplicated() &&
7296 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7297 sp<SwAudioOutputDescriptor> remainingOutput =
7298 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007299 // As all active tracks on duplicated output will be deleted,
7300 // and as they were also referenced on the other output, the reference
7301 // count for their stream type must be adjusted accordingly on
7302 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007303 const bool wasActive = remainingOutput->isActive();
7304 // Note: no-op on the closing output where all clients has already been set inactive
7305 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007306 // stop() will be a no op if the output is still active but is needed in case all
7307 // active streams refcounts where cleared above
7308 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007309 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007310 }
Eric Laurente552edb2014-03-10 17:42:56 -07007311 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7312 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7313
7314 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007315 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007316 }
7317 }
7318
Eric Laurent05b90f82014-08-27 15:32:29 -07007319 nextAudioPortGeneration();
7320
François Gaffie1c878552018-11-22 16:53:21 +01007321 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007322 if (index >= 0) {
7323 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007324 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7325 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007326 mAudioPatches.removeItemsAt(index);
7327 mpClientInterface->onAudioPatchListUpdate();
7328 }
7329
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007330 if (closingOutputWasActive) {
7331 closingOutput->stop();
7332 }
François Gaffie1c878552018-11-22 16:53:21 +01007333 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007334 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007335 for (const auto device : closingOutput->devices()) {
7336 device->setPreferredConfig(nullptr);
7337 }
7338 }
Eric Laurente552edb2014-03-10 17:42:56 -07007339
François Gaffie53615e22015-03-19 09:24:12 +01007340 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007341 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007342 if (closingOutput == mSpatializerOutput) {
7343 mSpatializerOutput.clear();
7344 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007345
7346 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7347 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007348 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007349 bool directOutputOpen = false;
7350 for (size_t i = 0; i < mOutputs.size(); i++) {
7351 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7352 directOutputOpen = true;
7353 break;
7354 }
7355 }
7356 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007357 ALOGV("no direct outputs open, reset MSD patches");
7358 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7359 // how output devices for patching are resolved. Avoid by caching and reusing the
7360 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7361 // devices to patch to. This may be complicated by the fact that devices may become
7362 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007363 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007364 }
7365 }
jiabin220eea12024-05-17 17:55:20 +00007366
7367 if (closingOutput->mPreferredAttrInfo != nullptr) {
7368 closingOutput->mPreferredAttrInfo->resetActiveClient();
7369 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007370}
7371
7372void AudioPolicyManager::closeInput(audio_io_handle_t input)
7373{
7374 ALOGV("closeInput(%d)", input);
7375
7376 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7377 if (inputDesc == NULL) {
7378 ALOGW("closeInput() unknown input %d", input);
7379 return;
7380 }
7381
Eric Laurent6a94d692014-05-20 11:18:06 -07007382 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007383
François Gaffie11d30102018-11-02 16:09:09 +01007384 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007385 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007386 if (index >= 0) {
7387 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007388 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7389 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007390 mAudioPatches.removeItemsAt(index);
7391 mpClientInterface->onAudioPatchListUpdate();
7392 }
7393
François Gaffie6ebbce02023-07-19 13:27:53 +02007394 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007395 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007396 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007397
François Gaffie11d30102018-11-02 16:09:09 +01007398 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7399 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007400 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007401 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007402 }
Eric Laurente552edb2014-03-10 17:42:56 -07007403}
7404
François Gaffie11d30102018-11-02 16:09:09 +01007405SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7406 const DeviceVector &devices,
7407 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007408{
7409 SortedVector<audio_io_handle_t> outputs;
7410
François Gaffie11d30102018-11-02 16:09:09 +01007411 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007412 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007413 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007414 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007415 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007416 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007417 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007418 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007419 outputs.add(openOutputs.keyAt(i));
7420 }
7421 }
7422 return outputs;
7423}
7424
Mikhail Naganov37977152018-07-11 15:54:44 -07007425void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7426{
7427 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7428 // output is suspended before any tracks are moved to it
7429 checkA2dpSuspend();
7430 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007431 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007432 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007433 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007434 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007435 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7436 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7437 // configuration changes will ultimately be rerouted correctly. We can still avoid
7438 // unnecessary rerouting by caching and reusing the arguments to
7439 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7440 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007441 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007442 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007443 // an event that changed routing likely occurred, inform upper layers
7444 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007445}
7446
François Gaffiec005e562018-11-06 15:04:49 +01007447bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7448 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007449{
François Gaffiec005e562018-11-06 15:04:49 +01007450 return mEngine->getProductStrategyForAttributes(lAttr) ==
7451 mEngine->getProductStrategyForAttributes(rAttr);
7452}
7453
Francois Gaffieff1eb522020-05-06 18:37:04 +02007454void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7455{
7456 for (size_t i = 0; i < mAudioSources.size(); i++) {
7457 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7458 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007459 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007460 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007461 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007462 }
7463 }
7464}
7465
7466void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7467{
7468 for (size_t i = 0; i < mAudioSources.size(); i++) {
7469 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7470 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7471 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7472 disconnectAudioSource(sourceDesc);
7473 }
7474 }
7475}
7476
François Gaffiec005e562018-11-06 15:04:49 +01007477void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7478{
7479 auto psId = mEngine->getProductStrategyForAttributes(attr);
7480
7481 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7482 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007483
François Gaffie11d30102018-11-02 16:09:09 +01007484 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7485 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007486
Eric Laurentc209fe42020-06-05 18:11:23 -07007487 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007488 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007489 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007490 // take into account dynamic audio policies related changes: if a client is now associated
7491 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007492 // invalidate clients on outputs that do not support all the newly selected devices for the
7493 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007494 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007495 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007496 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007497 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007498 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007499
Eric Laurentc209fe42020-06-05 18:11:23 -07007500 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7501 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7502 continue;
7503 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007504 if (!desc->supportsAllDevices(newDevices)) {
7505 invalidatedOutputs.push_back(desc);
7506 break;
7507 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007508 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007509 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007510 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7511 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7512 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007513 if (status == OK) {
7514 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7515 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7516 maxLatency = desc->latency();
7517 }
7518 invalidatedOutputs.push_back(desc);
7519 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007520 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007521 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007522 }
7523 }
7524
Eric Laurent56ed8842022-11-15 16:04:41 +01007525 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007526 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7527 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007528 for (audio_io_handle_t srcOut : srcOutputs) {
7529 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007530 if (desc == nullptr) continue;
7531
7532 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007533 maxLatency = desc->latency();
7534 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007535
Eric Laurent56ed8842022-11-15 16:04:41 +01007536 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007537 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007538 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007539 // a client on a non direct outputs has necessarily a linear PCM format
7540 // so we can call selectOutput() safely
7541 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7542 client->flags(),
7543 client->config().format,
7544 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007545 client->config().sample_rate,
7546 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007547 if (newOutput != srcOut) {
7548 invalidate = true;
7549 break;
7550 }
7551 } else {
7552 sp<IOProfile> profile = getProfileForOutput(newDevices,
7553 client->config().sample_rate,
7554 client->config().format,
7555 client->config().channel_mask,
7556 client->flags(),
7557 true /* directOnly */);
7558 if (profile != desc->mProfile) {
7559 invalidate = true;
7560 break;
7561 }
7562 }
7563 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007564 // mute strategy while moving tracks from one output to another
7565 if (invalidate) {
7566 invalidatedOutputs.push_back(desc);
7567 if (desc->isStrategyActive(psId)) {
7568 setStrategyMute(psId, true, desc);
7569 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7570 newDevices.types());
7571 }
Eric Laurente552edb2014-03-10 17:42:56 -07007572 }
François Gaffiec005e562018-11-06 15:04:49 +01007573 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007574 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007575 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007576 }
Eric Laurente552edb2014-03-10 17:42:56 -07007577 }
7578
Eric Laurent56ed8842022-11-15 16:04:41 +01007579 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7580 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7581 std::to_string(srcOutputs[0]).c_str(),
7582 std::to_string(dstOutputs[0]).c_str());
7583
François Gaffiec005e562018-11-06 15:04:49 +01007584 // Move effects associated to this stream from previous output to new output
7585 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007586 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007587 }
François Gaffiec005e562018-11-06 15:04:49 +01007588 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007589 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007590 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007591 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007592 desc->setTracksInvalidatedStatusByStrategy(psId);
7593 }
Eric Laurente552edb2014-03-10 17:42:56 -07007594 }
7595 }
7596}
7597
Eric Laurente0720872014-03-11 09:30:41 -07007598void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007599{
François Gaffiec005e562018-11-06 15:04:49 +01007600 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7601 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7602 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007603 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007604 }
Eric Laurente552edb2014-03-10 17:42:56 -07007605}
7606
Kevin Rocard153f92d2018-12-18 18:33:28 -08007607void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007608 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007609 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007610 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007611 for (size_t i = 0; i < mOutputs.size(); i++) {
7612 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7613 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007614 sp<AudioPolicyMix> primaryMix;
7615 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007616 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007617 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7618 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7619 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007620 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7621 for (auto &secondaryMix : secondaryMixes) {
7622 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7623 if (outputDesc != nullptr &&
7624 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7625 secondaryDescs.push_back(outputDesc);
7626 }
7627 }
7628
jiabinc44b3462022-12-08 12:52:31 -08007629 if (status != OK &&
7630 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7631 // When it failed to query secondary output, only invalidate the client that is not
7632 // MMAP. The reason is that MMAP stream will not support secondary output.
7633 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007634 } else if (!std::equal(
7635 client->getSecondaryOutputs().begin(),
7636 client->getSecondaryOutputs().end(),
7637 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007638 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7639 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007640 // If the format is not PCM, the tracks should be invalidated to get correct
7641 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007642 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007643 } else {
7644 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7645 std::vector<audio_io_handle_t> secondaryOutputIds;
7646 for (const auto &secondaryDesc: secondaryDescs) {
7647 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7648 weakSecondaryDescs.push_back(secondaryDesc);
7649 }
7650 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7651 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007652 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007653 }
7654 }
7655 }
jiabin10a03f12021-05-07 23:46:28 +00007656 if (!trackSecondaryOutputs.empty()) {
7657 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7658 }
jiabinc44b3462022-12-08 12:52:31 -08007659 if (!clientsToInvalidate.empty()) {
7660 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7661 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007662 }
7663}
7664
Eric Laurent2517af32020-11-25 15:31:27 +01007665bool AudioPolicyManager::isScoRequestedForComm() const {
7666 AudioDeviceTypeAddrVector devices;
7667 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7668 for (const auto &device : devices) {
7669 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7670 return true;
7671 }
7672 }
7673 return false;
7674}
7675
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007676bool AudioPolicyManager::isHearingAidUsedForComm() const {
7677 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7678 true /*fromCache*/);
7679 for (const auto &device : devices) {
7680 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7681 return true;
7682 }
7683 }
7684 return false;
7685}
7686
7687
Eric Laurente0720872014-03-11 09:30:41 -07007688void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007689{
François Gaffie53615e22015-03-19 09:24:12 +01007690 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007691 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007692 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007693 return;
7694 }
7695
Eric Laurent3a4311c2014-03-17 12:00:47 -07007696 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007697 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7698 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007699 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007700
7701 // if suspended, restore A2DP output if:
7702 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007703 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007704 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007705 //
Eric Laurentf732e072016-08-03 19:30:28 -07007706 // if not suspended, suspend A2DP output if:
7707 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007708 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007709 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007710 //
7711 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007712 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007713 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007714 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007715 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007716
7717 mpClientInterface->restoreOutput(a2dpOutput);
7718 mA2dpSuspended = false;
7719 }
7720 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007721 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007722 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007723 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007724 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007725
7726 mpClientInterface->suspendOutput(a2dpOutput);
7727 mA2dpSuspended = true;
7728 }
7729 }
7730}
7731
François Gaffie11d30102018-11-02 16:09:09 +01007732DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7733 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007734{
François Gaffiedb1755b2023-09-01 11:50:35 +02007735 if (outputDesc == nullptr) {
7736 return DeviceVector{};
7737 }
François Gaffie11d30102018-11-02 16:09:09 +01007738
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007739 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007740 if (index >= 0) {
7741 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007742 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007743 ALOGV("%s device %s forced by patch %d", __func__,
7744 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7745 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007746 }
7747 }
7748
Dean Wheatley514b4312020-06-17 21:45:00 +10007749 // Do not retrieve engine device for outputs through MSD
7750 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7751 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7752 return outputDesc->devices();
7753 }
7754
Eric Laurent97ac8712018-07-27 18:59:02 -07007755 // Honor explicit routing requests only if no client using default routing is active on this
7756 // input: a specific app can not force routing for other apps by setting a preferred device.
7757 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007758 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007759 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007760 if (device != nullptr) {
7761 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007762 }
7763
François Gaffiea807ef92018-11-05 10:44:33 +01007764 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7765 // of setForceUse / Default Bus device here
7766 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7767 if (device != nullptr) {
7768 return DeviceVector(device);
7769 }
7770
François Gaffiedb1755b2023-09-01 11:50:35 +02007771 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007772 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7773 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307774 auto hasStreamActive = [&](auto stream) {
7775 return hasStream(streams, stream) && isStreamActive(stream, 0);
7776 };
Eric Laurent484e9272018-06-07 17:29:23 -07007777
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307778 auto doGetOutputDevicesForVoice = [&]() {
7779 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007780 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307781 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007782 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7783 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307784 };
7785
7786 // With low-latency playing on speaker, music on WFD, when the first low-latency
7787 // output is stopped, getNewOutputDevices checks for a product strategy
7788 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007789 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307790 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7791 // stream is associated to the output descriptor.
7792 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7793 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7794 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7795 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007796 // Retrieval of devices for voice DL is done on primary output profile, cannot
7797 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007798 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007799 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7800 break;
7801 }
Eric Laurente552edb2014-03-10 17:42:56 -07007802 }
François Gaffiec005e562018-11-06 15:04:49 +01007803 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007804 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007805}
7806
François Gaffie11d30102018-11-02 16:09:09 +01007807sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7808 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007809{
François Gaffie11d30102018-11-02 16:09:09 +01007810 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007811
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007812 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007813 if (index >= 0) {
7814 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007815 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007816 ALOGV("getNewInputDevice() device %s forced by patch %d",
7817 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7818 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007819 }
7820 }
7821
Eric Laurent97ac8712018-07-27 18:59:02 -07007822 // Honor explicit routing requests only if no client using default routing is active on this
7823 // input: a specific app can not force routing for other apps by setting a preferred device.
7824 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007825 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7826 if (device != nullptr) {
7827 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007828 }
7829
Eric Laurentdc95a252018-04-12 12:46:56 -07007830 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007831 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007832 audio_attributes_t attributes;
7833 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007834 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007835 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7836 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007837 attributes = topClient->attributes();
7838 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007839 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007840 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007841 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7842 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007843 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007844 }
7845
Francois Gaffie716e1432019-01-14 16:58:59 +01007846 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7847 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007848 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007849 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007850 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007851 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007852
Eric Laurente552edb2014-03-10 17:42:56 -07007853 return device;
7854}
7855
Eric Laurent794fde22016-03-11 09:50:45 -08007856bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7857 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007858 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007859}
7860
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007861status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007862 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007863 if (devices == nullptr) {
7864 return BAD_VALUE;
7865 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007866
Andy Hung6d23c0f2022-02-16 09:37:15 -08007867 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007868 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7869 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007870 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007871 for (const auto& device : curDevices) {
7872 devices->push_back(device->getDeviceTypeAddr());
7873 }
7874 return NO_ERROR;
7875}
7876
Eric Laurente0720872014-03-11 09:30:41 -07007877void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007878 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007879 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007880 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007881 updateDevicesAndOutputs();
7882 break;
7883 default:
7884 break;
7885 }
7886}
7887
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007888uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007889
7890 // skip beacon mute management if a dedicated TTS output is available
7891 if (mTtsOutputAvailable) {
7892 return 0;
7893 }
7894
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007895 switch(event) {
7896 case STARTING_OUTPUT:
7897 mBeaconMuteRefCount++;
7898 break;
7899 case STOPPING_OUTPUT:
7900 if (mBeaconMuteRefCount > 0) {
7901 mBeaconMuteRefCount--;
7902 }
7903 break;
7904 case STARTING_BEACON:
7905 mBeaconPlayingRefCount++;
7906 break;
7907 case STOPPING_BEACON:
7908 if (mBeaconPlayingRefCount > 0) {
7909 mBeaconPlayingRefCount--;
7910 }
7911 break;
7912 }
7913
7914 if (mBeaconMuteRefCount > 0) {
7915 // any playback causes beacon to be muted
7916 return setBeaconMute(true);
7917 } else {
7918 // no other playback: unmute when beacon starts playing, mute when it stops
7919 return setBeaconMute(mBeaconPlayingRefCount == 0);
7920 }
7921}
7922
7923uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7924 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7925 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7926 // keep track of muted state to avoid repeating mute/unmute operations
7927 if (mBeaconMuted != mute) {
7928 // mute/unmute AUDIO_STREAM_TTS on all outputs
7929 ALOGV("\t muting %d", mute);
7930 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007931 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7932 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7933 ALOGV("\t no tts volume source available");
7934 return 0;
7935 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007936 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007937 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa1e865e62024-08-15 19:11:42 -07007938 setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
7939 DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007940 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007941 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007942 maxLatency = latency;
7943 }
7944 }
7945 mBeaconMuted = mute;
7946 return maxLatency;
7947 }
7948 return 0;
7949}
7950
Eric Laurente0720872014-03-11 09:30:41 -07007951void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007952{
François Gaffiec005e562018-11-06 15:04:49 +01007953 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007954 mPreviousOutputs = mOutputs;
7955}
7956
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007957uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007958 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007959 uint32_t delayMs)
7960{
7961 // mute/unmute strategies using an incompatible device combination
7962 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7963 // if unmuting, unmute only after the specified delay
7964 if (outputDesc->isDuplicated()) {
7965 return 0;
7966 }
7967
7968 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007969 DeviceVector devices = outputDesc->devices();
7970 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007971
François Gaffiec005e562018-11-06 15:04:49 +01007972 auto productStrategies = mEngine->getOrderedProductStrategies();
7973 for (const auto &productStrategy : productStrategies) {
7974 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7975 DeviceVector curDevices =
7976 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7977 curDevices = curDevices.filter(outputDesc->supportedDevices());
7978 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007979 bool doMute = false;
7980
François Gaffiec005e562018-11-06 15:04:49 +01007981 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007982 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007983 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7984 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007985 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007986 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007987 }
Eric Laurent99401132014-05-07 19:48:15 -07007988 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007989 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007990 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007991 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007992 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007993 continue;
7994 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307995 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007996 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7997 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7998 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007999 if (mute) {
8000 // FIXME: should not need to double latency if volume could be applied
8001 // immediately by the audioflinger mixer. We must account for the delay
8002 // between now and the next time the audioflinger thread for this output
8003 // will process a buffer (which corresponds to one buffer size,
8004 // usually 1/2 or 1/4 of the latency).
8005 if (muteWaitMs < desc->latency() * 2) {
8006 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07008007 }
8008 }
8009 }
8010 }
8011 }
8012 }
8013
Eric Laurent99401132014-05-07 19:48:15 -07008014 // temporary mute output if device selection changes to avoid volume bursts due to
8015 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01008016 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07008017 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008018
Eric Laurentdc462862016-07-19 12:29:53 -07008019 if (muteWaitMs < tempMuteWaitMs) {
8020 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07008021 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008022
8023 // If recommended duration is defined, replace temporary mute duration to avoid
8024 // truncated notifications at beginning, which depends on duration of changing path in HAL.
8025 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8026 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8027 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8028 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8029
François Gaffieaaac0fd2018-11-22 17:56:39 +01008030 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8031 // make sure that we do not start the temporary mute period too early in case of
8032 // delayed device change
Vlad Popa1e865e62024-08-15 19:11:42 -07008033 setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8034 setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8035 delayMs + tempMuteDurationMs,
8036 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008037 }
8038 }
8039
Eric Laurente552edb2014-03-10 17:42:56 -07008040 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8041 if (muteWaitMs > delayMs) {
8042 muteWaitMs -= delayMs;
8043 usleep(muteWaitMs * 1000);
8044 return muteWaitMs;
8045 }
8046 return 0;
8047}
8048
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308049uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8050 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008051 const DeviceVector &devices,
8052 bool force,
8053 int delayMs,
8054 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008055 bool requiresMuteCheck, bool requiresVolumeCheck,
8056 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008057{
jiabin3ff8d7d2022-12-13 06:27:44 +00008058 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308059 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8060 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8061 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008062 uint32_t muteWaitMs;
8063
8064 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308065 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008066 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308067 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008068 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008069 return muteWaitMs;
8070 }
Eric Laurente552edb2014-03-10 17:42:56 -07008071
8072 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008073 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008074 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008075 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008076
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308077 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8078 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008079
8080 if (!filteredDevices.isEmpty()) {
8081 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008082 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008083
8084 // if the outputs are not materially active, there is no need to mute.
8085 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008086 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008087 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308088 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8089 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008090 muteWaitMs = 0;
8091 }
Eric Laurente552edb2014-03-10 17:42:56 -07008092
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008093 bool outputRouted = outputDesc->isRouted();
8094
Eric Laurent79ea9582020-06-11 18:49:24 -07008095 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8096 // output profile or if new device is not supported AND previous device(s) is(are) still
8097 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008098 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308099 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8100 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008101 // restore previous device after evaluating strategy mute state
8102 outputDesc->setDevices(prevDevices);
8103 return muteWaitMs;
8104 }
8105
Eric Laurente552edb2014-03-10 17:42:56 -07008106 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008107 // the requested device is AUDIO_DEVICE_NONE
8108 // OR the requested device is the same as current device
8109 // AND force is not specified
8110 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008111 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008112 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308113 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8114 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8115 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008116 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308117 ALOGV("%s %s setting same device on routed output, force apply volumes",
8118 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008119 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8120 }
Eric Laurente552edb2014-03-10 17:42:56 -07008121 return muteWaitMs;
8122 }
8123
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308124 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8125 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008126
Eric Laurente552edb2014-03-10 17:42:56 -07008127 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008128 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008129 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008130 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008131 PatchBuilder patchBuilder;
8132 patchBuilder.addSource(outputDesc);
8133 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8134 for (const auto &filteredDevice : filteredDevices) {
8135 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008136 }
8137
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008138 // Add half reported latency to delayMs when muteWaitMs is null in order
8139 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008140 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8141 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8142 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008143 }
Eric Laurente552edb2014-03-10 17:42:56 -07008144
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008145 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8146 if (!skipMuteDelay) {
8147 // update stream volumes according to new device
8148 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8149 }
Eric Laurente552edb2014-03-10 17:42:56 -07008150
8151 return muteWaitMs;
8152}
8153
Eric Laurentc75307b2015-03-17 15:29:32 -07008154status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008155 int delayMs,
8156 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008157{
Eric Laurent6a94d692014-05-20 11:18:06 -07008158 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008159 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8160 return INVALID_OPERATION;
8161 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008162 if (patchHandle) {
8163 index = mAudioPatches.indexOfKey(*patchHandle);
8164 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008165 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008166 }
8167 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008168 return INVALID_OPERATION;
8169 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008170 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008171 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008172 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008173 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008174 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008175 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008176 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008177 return status;
8178}
8179
8180status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008181 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008182 bool force,
8183 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008184{
8185 status_t status = NO_ERROR;
8186
Eric Laurent1f2f2232014-06-02 12:01:23 -07008187 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008188 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8189 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008190
François Gaffie11d30102018-11-02 16:09:09 +01008191 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008192 PatchBuilder patchBuilder;
8193 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008194 // AUDIO_SOURCE_HOTWORD is for internal use only:
8195 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008196 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8197 auto result = usecase;
8198 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8199 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8200 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008201 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008202 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008203 if (audio_is_remote_submix_device(device->type())) {
8204 // remote submix HAL does not support audio conversion, need source device
8205 // audio config to match the sink input descriptor audio config, otherwise AIDL
8206 // HAL patching will fail
8207 audio_port_config srcDevicePortConfig = {};
8208 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8209 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8210 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8211 srcDevicePortConfig.format = inputDesc->getFormat();
8212 patchBuilder.addSource(srcDevicePortConfig);
8213 } else {
8214 patchBuilder.addSource(device);
8215 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008216 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008217 }
8218 }
8219 return status;
8220}
8221
Eric Laurent6a94d692014-05-20 11:18:06 -07008222status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8223 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008224{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008225 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008226 ssize_t index;
8227 if (patchHandle) {
8228 index = mAudioPatches.indexOfKey(*patchHandle);
8229 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008230 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008231 }
8232 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008233 return INVALID_OPERATION;
8234 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008235 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008236 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008237 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008238 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008239 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008240 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008241 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008242 return status;
8243}
8244
François Gaffie11d30102018-11-02 16:09:09 +01008245sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008246 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008247 audio_format_t& format,
8248 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008249 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008250{
8251 // Choose an input profile based on the requested capture parameters: select the first available
8252 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008253 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008254
Atneya Nair0f0a8032022-12-12 16:20:12 -08008255 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8256 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8257 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8258
8259 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008260
jiabin2fd710d2022-05-02 23:20:22 +00008261 for (;;) {
jiabin91beb492024-10-16 21:53:36 +00008262 sp<IOProfile> inexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008263 uint32_t inexactSamplingRate = 0;
8264 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8265 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008266 uint32_t updatedSamplingRate = 0;
8267 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8268 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8269 for (const auto& hwModule : mHwModules) {
8270 for (const auto& profile : hwModule->getInputProfiles()) {
8271 // profile->log();
8272 //updatedFormat = format;
jiabin91beb492024-10-16 21:53:36 +00008273 auto compatibleScore = profile->getCompatibilityScore(
jiabin66acc432024-02-06 00:57:36 +00008274 DeviceVector(device),
8275 samplingRate,
8276 &updatedSamplingRate,
8277 format,
8278 &updatedFormat,
8279 channelMask,
8280 &updatedChannelMask,
8281 // FIXME ugly cast
jiabin91beb492024-10-16 21:53:36 +00008282 (audio_output_flags_t) flags);
8283 if (compatibleScore == IOProfile::EXACT_MATCH) {
jiabin66acc432024-02-06 00:57:36 +00008284 samplingRate = updatedSamplingRate;
8285 format = updatedFormat;
8286 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008287 return profile;
jiabin91beb492024-10-16 21:53:36 +00008288 } else if ((flags != AUDIO_INPUT_FLAG_NONE
8289 && compatibleScore == IOProfile::PARTIAL_MATCH_WITH_FLAG)
8290 || (inexact == nullptr && compatibleScore != IOProfile::NO_MATCH)) {
8291 inexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008292 inexactSamplingRate = updatedSamplingRate;
8293 inexactFormat = updatedFormat;
8294 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008295 }
8296 }
8297 }
8298
jiabin91beb492024-10-16 21:53:36 +00008299 if (inexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008300 samplingRate = inexactSamplingRate;
8301 format = inexactFormat;
8302 channelMask = inexactChannelMask;
jiabin91beb492024-10-16 21:53:36 +00008303 return inexact;
jiabin2fd710d2022-05-02 23:20:22 +00008304 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8305 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8306 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8307 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8308 flags = AUDIO_INPUT_FLAG_NONE;
8309 } else { // fail
8310 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8311 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8312 samplingRate, format, channelMask, oriFlags);
8313 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008314 }
8315 }
jiabin2fd710d2022-05-02 23:20:22 +00008316
8317 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008318}
8319
Vlad Popa87e0e582024-05-20 18:49:20 -07008320float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8321 VolumeSource volumeSource,
8322 int index,
8323 const DeviceTypeSet &deviceTypes)
8324{
8325 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8326 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8327 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8328
8329 if (com_android_media_audio_abs_volume_index_fix()) {
Vlad Popa08502d82024-10-22 20:17:47 -07008330 const auto it = mAbsoluteVolumeDrivingStreams.find(volumeDevice);
8331 if (it != mAbsoluteVolumeDrivingStreams.end()) {
8332 audio_attributes_t attributesToDriveAbs = it->second;
Vlad Popa87e0e582024-05-20 18:49:20 -07008333 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8334 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8335 ALOGD("%s: no group matching with %s", __FUNCTION__,
8336 toString(attributesToDriveAbs).c_str());
8337 return volumeDb;
8338 }
8339
8340 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8341 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8342 if (vsToDriveAbs == volumeSource) {
8343 // attenuation is applied by the abs volume controller
Vlad Popa444e95e2024-11-07 18:26:20 -08008344 // do not mute LE broadcast to allow the secondary device to continue playing
8345 return (index != 0 || volumeDevice == AUDIO_DEVICE_OUT_BLE_BROADCAST) ? volumeDbMax
8346 : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008347 } else {
8348 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8349 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8350 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8351 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8352 curvesAbs.getVolumeIndexMax());
8353 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8354 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8355 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8356 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8357 return newVolumeDb;
8358 }
8359 }
8360 return volumeDb;
8361 } else {
8362 return volumeDb;
8363 }
8364}
8365
François Gaffieaaac0fd2018-11-22 17:56:39 +01008366float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8367 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008368 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008369 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008370 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008371 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008372{
Vlad Popa9d482762024-06-21 16:40:23 -07008373 float volumeDb;
8374 if (adjustAttenuation) {
8375 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8376 } else {
8377 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8378 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008379 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8380 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8381
8382 if (!computeInternalInteraction) {
8383 return volumeDb;
8384 }
8385
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008386 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8387 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8388 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8389 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008390 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8391 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8392 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8393 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8394 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008395 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008396 mOutputs.isActive(ringVolumeSrc, 0)) {
8397 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008398 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008399 adjustAttenuation,
8400 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008401 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008402 }
8403
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008404 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008405 if ((volumeSource != callVolumeSrc && (isInCall() ||
8406 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008407 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008408 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8409 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008410 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8411 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8412 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008413 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008414 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008415 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008416 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008417 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008418 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008419 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008420 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8421 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8422 // programmatically muted.
8423 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8424 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8425 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008426 bool exemptFromCapping =
8427 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8428 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008429 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8430 volumeSource, volumeDb);
8431 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008432 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8433 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8434 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008435 }
8436 }
Eric Laurente552edb2014-03-10 17:42:56 -07008437 // if a headset is connected, apply the following rules to ring tones and notifications
8438 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008439 // - always attenuate notifications volume by 6dB
8440 // - attenuate ring tones volume by 6dB unless music is not playing and
8441 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008442 // - if music is playing, always limit the volume to current music volume,
8443 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008444 if (!Intersection(deviceTypes,
8445 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8446 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008447 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8448 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008449 ((volumeSource == alarmVolumeSrc ||
8450 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008451 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8452 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8453 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008454 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8455 curves.canBeMuted()) {
8456
Eric Laurente552edb2014-03-10 17:42:56 -07008457 // when the phone is ringing we must consider that music could have been paused just before
8458 // by the music application and behave as if music was active if the last music track was
8459 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008460 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8461 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008462 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008463 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008464 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8465 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008466 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008467 float musicVolDb = computeVolume(musicCurves,
8468 musicVolumeSrc,
8469 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008470 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008471 adjustAttenuation,
8472 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008473 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8474 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8475 if (volumeDb > minVolDb) {
8476 volumeDb = minVolDb;
8477 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008478 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008479 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8480 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008481 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8482 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8483 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8484 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008485 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008486 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008487 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8488 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008489 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8490 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008491 }
8492 }
jiabin9a3361e2019-10-01 09:38:30 -07008493 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008494 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008495 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008496 }
8497 }
8498
François Gaffie43c73442018-11-08 08:21:55 +01008499 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008500}
8501
Eric Laurent3839bc02018-07-10 18:33:34 -07008502int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008503 VolumeSource fromVolumeSource,
8504 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008505{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008506 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008507 return srcIndex;
8508 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008509 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8510 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008511 float minSrc = (float)srcCurves.getVolumeIndexMin();
8512 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8513 float minDst = (float)dstCurves.getVolumeIndexMin();
8514 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008515
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008516 // preserve mute request or correct range
8517 if (srcIndex < minSrc) {
8518 if (srcIndex == 0) {
8519 return 0;
8520 }
8521 srcIndex = minSrc;
8522 } else if (srcIndex > maxSrc) {
8523 srcIndex = maxSrc;
8524 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008525 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8526}
8527
François Gaffieaaac0fd2018-11-22 17:56:39 +01008528status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8529 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008530 int index,
8531 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008532 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008533 int delayMs,
8534 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008535{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008536 // APM is single threaded, and single instance.
8537 static std::set<IVolumeCurves*> invalidCurvesReported;
8538
François Gaffieaaac0fd2018-11-22 17:56:39 +01008539 // do not change actual attributes volume if the attributes is muted
Vlad Popa1e865e62024-08-15 19:11:42 -07008540 if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008541 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8542 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008543 return NO_ERROR;
8544 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008545
Eric Laurentae6e88c2024-01-10 14:42:57 +01008546 bool isVoiceVolSrc;
8547 bool isBtScoVolSrc;
8548 if (!isVolumeConsistentForCalls(
8549 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008550 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008551 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008552 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008553 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008554
jiabin9a3361e2019-10-01 09:38:30 -07008555 if (deviceTypes.empty()) {
8556 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008557 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008558 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008559 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008560 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008561
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008562 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008563 if (!invalidCurvesReported.count(&curves)) {
8564 invalidCurvesReported.insert(&curves);
8565 String8 dump;
8566 curves.dump(&dump);
8567 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8568 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008569 return BAD_VALUE;
8570 }
8571
jiabin9a3361e2019-10-01 09:38:30 -07008572 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008573 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008574 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008575 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008576 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8577 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008578 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8579 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008580 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008581 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008582
8583 bool muted;
8584 if (!com_android_media_audio_ring_my_car()) {
8585 muted = (index == 0) && (volumeDb != 0.0f);
8586 } else {
8587 muted = curves.isMuted();
8588 }
Eric Laurent31a428a2023-08-11 12:16:28 +02008589 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8590 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008591
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008592 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008593 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8594 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8595 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008596 }
Eric Laurente552edb2014-03-10 17:42:56 -07008597 return NO_ERROR;
8598}
8599
Eric Laurentae6e88c2024-01-10 14:42:57 +01008600void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008601 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008602 float voiceVolume;
Vlad Popa1e865e62024-08-15 19:11:42 -07008603
8604 if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8605 index = 0;
8606 }
8607
chenxin2095559032024-06-15 13:59:29 +08008608 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008609 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008610 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008611 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8612 } else {
8613 voiceVolume = index == 0 ? 0.0 : 1.0;
8614 }
8615 if (voiceVolume != mLastVoiceVolume) {
8616 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8617 mLastVoiceVolume = voiceVolume;
8618 }
8619}
8620
8621bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8622 const DeviceTypeSet& deviceTypes,
8623 bool& isVoiceVolSrc,
8624 bool& isBtScoVolSrc,
8625 const char* caller) {
8626 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008627 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8628
Eric Laurentae6e88c2024-01-10 14:42:57 +01008629 const bool isScoRequested = isScoRequestedForComm();
8630 const bool isHAUsed = isHearingAidUsedForComm();
8631
Vlad Popa695b76b2024-06-14 16:49:25 -07008632 if (com_android_media_audio_replace_stream_bt_sco()) {
8633 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8634 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8635 (isScoRequested || isHAUsed);
8636 return true;
8637 }
8638
8639 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008640 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8641
8642 if ((callVolSrc != btScoVolSrc) &&
8643 ((isVoiceVolSrc && isScoRequested) ||
8644 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8645 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8646 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8647 volumeSource, isScoRequested ? " " : " not ");
8648 return false;
8649 }
8650 return true;
8651}
8652
Eric Laurentc75307b2015-03-17 15:29:32 -07008653void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008654 const DeviceTypeSet& deviceTypes,
8655 int delayMs,
8656 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008657{
jiabincd510522020-01-22 09:40:55 -08008658 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008659 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8660 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
Vlad Popa1e865e62024-08-15 19:11:42 -07008661 checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
jiabin9a3361e2019-10-01 09:38:30 -07008662 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008663 }
8664}
8665
François Gaffiec005e562018-11-06 15:04:49 +01008666void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8667 bool on,
8668 const sp<AudioOutputDescriptor>& outputDesc,
8669 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008670 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008671{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008672 std::vector<VolumeSource> sourcesToMute;
8673 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8674 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8675 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008676 VolumeSource source = toVolumeSource(attributes, false);
8677 if ((source != VOLUME_SOURCE_NONE) &&
8678 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8679 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008680 sourcesToMute.push_back(source);
8681 }
Eric Laurente552edb2014-03-10 17:42:56 -07008682 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008683 for (auto source : sourcesToMute) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008684 setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008685 }
8686
Eric Laurente552edb2014-03-10 17:42:56 -07008687}
8688
Vlad Popa1e865e62024-08-15 19:11:42 -07008689void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8690 bool on,
8691 const sp<AudioOutputDescriptor>& outputDesc,
8692 int delayMs,
8693 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008694{
jiabin9a3361e2019-10-01 09:38:30 -07008695 if (deviceTypes.empty()) {
8696 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008697 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008698 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008699 if (on) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008700 if (!outputDesc->isMutedInternally(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008701 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008702 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008703 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8704 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008705 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008706 }
8707 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008708 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8709 // ignored
8710 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008711 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07008712 if (!outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008713 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008714 return;
8715 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008716 if (outputDesc->decMuteCount(volumeSource) == 0) {
8717 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008718 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008719 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008720 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008721 delayMs);
8722 }
8723 }
8724}
8725
François Gaffie53615e22015-03-19 09:24:12 +01008726bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8727{
François Gaffiec005e562018-11-06 15:04:49 +01008728 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008729 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8730 return true;
8731 }
8732
8733 // has known usage?
8734 switch (paa->usage) {
8735 case AUDIO_USAGE_UNKNOWN:
8736 case AUDIO_USAGE_MEDIA:
8737 case AUDIO_USAGE_VOICE_COMMUNICATION:
8738 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8739 case AUDIO_USAGE_ALARM:
8740 case AUDIO_USAGE_NOTIFICATION:
8741 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8742 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8743 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8744 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8745 case AUDIO_USAGE_NOTIFICATION_EVENT:
8746 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8747 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8748 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8749 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008750 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008751 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008752 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008753 case AUDIO_USAGE_EMERGENCY:
8754 case AUDIO_USAGE_SAFETY:
8755 case AUDIO_USAGE_VEHICLE_STATUS:
8756 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008757 break;
8758 default:
8759 return false;
8760 }
8761 return true;
8762}
8763
François Gaffie2110e042015-03-24 08:41:51 +01008764audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8765{
8766 return mEngine->getForceUse(usage);
8767}
8768
Eric Laurent96d1dda2022-03-14 17:14:19 +01008769bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008770 return isStateInCall(mEngine->getPhoneState());
8771}
8772
Eric Laurent96d1dda2022-03-14 17:14:19 +01008773bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008774 return is_state_in_call(state);
8775}
8776
Eric Laurentf9cccec2022-11-16 19:12:00 +01008777bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008778 audio_mode_t mode = mEngine->getPhoneState();
8779 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008780 || (mode == AUDIO_MODE_CALL_SCREEN)
8781 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008782}
8783
Eric Laurentf9cccec2022-11-16 19:12:00 +01008784bool AudioPolicyManager::isInCallOrScreening() const {
8785 audio_mode_t mode = mEngine->getPhoneState();
8786 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8787}
8788
Eric Laurentd60560a2015-04-10 11:31:20 -07008789void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8790{
8791 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008792 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008793 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008794 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008795 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008796 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008797 }
8798 }
8799
8800 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8801 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8802 bool release = false;
8803 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8804 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8805 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8806 source->ext.device.type == deviceDesc->type()) {
8807 release = true;
8808 }
8809 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008810 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008811 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8812 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8813 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008814 sink->ext.device.type == deviceDesc->type() &&
8815 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8816 || strncmp(sink->ext.device.address, address,
8817 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008818 release = true;
8819 }
8820 }
8821 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008822 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8823 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008824 }
8825 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008826
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008827 mInputs.clearSessionRoutesForDevice(deviceDesc);
8828
Francois Gaffie716e1432019-01-14 16:58:59 +01008829 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008830}
8831
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008832void AudioPolicyManager::modifySurroundFormats(
8833 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008834 std::unordered_set<audio_format_t> enforcedSurround(
8835 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008836 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008837 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008838 allSurround.insert(pair.first);
8839 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8840 }
Phil Burk09bc4612016-02-24 15:58:15 -08008841
8842 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8843 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008844 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008845 // This is the resulting set of formats depending on the surround mode:
8846 // 'all surround' = allSurround
8847 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8848 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8849 // 'manual surround' = mManualSurroundFormats
8850 // AUTO: formats v 'enforced surround'
8851 // ALWAYS: formats v 'all surround' v 'enforced surround'
8852 // NEVER: formats ^ 'non-surround'
8853 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008854
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008855 std::unordered_set<audio_format_t> formatSet;
8856 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8857 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008858 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008859 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008860 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008861 formatSet.insert(*formatIter);
8862 }
8863 }
8864 } else {
8865 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8866 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008867 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008868
jiabin81772902018-04-02 17:52:27 -07008869 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008870 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008871 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8872 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8873 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008874 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008875 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8876 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8877 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008878 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008879 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008880 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008881 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008882 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008883 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008884}
8885
jiabin06e4bab2019-07-29 10:13:34 -07008886void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8887 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008888 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8889 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8890
8891 // If NEVER, then remove support for channelMasks > stereo.
8892 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008893 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8894 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008895 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008896 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008897 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008898 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008899 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008900 }
8901 }
jiabin81772902018-04-02 17:52:27 -07008902 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8903 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8904 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008905 bool supports5dot1 = false;
8906 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008907 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008908 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8909 supports5dot1 = true;
8910 break;
8911 }
8912 }
8913 // If not then add 5.1 support.
8914 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008915 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008916 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008917 }
Phil Burk09bc4612016-02-24 15:58:15 -08008918 }
8919}
8920
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008921void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008922 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008923 const sp<IOProfile>& profile) {
8924 if (!profile->hasDynamicAudioProfile()) {
8925 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008926 }
François Gaffie112b0af2015-11-19 16:13:25 +01008927
jiabin12537fc2023-10-12 17:56:08 +00008928 audio_port_v7 devicePort;
8929 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008930
jiabin12537fc2023-10-12 17:56:08 +00008931 audio_port_v7 mixPort;
8932 profile->toAudioPort(&mixPort);
8933 mixPort.ext.mix.handle = ioHandle;
8934
8935 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8936 if (status != NO_ERROR) {
8937 ALOGE("%s failed to query the attributes of the mix port", __func__);
8938 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008939 }
jiabin12537fc2023-10-12 17:56:08 +00008940
8941 std::set<audio_format_t> supportedFormats;
8942 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8943 supportedFormats.insert(mixPort.audio_profiles[i].format);
8944 }
8945 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8946 mReportedFormatsMap[devDesc] = formats;
8947
8948 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008949 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8950 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008951 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8952 modifySurroundFormats(devDesc, &formats);
8953 size_t modifiedNumProfiles = 0;
8954 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8955 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8956 formats.end()) {
8957 // Skip the format that is not present after modifying surround formats.
8958 continue;
8959 }
8960 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8961 sizeof(struct audio_profile));
8962 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8963 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8964 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8965 modifySurroundChannelMasks(&channels);
8966 std::copy(channels.begin(), channels.end(),
8967 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8968 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8969 }
8970 mixPort.num_audio_profiles = modifiedNumProfiles;
8971 }
8972 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008973}
Eric Laurentd60560a2015-04-10 11:31:20 -07008974
Mikhail Naganovdc769682018-05-04 15:34:08 -07008975status_t AudioPolicyManager::installPatch(const char *caller,
8976 audio_patch_handle_t *patchHandle,
8977 AudioIODescriptorInterface *ioDescriptor,
8978 const struct audio_patch *patch,
8979 int delayMs)
8980{
8981 ssize_t index = mAudioPatches.indexOfKey(
8982 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8983 *patchHandle : ioDescriptor->getPatchHandle());
8984 sp<AudioPatch> patchDesc;
8985 status_t status = installPatch(
8986 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8987 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008988 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008989 }
8990 return status;
8991}
8992
8993status_t AudioPolicyManager::installPatch(const char *caller,
8994 ssize_t index,
8995 audio_patch_handle_t *patchHandle,
8996 const struct audio_patch *patch,
8997 int delayMs,
8998 uid_t uid,
8999 sp<AudioPatch> *patchDescPtr)
9000{
9001 sp<AudioPatch> patchDesc;
9002 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
9003 if (index >= 0) {
9004 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01009005 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009006 }
9007
9008 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
9009 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
9010 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
9011 if (status == NO_ERROR) {
9012 if (index < 0) {
9013 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01009014 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009015 } else {
9016 patchDesc->mPatch = *patch;
9017 }
François Gaffieafd4cea2019-11-18 15:50:22 +01009018 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009019 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009020 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009021 }
9022 nextAudioPortGeneration();
9023 mpClientInterface->onAudioPatchListUpdate();
9024 }
9025 if (patchDescPtr) *patchDescPtr = patchDesc;
9026 return status;
9027}
9028
jiabinbce0c1d2020-10-05 11:20:18 -07009029bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9030{
9031 const TrackClientVector activeClients = output->getActiveClients();
9032 if (activeClients.empty()) {
9033 return true;
9034 }
9035 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9036 if (index < 0) {
9037 ALOGE("%s, no audio patch found while there are active clients on output %d",
9038 __func__, output->getId());
9039 return false;
9040 }
9041 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9042 DeviceVector routedDevices;
9043 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9044 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9045 patchDesc->mPatch.sinks[i].id);
9046 if (device == nullptr) {
9047 ALOGE("%s, no audio device found with id(%d)",
9048 __func__, patchDesc->mPatch.sinks[i].id);
9049 return false;
9050 }
9051 routedDevices.add(device);
9052 }
9053 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009054 if (client->isInvalid()) {
9055 // No need to take care about invalidated clients.
9056 continue;
9057 }
jiabinbce0c1d2020-10-05 11:20:18 -07009058 sp<DeviceDescriptor> preferredDevice =
9059 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9060 if (mEngine->getOutputDevicesForAttributes(
9061 client->attributes(), preferredDevice, false) == routedDevices) {
9062 return false;
9063 }
9064 }
9065 return true;
9066}
9067
9068sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009069 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009070 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9071 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009072{
9073 for (const auto& device : devices) {
9074 // TODO: This should be checking if the profile supports the device combo.
9075 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009076 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9077 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009078 return nullptr;
9079 }
9080 }
9081 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9082 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009083 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009084 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009085 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009086 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009087 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009088 return nullptr;
9089 }
jiabin14b50cc2023-12-13 19:01:52 +00009090 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9091 auto portConfig = desc->getConfig();
9092 for (const auto& device : devices) {
9093 device->setPreferredConfig(&portConfig);
9094 }
9095 }
jiabinbce0c1d2020-10-05 11:20:18 -07009096
9097 // Here is where the out_set_parameters() for card & device gets called
9098 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9099 const audio_devices_t deviceType = device->type();
9100 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009101 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009102 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9103 mpClientInterface->setParameters(output, String8(param));
9104 free(param);
9105 }
jiabin12537fc2023-10-12 17:56:08 +00009106 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009107 if (!profile->hasValidAudioProfile()) {
9108 ALOGW("%s() missing param", __func__);
9109 desc->close();
9110 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009111 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9112 // Reopen the output with the best audio profile picked by APM when the profile supports
9113 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009114 desc->close();
9115 output = AUDIO_IO_HANDLE_NONE;
9116 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9117 profile->pickAudioProfile(
9118 config.sample_rate, config.channel_mask, config.format);
9119 config.offload_info.sample_rate = config.sample_rate;
9120 config.offload_info.channel_mask = config.channel_mask;
9121 config.offload_info.format = config.format;
9122
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009123 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009124 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009125 if (status != NO_ERROR) {
9126 return nullptr;
9127 }
9128 }
9129
9130 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009131 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9132 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9133 hwModule->getHalVersionMajor() >= 3) {
9134 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9135 }
baek.kim -61c20122022-07-27 10:05:32 +00009136 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9137 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9138
jiabinbce0c1d2020-10-05 11:20:18 -07009139 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9140 sp<AudioPolicyMix> policyMix;
9141 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9142 policyMix->setOutput(desc);
9143 desc->mPolicyMix = policyMix;
9144 } else {
9145 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009146 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009147 }
9148
baek.kim -61c20122022-07-27 10:05:32 +00009149 } else if (hasPrimaryOutput() && speaker != nullptr
9150 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009151 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9152 // no duplicated output for:
9153 // - direct outputs
9154 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009155 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009156 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9157
9158 //TODO: configure audio effect output stage here
9159
9160 // open a duplicating output thread for the new output and the primary output
9161 sp<SwAudioOutputDescriptor> dupOutputDesc =
9162 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9163 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9164 if (status == NO_ERROR) {
9165 // add duplicated output descriptor
9166 addOutput(duplicatedOutput, dupOutputDesc);
9167 } else {
9168 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9169 mPrimaryOutput->mIoHandle, output);
9170 desc->close();
9171 removeOutput(output);
9172 nextAudioPortGeneration();
9173 return nullptr;
9174 }
9175 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009176 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9177 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9178 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009179 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009180 }
jiabinbce0c1d2020-10-05 11:20:18 -07009181 return desc;
9182}
9183
jiabinf1c73972022-04-14 16:28:52 -07009184status_t AudioPolicyManager::getDevicesForAttributes(
9185 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009186 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9187 // over any usage or content type also present in attr.
9188 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9189 attr.source != AUDIO_SOURCE_INVALID) {
9190 return getInputDevicesForAttributes(attr, devices);
9191 }
9192
jiabinf1c73972022-04-14 16:28:52 -07009193 // Devices are determined in the following precedence:
9194 //
9195 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9196 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9197 //
9198 // If no such dynamic policy then
9199 // 2) Devices containing an active client using setPreferredDevice
9200 // with same strategy as the attributes.
9201 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9202 //
9203 // If no corresponding active client with setPreferredDevice then
9204 // 3) Devices associated with the strategy determined by the attributes
9205 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9206 //
9207 // See related getOutputForAttrInt().
9208
9209 // check dynamic policies but only for primary descriptors (secondary not used for audible
9210 // audio routing, only used for duplication for playback capture)
9211 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009212 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009213 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009214 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9215 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9216 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009217 if (status != OK) {
9218 return status;
9219 }
9220
9221 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9222 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9223 // as they are unaffected by device/stream volume
9224 // (per SwAudioOutputDescriptor::isFixedVolume()).
9225 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9226 ) {
9227 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9228 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9229 devices.add(deviceDesc);
9230 } else {
9231 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9232 // which selects setPreferredDevice if active. This means forVolume call
9233 // will take an active setPreferredDevice, if such exists.
9234
9235 devices = mEngine->getOutputDevicesForAttributes(
9236 attr, nullptr /* preferredDevice */, false /* fromCache */);
9237 }
9238
9239 if (forVolume) {
9240 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9241 // for single volume control in AudioService (such relationship should exist if
9242 // SPEAKER_SAFE is present).
9243 //
9244 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9245 DeviceVector speakerSafeDevices =
9246 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9247 if (!speakerSafeDevices.isEmpty()) {
9248 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9249 devices.remove(speakerSafeDevices);
9250 }
9251 }
9252
9253 return NO_ERROR;
9254}
9255
wenyu zhang8558a332024-09-09 15:12:48 +00009256status_t AudioPolicyManager::getInputDevicesForAttributes(
9257 const audio_attributes_t &attr, DeviceVector &devices) {
9258 devices = DeviceVector(
9259 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9260 AUDIO_SESSION_NONE,
9261 nullptr /* mix */));
9262 return NO_ERROR;
9263}
9264
jiabinf1c73972022-04-14 16:28:52 -07009265status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9266 AudioProfileVector& audioProfiles,
9267 uint32_t flags,
9268 bool isInput) {
9269 for (const auto& hwModule : mHwModules) {
9270 // the MSD module checks for different conditions
9271 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9272 continue;
9273 }
9274 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9275 : hwModule->getOutputProfiles();
9276 for (const auto& profile : ioProfiles) {
9277 if (!profile->areAllDevicesSupported(devices) ||
jiabin91beb492024-10-16 21:53:36 +00009278 !profile->isCompatibleProfileForFlags(flags)) {
jiabinf1c73972022-04-14 16:28:52 -07009279 continue;
9280 }
9281 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9282 }
9283 }
9284
9285 if (!isInput) {
9286 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9287 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9288 if (msdModule != nullptr) {
9289 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9290 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9291 for (const auto &profile: msdModule->getOutputProfiles()) {
9292 if (!profile->asAudioPort()->isDirectOutput()) {
9293 continue;
9294 }
9295 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9296 }
9297 } else {
9298 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9299 }
9300 }
9301 }
9302
9303 return NO_ERROR;
9304}
9305
jiabin3ff8d7d2022-12-13 06:27:44 +00009306sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9307 const audio_config_t *config,
9308 audio_output_flags_t flags,
9309 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009310 closeOutput(outputDesc->mIoHandle);
9311 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9312 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9313 if (preferredOutput == nullptr) {
9314 ALOGE("%s failed to reopen output device=%d, caller=%s",
9315 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009316 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009317 return preferredOutput;
9318}
9319
9320void AudioPolicyManager::reopenOutputsWithDevices(
9321 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9322 for (const auto& [output, devices] : outputsToReopen) {
9323 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9324 closeOutput(output);
9325 openOutputWithProfileAndDevice(desc->mProfile, devices);
9326 }
jiabina84c3d32022-12-02 18:59:55 +00009327}
9328
jiabinc44b3462022-12-08 12:52:31 -08009329PortHandleVector AudioPolicyManager::getClientsForStream(
9330 audio_stream_type_t streamType) const {
9331 PortHandleVector clients;
9332 for (size_t i = 0; i < mOutputs.size(); ++i) {
9333 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9334 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9335 }
9336 return clients;
9337}
9338
9339void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9340 PortHandleVector clients;
9341 for (auto stream : streams) {
9342 PortHandleVector clientsForStream = getClientsForStream(stream);
9343 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9344 }
9345 mpClientInterface->invalidateTracks(clients);
9346}
9347
jiabin220eea12024-05-17 17:55:20 +00009348void AudioPolicyManager::updateClientsInternalMute(
9349 const sp<android::SwAudioOutputDescriptor> &desc) {
9350 if (!desc->isBitPerfect() ||
9351 !com::android::media::audioserver::
9352 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9353 // This is only used for bit perfect output now.
9354 return;
9355 }
9356 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9357 bool bitPerfectClientInternalMute = false;
9358 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9359 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9360 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9361 bitPerfectClient = client;
9362 continue;
9363 }
9364 bool muted = false;
9365 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9366 // System sound is muted.
9367 muted = true;
9368 } else {
9369 bitPerfectClientInternalMute = true;
9370 }
9371 if (client->setInternalMute(muted)) {
9372 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9373 if (!result.ok()) {
9374 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9375 continue;
9376 }
9377 media::TrackInternalMuteInfo info;
9378 info.portId = result.value();
9379 info.muted = client->getInternalMute();
9380 clientsInternalMute.push_back(std::move(info));
9381 }
9382 }
9383 if (bitPerfectClient != nullptr &&
9384 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9385 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9386 if (result.ok()) {
9387 media::TrackInternalMuteInfo info;
9388 info.portId = result.value();
9389 info.muted = bitPerfectClient->getInternalMute();
9390 clientsInternalMute.push_back(std::move(info));
9391 } else {
9392 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9393 __func__, bitPerfectClient->portId());
9394 }
9395 }
9396 if (!clientsInternalMute.empty()) {
9397 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9398 status != NO_ERROR) {
9399 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9400 }
9401 }
9402}
9403
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00009404status_t AudioPolicyManager::getMmapPolicyInfos(AudioMMapPolicyType policyType,
9405 std::vector<AudioMMapPolicyInfo> *policyInfos) {
9406 if (policyType != AudioMMapPolicyType::DEFAULT &&
9407 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9408 return BAD_VALUE;
9409 }
9410 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9411 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9412 return status;
9413 }
9414 }
9415 *policyInfos = mMmapPolicyInfos[policyType];
9416 return NO_ERROR;
9417}
9418
9419status_t AudioPolicyManager::getMmapPolicyForDevice(
9420 AudioMMapPolicyType policyType, AudioMMapPolicyInfo *policyInfo) {
9421 if (policyType != AudioMMapPolicyType::DEFAULT &&
9422 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9423 return BAD_VALUE;
9424 }
9425 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9426 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9427 return status;
9428 }
9429 }
9430 auto it = mMmapPolicyByDeviceType[policyType].find(policyInfo->device.type);
9431 policyInfo->mmapPolicy = it == mMmapPolicyByDeviceType[policyType].end()
9432 ? AudioMMapPolicy::NEVER : it->second;
9433 return NO_ERROR;
9434}
9435
9436status_t AudioPolicyManager::updateMmapPolicyInfos(AudioMMapPolicyType policyType) {
9437 std::vector<AudioMMapPolicyInfo> policyInfos;
9438 if (status_t status = mpClientInterface->getMmapPolicyInfos(policyType, &policyInfos);
9439 status != NO_ERROR) {
9440 ALOGE("%s, failed, error = %d", __func__, status);
9441 return status;
9442 }
9443 std::map<AudioDeviceDescription, AudioMMapPolicy> mmapPolicyByDeviceType;
9444 if (policyInfos.size() == 1 && policyInfos[0].device == AudioDevice()) {
9445 // When there is only one AudioMMapPolicyInfo instance and the device is a default value,
9446 // it indicates the mmap policy is reported via system property. In that case, use the
9447 // routing information to fill details for how mmap is supported for a particular device.
9448 for (const auto &hwModule: mHwModules) {
9449 for (const auto &profile: hwModule->getInputProfiles()) {
9450 if ((profile->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ)
9451 != AUDIO_INPUT_FLAG_MMAP_NOIRQ) {
9452 continue;
9453 }
9454 for (const auto &device: profile->getSupportedDevices()) {
9455 auto deviceDesc =
9456 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9457 if (deviceDesc.ok()) {
9458 mmapPolicyByDeviceType.emplace(
9459 deviceDesc.value(), policyInfos[0].mmapPolicy);
9460 }
9461 }
9462 }
9463 for (const auto &profile: hwModule->getOutputProfiles()) {
9464 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)
9465 != AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
9466 continue;
9467 }
9468 for (const auto &device: profile->getSupportedDevices()) {
9469 auto deviceDesc =
9470 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9471 if (deviceDesc.ok()) {
9472 mmapPolicyByDeviceType.emplace(
9473 deviceDesc.value(), policyInfos[0].mmapPolicy);
9474 }
9475 }
9476 }
9477 }
9478 } else {
9479 for (const auto &info: policyInfos) {
9480 mmapPolicyByDeviceType[info.device.type] = info.mmapPolicy;
9481 }
9482 }
9483 mMmapPolicyByDeviceType.emplace(policyType, mmapPolicyByDeviceType);
9484 mMmapPolicyInfos.emplace(policyType, policyInfos);
9485 return NO_ERROR;
9486}
9487
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009488} // namespace android