blob: 54ef5d504c5e0626b2fa3e5ba9b23ec655950f28 [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 Popaa536eb32024-07-18 16:00:35 -07003567 if (!enabled) {
3568 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3569 return NO_ERROR;
3570 }
3571
Vlad Popa87e0e582024-05-20 18:49:20 -07003572 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3573 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3574 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3575 toString(streamToDriveAbs).c_str());
3576 return BAD_VALUE;
3577 }
3578
Vlad Popaa536eb32024-07-18 16:00:35 -07003579 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003580 return NO_ERROR;
3581}
3582
François Gaffie251c7f02018-11-07 10:41:08 +01003583void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003584{
3585 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003586 if (indexMin < 0 || indexMax < 0) {
3587 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3588 return;
3589 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003590 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003591
3592 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003593 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3594 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003595 continue;
3596 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003597 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003598 }
Eric Laurente552edb2014-03-10 17:42:56 -07003599}
3600
Eric Laurente0720872014-03-11 09:30:41 -07003601status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003602 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003603 bool muted,
François Gaffie53615e22015-03-19 09:24:12 +01003604 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003605{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003606 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003607 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3608 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3609 return NO_ERROR;
3610 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303611 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3612 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Vlad Popa1e865e62024-08-15 19:11:42 -07003613 return setVolumeIndexForAttributes(attributes, index, muted, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003614}
3615
Eric Laurente0720872014-03-11 09:30:41 -07003616status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003617 int *index,
3618 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003619{
François Gaffiec005e562018-11-06 15:04:49 +01003620 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3621 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003622 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003623 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003624 deviceTypes = mEngine->getOutputDevicesForStream(
3625 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003626 }
jiabin9a3361e2019-10-01 09:38:30 -07003627 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003628}
3629
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003630status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003631 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003632 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003633 audio_devices_t device)
3634{
3635 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003636 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3637 if (group == VOLUME_GROUP_NONE) {
3638 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003639 return BAD_VALUE;
3640 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003641 ALOGV("%s: group %d matching with %s index %d",
3642 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003643 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3644 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3645 __FUNCTION__, toString(attributes).c_str());
3646 return NO_ERROR;
3647 }
François Gaffiecfe17322018-11-07 13:41:29 +01003648 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003649 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003650 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003651 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3652 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3653 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3654 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003655 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3656
Vlad Popa1e865e62024-08-15 19:11:42 -07003657
3658 status = setVolumeCurveIndex(index, muted, device, curves);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003659 if (status != NO_ERROR) {
3660 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3661 return status;
3662 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003663
jiabin9a3361e2019-10-01 09:38:30 -07003664 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003665 auto curCurvAttrs = curves.getAttributes();
3666 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3667 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003668 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003669 } else if (!curves.getStreamTypes().empty()) {
3670 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003671 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003672 } else {
3673 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3674 return BAD_VALUE;
3675 }
jiabin9a3361e2019-10-01 09:38:30 -07003676 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3677 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003678
François Gaffiecfe17322018-11-07 13:41:29 +01003679 // update volume on all outputs and streams matching the following:
3680 // - The requested stream (or a stream matching for volume control) is active on the output
3681 // - The device (or devices) selected by the engine for this stream includes
3682 // the requested device
3683 // - For non default requested device, currently selected device on the output is either the
3684 // requested device or one of the devices selected by the engine for this stream
3685 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3686 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003687 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003688 for (size_t i = 0; i < mOutputs.size(); i++) {
3689 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003690 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003691
jiabin9a3361e2019-10-01 09:38:30 -07003692 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3693 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003694 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003695
3696 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003697 continue;
3698 }
3699 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3700 curDevices.find(device) == curDevices.end()) {
3701 continue;
3702 }
3703 bool applyVolume = false;
3704 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3705 curSrcDevices.insert(device);
3706 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003707 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3708 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003709 } else {
3710 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3711 }
3712 if (!applyVolume) {
3713 continue; // next output
3714 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003715 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3716 // If a higher priority strategy is active, and the output is routed to a device with a
3717 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003718 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003719 applyVolume = false;
Vlad Popa1e865e62024-08-15 19:11:42 -07003720 bool swMute = com_android_media_audio_ring_my_car() ? curves.isMuted() : (index == 0);
Francois Gaffie593634d2021-06-22 13:31:31 +02003721 // If the volume source is active with higher priority source, ensure at least Sw Muted
Vlad Popa1e865e62024-08-15 19:11:42 -07003722 desc->setSwMute(swMute, vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003723 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3724 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3725 false /*preferredDevice*/);
3726 if (activeClients.empty()) {
3727 continue;
3728 }
3729 bool isPreempted = false;
3730 bool isHigherPriority = productStrategy < strategy;
3731 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003732 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003733 ALOGV("%s: Strategy=%d (\nrequester:\n"
3734 " group %d, volumeGroup=%d attributes=%s)\n"
3735 " higher priority source active:\n"
3736 " volumeGroup=%d attributes=%s) \n"
3737 " on output %zu, bailing out", __func__, productStrategy,
3738 group, group, toString(attributes).c_str(),
3739 client->volumeSource(), toString(client->attributes()).c_str(), i);
3740 applyVolume = false;
3741 isPreempted = true;
3742 break;
3743 }
3744 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003745 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003746 applyVolume = true;
3747 }
3748 }
3749 if (isPreempted || applyVolume) {
3750 break;
3751 }
3752 }
3753 if (!applyVolume) {
3754 continue; // next output
3755 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003756 }
François Gaffieed91f582020-01-31 10:35:37 +01003757 //FIXME: workaround for truncated touch sounds
3758 // delayed volume change for system stream to be removed when the problem is
3759 // handled by system UI
Vlad Popa1e865e62024-08-15 19:11:42 -07003760 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003761 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003762 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3763 if (volStatus != NO_ERROR) {
3764 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003765 }
3766 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003767
3768 // update voice volume if the an active call route exists
3769 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3770 && (curSrcDevices.find(
3771 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3772 != curSrcDevices.end())) {
3773 bool isVoiceVolSrc;
3774 bool isBtScoVolSrc;
3775 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3776 isVoiceVolSrc, isBtScoVolSrc, __func__)
3777 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003778 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3779 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3780 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003781 }
3782 }
3783
François Gaffiecfe17322018-11-07 13:41:29 +01003784 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3785 return status;
3786}
3787
François Gaffieaaac0fd2018-11-22 17:56:39 +01003788status_t AudioPolicyManager::setVolumeCurveIndex(int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003789 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003790 audio_devices_t device,
3791 IVolumeCurves &volumeCurves)
3792{
3793 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3794 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003795 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3796 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003797 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303798 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3799 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003800 return BAD_VALUE;
3801 }
3802 if (!audio_is_output_device(device)) {
3803 return BAD_VALUE;
3804 }
3805
3806 // Force max volume if stream cannot be muted
3807 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3808
Vlad Popa1e865e62024-08-15 19:11:42 -07003809 ALOGV("%s device %08x, index %d, muted %d", __FUNCTION__ , device, index, muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003810 volumeCurves.addCurrentVolumeIndex(device, index);
Vlad Popa1e865e62024-08-15 19:11:42 -07003811 volumeCurves.setIsMuted(muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003812 return NO_ERROR;
3813}
3814
3815status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3816 int &index,
3817 audio_devices_t device)
3818{
3819 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3820 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003821 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003822 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003823 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003824 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003825 }
jiabin9a3361e2019-10-01 09:38:30 -07003826 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003827}
3828
3829status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3830 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003831 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003832{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003833 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003834 return BAD_VALUE;
3835 }
jiabin9a3361e2019-10-01 09:38:30 -07003836 index = curves.getVolumeIndex(deviceTypes);
3837 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003838 return NO_ERROR;
3839}
3840
3841status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3842 int &index)
3843{
3844 index = getVolumeCurves(attr).getVolumeIndexMin();
3845 return NO_ERROR;
3846}
3847
3848status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3849 int &index)
3850{
3851 index = getVolumeCurves(attr).getVolumeIndexMax();
3852 return NO_ERROR;
3853}
3854
Eric Laurent36829f92017-04-07 19:04:42 -07003855audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003856{
3857 // select one output among several suitable for global effects.
3858 // The priority is as follows:
3859 // 1: An offloaded output. If the effect ends up not being offloadable,
3860 // AudioFlinger will invalidate the track and the offloaded output
3861 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003862 // 2: Spatializer output if the stereo spatializer feature enabled
3863 // 3: A deep buffer output
3864 // 4: The primary output
3865 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003866
François Gaffiec005e562018-11-06 15:04:49 +01003867 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3868 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003869 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003870
Eric Laurent36829f92017-04-07 19:04:42 -07003871 if (outputs.size() == 0) {
3872 return AUDIO_IO_HANDLE_NONE;
3873 }
Eric Laurente552edb2014-03-10 17:42:56 -07003874
Eric Laurent36829f92017-04-07 19:04:42 -07003875 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3876 bool activeOnly = true;
3877
3878 while (output == AUDIO_IO_HANDLE_NONE) {
3879 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003880 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003881 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3882 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3883
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003884 for (audio_io_handle_t outputLoop : outputs) {
3885 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003886 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003887 continue;
3888 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003889 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003890 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003891 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003892 outputOffloaded = outputLoop;
3893 }
3894 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3895 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3896 outputSpatializer = outputLoop;
3897 }
Eric Laurent36829f92017-04-07 19:04:42 -07003898 }
3899 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003900 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003901 }
3902 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003903 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003904 }
3905 }
3906 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3907 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003908 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3909 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003910 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3911 output = outputDeepBuffer;
3912 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3913 output = outputPrimary;
3914 } else {
3915 output = outputs[0];
3916 }
3917 activeOnly = false;
3918 }
3919
3920 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003921 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3922 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003923 mMusicEffectOutput = output;
3924 }
3925
3926 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003927 return output;
3928}
3929
Eric Laurent36829f92017-04-07 19:04:42 -07003930audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3931{
3932 return selectOutputForMusicEffects();
3933}
3934
Eric Laurente0720872014-03-11 09:30:41 -07003935status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003936 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003937 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003938 int session,
3939 int id)
3940{
Shunkai Yao29d10572024-03-19 04:31:47 +00003941 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003942 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003943 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003944 index = mInputs.indexOfKey(io);
3945 if (index < 0) {
3946 ALOGW("registerEffect() unknown io %d", io);
3947 return INVALID_OPERATION;
3948 }
Eric Laurente552edb2014-03-10 17:42:56 -07003949 }
3950 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003951 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3952 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3953 || strategy == PRODUCT_STRATEGY_NONE));
3954 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003955}
3956
Eric Laurentc241b0d2018-11-28 09:08:49 -08003957status_t AudioPolicyManager::unregisterEffect(int id)
3958{
3959 if (mEffects.getEffect(id) == nullptr) {
3960 return INVALID_OPERATION;
3961 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003962 if (mEffects.isEffectEnabled(id)) {
3963 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3964 setEffectEnabled(id, false);
3965 }
3966 return mEffects.unregisterEffect(id);
3967}
3968
3969status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3970{
3971 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3972 if (effect == nullptr) {
3973 return INVALID_OPERATION;
3974 }
3975
3976 status_t status = mEffects.setEffectEnabled(id, enabled);
3977 if (status == NO_ERROR) {
3978 mInputs.trackEffectEnabled(effect, enabled);
3979 }
3980 return status;
3981}
3982
Eric Laurent6c796322019-04-09 14:13:17 -07003983
3984status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3985{
3986 mEffects.moveEffects(ids, io);
3987 return NO_ERROR;
3988}
3989
Eric Laurentc75307b2015-03-17 15:29:32 -07003990bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3991{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003992 auto vs = toVolumeSource(stream, false);
3993 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003994}
3995
3996bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3997{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003998 auto vs = toVolumeSource(stream, false);
3999 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004000}
4001
Eric Laurente0720872014-03-11 09:30:41 -07004002bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07004003{
4004 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004005 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08004006 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004007 return true;
4008 }
4009 }
4010 return false;
4011}
4012
Eric Laurent275e8e92014-11-30 15:14:47 -08004013// Register a list of custom mixes with their attributes and format.
4014// When a mix is registered, corresponding input and output profiles are
4015// added to the remote submix hw module. The profile contains only the
4016// parameters (sampling rate, format...) specified by the mix.
4017// The corresponding input remote submix device is also connected.
4018//
4019// When a remote submix device is connected, the address is checked to select the
4020// appropriate profile and the corresponding input or output stream is opened.
4021//
4022// When capture starts, getInputForAttr() will:
4023// - 1 look for a mix matching the address passed in attribtutes tags if any
4024// - 2 if none found, getDeviceForInputSource() will:
4025// - 2.1 look for a mix matching the attributes source
4026// - 2.2 if none found, default to device selection by policy rules
4027// At this time, the corresponding output remote submix device is also connected
4028// and active playback use cases can be transferred to this mix if needed when reconnecting
4029// after AudioTracks are invalidated
4030//
4031// When playback starts, getOutputForAttr() will:
4032// - 1 look for a mix matching the address passed in attribtutes tags if any
4033// - 2 if none found, look for a mix matching the attributes usage
4034// - 3 if none found, default to device and output selection by policy rules.
4035
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004036status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004037{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004038 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4039 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004040 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004041 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004042 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004043 // examine each mix's route type
4044 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004045 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004046 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4047 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4048 ALOGE("Unsupported Policy Mix %zu of %zu: "
4049 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4050 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004051 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004052 break;
4053 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004054 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4055 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004056 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004057 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4058 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004059 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004060 rSubmixModule = mHwModules.getModuleFromName(
4061 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4062 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004063 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004064 i);
4065 res = INVALID_OPERATION;
4066 break;
4067 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004068 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004069
Eric Laurent97ac8712018-07-27 18:59:02 -07004070 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004071 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004072 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004073 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004074 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4075 } else {
4076 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4077 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004078 }
François Gaffie036e1e92015-03-19 10:16:24 +01004079
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004080 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004081 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004082 res = INVALID_OPERATION;
4083 break;
4084 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004085 audio_config_t outputConfig = mix.mFormat;
4086 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004087 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4088 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004089 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4090 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004091 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004092 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4093 audio_is_linear_pcm(outputConfig.format)
4094 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004095 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004096 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4097 audio_is_linear_pcm(inputConfig.format)
4098 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004099
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004100 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004101 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004102 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004103 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004104 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004105 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004106 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004107 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4108 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004109 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004110 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004111 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004112
4113 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4114 mix.mDeviceType, mix.mDeviceAddress,
4115 String8(), AUDIO_FORMAT_DEFAULT);
4116 if (device == nullptr) {
4117 res = INVALID_OPERATION;
4118 break;
4119 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004120
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004121 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004122 // First try to find an already opened output supporting the device
4123 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004124 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004125
Eric Laurentc529cf62020-04-17 18:19:10 -07004126 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004127 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004128 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004129 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004130 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004131 } else {
4132 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004133 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004134 }
4135 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004136 // If no output found, try to find a direct output profile supporting the device
4137 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4138 sp<HwModule> module = mHwModules[i];
4139 for (size_t j = 0;
4140 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4141 j++) {
4142 sp<IOProfile> profile = module->getOutputProfiles()[j];
4143 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4144 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4145 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004146 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004147 res = INVALID_OPERATION;
4148 } else {
4149 foundOutput = true;
4150 }
4151 }
4152 }
4153 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004154 if (res != NO_ERROR) {
4155 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004156 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004157 res = INVALID_OPERATION;
4158 break;
4159 } else if (!foundOutput) {
4160 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004161 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004162 res = INVALID_OPERATION;
4163 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004164 } else {
4165 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004166 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004167 }
Eric Laurentc722f302014-12-10 11:21:49 -08004168 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004169 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004170 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004171 if (audio_flags::audio_mix_ownership()) {
4172 // Only unregister mixes that were actually registered to not accidentally unregister
4173 // mixes that already existed previously.
4174 unregisterPolicyMixes(registeredMixes);
4175 registeredMixes.clear();
4176 } else {
4177 unregisterPolicyMixes(mixes);
4178 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004179 } else if (checkOutputs) {
4180 checkForDeviceAndOutputChanges();
4181 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004182 }
4183 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004184}
4185
4186status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4187{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004188 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004189 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004190 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004191 sp<HwModule> rSubmixModule;
4192 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004193 for (const auto& mix : mixes) {
4194 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004195
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004196 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004197 rSubmixModule = mHwModules.getModuleFromName(
4198 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4199 if (rSubmixModule == 0) {
4200 res = INVALID_OPERATION;
4201 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004202 }
4203 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004204
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004205 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004206
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004207 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004208 res = INVALID_OPERATION;
4209 continue;
4210 }
4211
Marvin Ramin0783e202024-03-05 12:45:50 +01004212 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004213 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004214 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4215 status_t currentRes =
4216 setDeviceConnectionStateInt(device,
4217 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4218 address.c_str(),
4219 "remote-submix",
4220 AUDIO_FORMAT_DEFAULT);
4221 if (!audio_flags::audio_mix_ownership()) {
4222 res = currentRes;
4223 }
4224 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004225 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004226 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004227 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004228 }
4229 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004230 }
jiabin5740f082019-08-19 15:08:30 -07004231 rSubmixModule->removeOutputProfile(address.c_str());
4232 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004233
Kevin Rocard153f92d2018-12-18 18:33:28 -08004234 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004235 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004236 res = INVALID_OPERATION;
4237 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004238 } else {
4239 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004240 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004241 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004242 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004243
4244 if (res == NO_ERROR && checkOutputs) {
4245 checkForDeviceAndOutputChanges();
4246 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004247 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004248 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004249}
4250
Marvin Raminbdefaf02023-11-01 09:10:32 +01004251status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4252 if (!audio_flags::audio_mix_test_api()) {
4253 return INVALID_OPERATION;
4254 }
4255
4256 _aidl_return.clear();
4257 _aidl_return.reserve(mPolicyMixes.size());
4258 for (const auto &policyMix: mPolicyMixes) {
4259 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4260 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4261 policyMix->mCbFlags);
4262 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004263 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004264 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004265 }
4266
Vlad Popaa5d73f32024-03-08 16:05:38 -08004267 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004268 return OK;
4269}
4270
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004271status_t AudioPolicyManager::updatePolicyMix(
4272 const AudioMix& mix,
4273 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4274 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4275 if (res == NO_ERROR) {
4276 checkForDeviceAndOutputChanges();
4277 updateCallAndOutputRouting();
4278 }
4279 return res;
4280}
4281
Mikhail Naganov100f0122018-11-29 11:22:16 -08004282void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4283{
4284 size_t i = 0;
4285 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4286 for (const auto& fmt : mManualSurroundFormats) {
4287 if (i++ != 0) dst->append(", ");
4288 std::string sfmt;
4289 FormatConverter::toString(fmt, sfmt);
4290 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4291 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4292 }
4293}
4294
Eric Laurentc529cf62020-04-17 18:19:10 -07004295// Returns true if all devices types match the predicate and are supported by one HW module
4296bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004297 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004298 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004299 const char *context,
4300 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004301 for (size_t i = 0; i < devices.size(); i++) {
4302 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004303 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004304 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004305 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004306 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004307 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004308 return false;
4309 }
4310 }
4311 return true;
4312}
4313
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004314void AudioPolicyManager::changeOutputDevicesMuteState(
4315 const AudioDeviceTypeAddrVector& devices) {
4316 ALOGVV("%s() num devices %zu", __func__, devices.size());
4317
4318 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4319 getSoftwareOutputsForDevices(devices);
4320
4321 for (size_t i = 0; i < outputs.size(); i++) {
4322 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4323 DeviceVector prevDevices = outputDesc->devices();
4324 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4325 }
4326}
4327
4328std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4329 const AudioDeviceTypeAddrVector& devices) const
4330{
4331 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4332 DeviceVector deviceDescriptors;
4333 for (size_t j = 0; j < devices.size(); j++) {
4334 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4335 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4336 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4337 ALOGE("%s: device type %#x address %s not supported or not an output device",
4338 __func__, devices[j].mType, devices[j].getAddress());
4339 continue;
4340 }
4341 deviceDescriptors.add(desc);
4342 }
4343 for (size_t i = 0; i < mOutputs.size(); i++) {
4344 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4345 continue;
4346 }
4347 outputs.push_back(mOutputs.valueAt(i));
4348 }
4349 return outputs;
4350}
4351
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004352status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004353 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004354 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004355 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4356 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004357 }
4358 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004359 if (res != NO_ERROR) {
4360 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4361 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004362 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004363
4364 checkForDeviceAndOutputChanges();
4365 updateCallAndOutputRouting();
4366
4367 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004368}
4369
4370status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4371 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004372 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4373 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004374 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004375 __FUNCTION__, uid);
4376 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004377 }
4378
Eric Laurentc529cf62020-04-17 18:19:10 -07004379 checkForDeviceAndOutputChanges();
4380 updateCallAndOutputRouting();
4381
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004382 return res;
4383}
4384
Eric Laurent2517af32020-11-25 15:31:27 +01004385
jiabin0a488932020-08-07 17:32:40 -07004386status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4387 device_role_t role,
4388 const AudioDeviceTypeAddrVector &devices) {
4389 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4390 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004391
Eric Laurentc529cf62020-04-17 18:19:10 -07004392 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004393 return BAD_VALUE;
4394 }
jiabin0a488932020-08-07 17:32:40 -07004395 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004396 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004397 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4398 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004399 return status;
4400 }
4401
4402 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004403
4404 bool forceVolumeReeval = false;
4405 // FIXME: workaround for truncated touch sounds
4406 // to be removed when the problem is handled by system UI
4407 uint32_t delayMs = 0;
4408 if (strategy == mCommunnicationStrategy) {
4409 forceVolumeReeval = true;
4410 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4411 updateInputRouting();
4412 }
4413 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004414
4415 return NO_ERROR;
4416}
4417
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004418void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4419 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004420{
4421 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004422 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004423 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004424 // Only apply special touch sound delay once
4425 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004426 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004427 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004428 for (size_t i = 0; i < mOutputs.size(); i++) {
4429 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4430 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004431 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4432 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004433 // As done in setDeviceConnectionState, we could also fix default device issue by
4434 // preventing the force re-routing in case of default dev that distinguishes on address.
4435 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004436 bool newDevicesNotEmpty = !newDevices.isEmpty();
4437 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4438 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004439 // If the device is using preferred mixer attributes, the output need to reopen
4440 // with default configuration when the new selected devices are different from
4441 // current routing devices.
4442 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4443 continue;
4444 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304445
jiabin2361ed82024-09-20 17:36:31 +00004446 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4447 newDevicesNotEmpty /*force*/, delayMs,
4448 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4449 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004450 // Only apply special touch sound delay once
4451 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004452 }
4453 if (forceVolumeReeval && !newDevices.isEmpty()) {
4454 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4455 }
4456 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004457 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004458 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004459}
4460
Eric Laurent2517af32020-11-25 15:31:27 +01004461void AudioPolicyManager::updateInputRouting() {
4462 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304463 // Skip for hotword recording as the input device switch
4464 // is handled within sound trigger HAL
4465 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4466 continue;
4467 }
Eric Laurent2517af32020-11-25 15:31:27 +01004468 auto newDevice = getNewInputDevice(activeDesc);
4469 // Force new input selection if the new device can not be reached via current input
4470 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4471 setInputDevice(activeDesc->mIoHandle, newDevice);
4472 } else {
4473 closeInput(activeDesc->mIoHandle);
4474 }
4475 }
4476}
4477
Paul Wang5d7cdb52022-11-22 09:45:06 +00004478status_t
4479AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4480 device_role_t role,
4481 const AudioDeviceTypeAddrVector &devices) {
4482 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4483 dumpAudioDeviceTypeAddrVector(devices).c_str());
4484
Eric Laurent78fedbf2023-03-09 14:40:44 +01004485 if (!areAllDevicesSupported(
4486 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004487 return BAD_VALUE;
4488 }
4489 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4490 if (status != NO_ERROR) {
4491 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4492 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4493 return status;
4494 }
4495
4496 checkForDeviceAndOutputChanges();
4497
4498 bool forceVolumeReeval = false;
4499 // TODO(b/263479999): workaround for truncated touch sounds
4500 // to be removed when the problem is handled by system UI
4501 uint32_t delayMs = 0;
4502 if (strategy == mCommunnicationStrategy) {
4503 forceVolumeReeval = true;
4504 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4505 updateInputRouting();
4506 }
4507 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4508
4509 return NO_ERROR;
4510}
4511
4512status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4513 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004514{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004515 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004516
Paul Wang5d7cdb52022-11-22 09:45:06 +00004517 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004518 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004519 ALOGW_IF(status != NAME_NOT_FOUND,
4520 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004521 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004522 return status;
4523 }
4524
4525 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004526
4527 bool forceVolumeReeval = false;
4528 // FIXME: workaround for truncated touch sounds
4529 // to be removed when the problem is handled by system UI
4530 uint32_t delayMs = 0;
4531 if (strategy == mCommunnicationStrategy) {
4532 forceVolumeReeval = true;
4533 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4534 updateInputRouting();
4535 }
4536 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004537
4538 return NO_ERROR;
4539}
4540
jiabin0a488932020-08-07 17:32:40 -07004541status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4542 device_role_t role,
4543 AudioDeviceTypeAddrVector &devices) {
4544 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004545}
4546
Jiabin Huang3b98d322020-09-03 17:54:16 +00004547status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4548 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4549 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4550 dumpAudioDeviceTypeAddrVector(devices).c_str());
4551
Mikhail Naganov55773032020-10-01 15:08:13 -07004552 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004553 return BAD_VALUE;
4554 }
4555 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4556 ALOGW_IF(status != NO_ERROR,
4557 "Engine could not set preferred devices %s for audio source %d role %d",
4558 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4559
Wenyu Zhang47655d22024-10-01 12:24:53 +00004560 if (status == NO_ERROR) {
4561 updateInputRouting();
4562 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004563 return status;
4564}
4565
4566status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4567 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4568 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4569 dumpAudioDeviceTypeAddrVector(devices).c_str());
4570
Mikhail Naganov55773032020-10-01 15:08:13 -07004571 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004572 return BAD_VALUE;
4573 }
4574 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4575 ALOGW_IF(status != NO_ERROR,
4576 "Engine could not add preferred devices %s for audio source %d role %d",
4577 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4578
Eric Laurent2517af32020-11-25 15:31:27 +01004579 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004580 return status;
4581}
4582
4583status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4584 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4585{
4586 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4587 dumpAudioDeviceTypeAddrVector(devices).c_str());
4588
Eric Laurent78fedbf2023-03-09 14:40:44 +01004589 if (!areAllDevicesSupported(
4590 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004591 return BAD_VALUE;
4592 }
4593
4594 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4595 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004596 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004597 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004598 if (status == NO_ERROR) {
4599 updateInputRouting();
4600 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004601 return status;
4602}
4603
4604status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4605 device_role_t role) {
4606 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4607
4608 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004609 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004610 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004611 if (status == NO_ERROR) {
4612 updateInputRouting();
4613 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004614 return status;
4615}
4616
4617status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4618 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4619 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4620}
4621
Oscar Azucena90e77632019-11-27 17:12:28 -08004622status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004623 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004624 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004625 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4626 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004627 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004628 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4629 if (status != NO_ERROR) {
4630 ALOGE("%s() could not set device affinity for userId %d",
4631 __FUNCTION__, userId);
4632 return status;
4633 }
4634
4635 // reevaluate outputs for all devices
4636 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004637 changeOutputDevicesMuteState(devices);
4638 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4639 true /* skipDelays */);
4640 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004641
4642 return NO_ERROR;
4643}
4644
4645status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004646 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004647 AudioDeviceTypeAddrVector devices;
4648 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004649 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4650 if (status != NO_ERROR) {
4651 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4652 __FUNCTION__, userId);
4653 return status;
4654 }
4655
4656 // reevaluate outputs for all devices
4657 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004658 changeOutputDevicesMuteState(devices);
4659 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4660 true /* skipDelays */);
4661 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004662
4663 return NO_ERROR;
4664}
4665
Andy Hungc29d82b2018-10-05 12:23:17 -07004666void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004667{
Andy Hungc29d82b2018-10-05 12:23:17 -07004668 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004669 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004670 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004671 std::string stateLiteral;
4672 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004673 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004674 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4675 "communications", "media", "record", "dock", "system",
4676 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4677 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4678 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004679 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4680 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4681 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4682 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4683 dst->append(" (MANUAL: ");
4684 dumpManualSurroundFormats(dst);
4685 dst->append(")");
4686 }
4687 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004688 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004689 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4690 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004691 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004692 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004693
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004694 dst->append("\n");
4695 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4696 dst->append("\n");
4697 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004698 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004699 mOutputs.dump(dst);
4700 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004701 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004702 mAudioPatches.dump(dst);
4703 mPolicyMixes.dump(dst);
4704 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004705
Kevin Rocardb99cc752019-03-21 20:52:24 -07004706 dst->appendFormat(" AllowedCapturePolicies:\n");
4707 for (auto& policy : mAllowedCapturePolicies) {
4708 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4709 }
4710
jiabina84c3d32022-12-02 18:59:55 +00004711 dst->appendFormat(" Preferred mixer audio configuration:\n");
4712 for (const auto it : mPreferredMixerAttrInfos) {
4713 dst->appendFormat(" - device port id: %d\n", it.first);
4714 for (const auto preferredMixerInfoIt : it.second) {
4715 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4716 preferredMixerInfoIt.second->dump(dst);
4717 }
4718 }
4719
François Gaffiec005e562018-11-06 15:04:49 +01004720 dst->appendFormat("\nPolicy Engine dump:\n");
4721 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004722
4723 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4724 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4725 dst->appendFormat(" - device type: %s, driving stream %d\n",
4726 dumpDeviceTypes({it.first}).c_str(),
4727 mEngine->getVolumeGroupForAttributes(it.second));
4728 }
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00004729
4730 // dump mmap policy by device
4731 dst->appendFormat("\nMmap policy:\n");
4732 for (const auto& [policyType, policyByDevice] : mMmapPolicyByDeviceType) {
4733 std::stringstream ss;
4734 ss << '{';
4735 for (const auto& [deviceType, policy] : policyByDevice) {
4736 ss << deviceType.toString() << ":" << toString(policy) << " ";
4737 }
4738 ss << '}';
4739 dst->appendFormat(" - %s: %s\n", toString(policyType).c_str(), ss.str().c_str());
4740 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004741}
4742
4743status_t AudioPolicyManager::dump(int fd)
4744{
4745 String8 result;
4746 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004747 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004748 return NO_ERROR;
4749}
4750
Kevin Rocardb99cc752019-03-21 20:52:24 -07004751status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4752{
4753 mAllowedCapturePolicies[uid] = capturePolicy;
4754 return NO_ERROR;
4755}
4756
Eric Laurente552edb2014-03-10 17:42:56 -07004757// This function checks for the parameters which can be offloaded.
4758// This can be enhanced depending on the capability of the DSP and policy
4759// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004760audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004761{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004762 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004763 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004764 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004765 offloadInfo.format,
4766 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4767 offloadInfo.has_video);
4768
jiabin2b9d5a12021-12-10 01:06:29 +00004769 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004770 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004771 }
4772
4773 // See if there is a profile to support this.
4774 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004775 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004776 offloadInfo.sample_rate,
4777 offloadInfo.format,
4778 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004779 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4780 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004781 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4782 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4783 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004784 if (profile == nullptr) {
4785 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4786 }
4787 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4788 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4789 }
4790 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004791}
4792
Michael Chana94fbb22018-04-24 14:31:19 +10004793bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4794 const audio_attributes_t& attributes) {
4795 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004796 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004797 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4798 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004799 config.sample_rate,
4800 config.format,
4801 config.channel_mask,
4802 output_flags,
4803 true /* directOnly */);
4804 ALOGV("%s() profile %sfound with name: %s, "
4805 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4806 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004807 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004808 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004809
4810 // also try the MSD module if compatible profile not found
4811 if (profile == nullptr) {
4812 profile = getMsdProfileForOutput(outputDevices,
4813 config.sample_rate,
4814 config.format,
4815 config.channel_mask,
4816 output_flags,
4817 true /* directOnly */);
4818 ALOGV("%s() MSD profile %sfound with name: %s, "
4819 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4820 __FUNCTION__, profile != 0 ? "" : "NOT ",
4821 (profile != 0 ? profile->getTagName().c_str() : "null"),
4822 config.sample_rate, config.format, config.channel_mask, output_flags);
4823 }
4824 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004825}
4826
jiabin2b9d5a12021-12-10 01:06:29 +00004827bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4828 bool durationIgnored) {
4829 if (mMasterMono) {
4830 return false; // no offloading if mono is set.
4831 }
4832
4833 // Check if offload has been disabled
4834 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4835 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4836 return false;
4837 }
4838
4839 // Check if stream type is music, then only allow offload as of now.
4840 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4841 {
4842 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4843 return false;
4844 }
4845
4846 //TODO: enable audio offloading with video when ready
4847 const bool allowOffloadWithVideo =
4848 property_get_bool("audio.offload.video", false /* default_value */);
4849 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4850 ALOGV("%s: has_video == true, returning false", __func__);
4851 return false;
4852 }
4853
4854 //If duration is less than minimum value defined in property, return false
4855 const int min_duration_secs = property_get_int32(
4856 "audio.offload.min.duration.secs", -1 /* default_value */);
4857 if (!durationIgnored) {
4858 if (min_duration_secs >= 0) {
4859 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4860 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4861 __func__, min_duration_secs);
4862 return false;
4863 }
4864 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4865 ALOGV("%s: Offload denied by duration < default min(=%u)",
4866 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4867 return false;
4868 }
4869 }
4870
4871 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4872 // creating an offloaded track and tearing it down immediately after start when audioflinger
4873 // detects there is an active non offloadable effect.
4874 // FIXME: We should check the audio session here but we do not have it in this context.
4875 // This may prevent offloading in rare situations where effects are left active by apps
4876 // in the background.
4877 if (mEffects.isNonOffloadableEffectEnabled()) {
4878 return false;
4879 }
4880
4881 return true;
4882}
4883
4884audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4885 const audio_config_t *config) {
4886 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4887 offloadInfo.format = config->format;
4888 offloadInfo.sample_rate = config->sample_rate;
4889 offloadInfo.channel_mask = config->channel_mask;
4890 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4891 offloadInfo.has_video = false;
4892 offloadInfo.is_streaming = false;
4893 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4894
4895 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4896 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4897 audio_flags_to_audio_output_flags(attr->flags, &flags);
4898 // only retain flags that will drive compressed offload or passthrough
4899 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4900 if (offloadPossible) {
4901 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4902 }
4903 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4904
Dorin Drimusfae3c642022-03-17 18:36:30 +01004905 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004906 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4907 [this, attr](sp<DeviceDescriptor> device) {
4908 return getPreferredMixerAttributesInfo(
4909 device->getId(),
4910 mEngine->getProductStrategyForAttributes(*attr),
4911 true /*activeBitPerfectPreferred*/) != nullptr;
4912 })) {
4913 // Bit-perfect playback is active on one of the selected devices, direct output will
4914 // be rejected at this instant.
4915 return AUDIO_DIRECT_NOT_SUPPORTED;
4916 }
jiabin2b9d5a12021-12-10 01:06:29 +00004917 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004918 DeviceVector outputDevices = engineOutputDevices;
4919 // the MSD module checks for different conditions and output devices
4920 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4921 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4922 continue;
4923 }
4924 outputDevices = getMsdAudioOutDevices();
4925 }
jiabin2b9d5a12021-12-10 01:06:29 +00004926 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004927 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004928 config->sample_rate, nullptr /*updatedSamplingRate*/,
4929 config->format, nullptr /*updatedFormat*/,
4930 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004931 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004932 continue;
4933 }
4934 // reject profiles not corresponding to a device currently available
4935 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4936 continue;
4937 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004938 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4939 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004940 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004941 != AUDIO_DIRECT_NOT_SUPPORTED) {
4942 // Already reports offload gapless supported. No need to report offload support.
4943 continue;
4944 }
4945 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4946 != AUDIO_OUTPUT_FLAG_NONE) {
4947 // If offload gapless is reported, no need to report offload support.
4948 directMode = (audio_direct_mode_t) ((directMode &
4949 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4950 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4951 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004952 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004953 }
4954 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004955 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004956 }
4957 }
4958 }
4959 return directMode;
4960}
4961
Dorin Drimusf2196d82022-01-03 12:11:18 +01004962status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4963 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004964 if (mEffects.isNonOffloadableEffectEnabled()) {
4965 return OK;
4966 }
jiabinf1c73972022-04-14 16:28:52 -07004967 DeviceVector devices;
4968 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004969 if (status != OK) {
4970 return status;
4971 }
4972 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4973 if (devices.empty()) {
4974 return OK; // no output devices for the attributes
4975 }
jiabinf1c73972022-04-14 16:28:52 -07004976 return getProfilesForDevices(devices, audioProfilesVector,
4977 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004978}
4979
jiabina84c3d32022-12-02 18:59:55 +00004980status_t AudioPolicyManager::getSupportedMixerAttributes(
4981 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4982 ALOGV("%s, portId=%d", __func__, portId);
4983 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4984 if (deviceDescriptor == nullptr) {
4985 ALOGE("%s the requested device is currently unavailable", __func__);
4986 return BAD_VALUE;
4987 }
jiabin96daffc2023-05-11 17:51:55 +00004988 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4989 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4990 deviceDescriptor->type());
4991 return BAD_VALUE;
4992 }
jiabina84c3d32022-12-02 18:59:55 +00004993 for (const auto& hwModule : mHwModules) {
4994 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4995 if (curProfile->supportsDevice(deviceDescriptor)) {
4996 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4997 }
4998 }
4999 }
5000 return NO_ERROR;
5001}
5002
5003status_t AudioPolicyManager::setPreferredMixerAttributes(
5004 const audio_attributes_t *attr,
5005 audio_port_handle_t portId,
5006 uid_t uid,
5007 const audio_mixer_attributes_t *mixerAttributes) {
5008 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
5009 "mixerBehavior=%d}, uid=%d, portId=%u",
5010 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
5011 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
5012 mixerAttributes->mixer_behavior, uid, portId);
5013 if (attr->usage != AUDIO_USAGE_MEDIA) {
5014 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
5015 return BAD_VALUE;
5016 }
5017 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5018 if (deviceDescriptor == nullptr) {
5019 ALOGE("%s the requested device is currently unavailable", __func__);
5020 return BAD_VALUE;
5021 }
5022 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5023 ALOGE("%s(%d), type=%d, is not a usb output device",
5024 __func__, portId, deviceDescriptor->type());
5025 return BAD_VALUE;
5026 }
5027
5028 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5029 audio_flags_to_audio_output_flags(attr->flags, &flags);
5030 flags = (audio_output_flags_t) (flags |
5031 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5032 sp<IOProfile> profile = nullptr;
5033 DeviceVector devices(deviceDescriptor);
5034 for (const auto& hwModule : mHwModules) {
5035 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5036 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005037 && curProfile->getCompatibilityScore(
5038 devices,
5039 mixerAttributes->config.sample_rate,
5040 nullptr /*updatedSamplingRate*/,
5041 mixerAttributes->config.format,
5042 nullptr /*updatedFormat*/,
5043 mixerAttributes->config.channel_mask,
5044 nullptr /*updatedChannelMask*/,
jiabin91beb492024-10-16 21:53:36 +00005045 flags)
jiabin66acc432024-02-06 00:57:36 +00005046 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005047 profile = curProfile;
5048 break;
5049 }
5050 }
5051 }
5052 if (profile == nullptr) {
5053 ALOGE("%s, there is no compatible profile found", __func__);
5054 return BAD_VALUE;
5055 }
5056
5057 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5058 sp<PreferredMixerAttributesInfo>::make(
5059 uid, portId, profile, flags, *mixerAttributes);
5060 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5061 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5062
5063 // If 1) there is any client from the preferred mixer configuration owner that is currently
5064 // active and matches the strategy and 2) current output is on the preferred device and the
5065 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5066 // configuration.
5067 std::vector<audio_io_handle_t> outputsToReopen;
5068 for (size_t i = 0; i < mOutputs.size(); i++) {
5069 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005070 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5071 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005072 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005073 } else {
5074 for (const auto &client: output->getActiveClients()) {
5075 if (client->uid() == uid && client->strategy() == strategy) {
5076 client->setIsInvalid();
5077 outputsToReopen.push_back(output->mIoHandle);
5078 }
jiabina84c3d32022-12-02 18:59:55 +00005079 }
5080 }
5081 }
5082 }
5083 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5084 config.sample_rate = mixerAttributes->config.sample_rate;
5085 config.channel_mask = mixerAttributes->config.channel_mask;
5086 config.format = mixerAttributes->config.format;
5087 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005088 sp<SwAudioOutputDescriptor> desc =
5089 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5090 if (desc == nullptr) {
5091 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5092 continue;
5093 }
jiabin220eea12024-05-17 17:55:20 +00005094 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005095 }
5096
5097 return NO_ERROR;
5098}
5099
5100sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005101 audio_port_handle_t devicePortId,
5102 product_strategy_t strategy,
5103 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005104 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5105 if (it == mPreferredMixerAttrInfos.end()) {
5106 return nullptr;
5107 }
jiabind9a58d32023-06-01 17:57:30 +00005108 if (activeBitPerfectPreferred) {
5109 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005110 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005111 return info;
5112 }
5113 }
jiabina84c3d32022-12-02 18:59:55 +00005114 }
jiabind9a58d32023-06-01 17:57:30 +00005115 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5116 return strategyMatchedMixerAttrInfoIt == it->second.end()
5117 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005118}
5119
5120status_t AudioPolicyManager::getPreferredMixerAttributes(
5121 const audio_attributes_t *attr,
5122 audio_port_handle_t portId,
5123 audio_mixer_attributes_t* mixerAttributes) {
5124 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5125 portId, mEngine->getProductStrategyForAttributes(*attr));
5126 if (info == nullptr) {
5127 return NAME_NOT_FOUND;
5128 }
5129 *mixerAttributes = info->getMixerAttributes();
5130 return NO_ERROR;
5131}
5132
5133status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5134 audio_port_handle_t portId,
5135 uid_t uid) {
5136 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5137 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5138 if (preferredMixerAttrInfo == nullptr) {
5139 return NAME_NOT_FOUND;
5140 }
5141 if (preferredMixerAttrInfo->getUid() != uid) {
5142 ALOGE("%s, requested uid=%d, owned uid=%d",
5143 __func__, uid, preferredMixerAttrInfo->getUid());
5144 return PERMISSION_DENIED;
5145 }
5146 mPreferredMixerAttrInfos[portId].erase(strategy);
5147 if (mPreferredMixerAttrInfos[portId].empty()) {
5148 mPreferredMixerAttrInfos.erase(portId);
5149 }
5150
5151 // Reconfig existing output
5152 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5153 for (size_t i = 0; i < mOutputs.size(); i++) {
5154 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5155 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5156 }
5157 }
5158 for (const auto output : potentialOutputsToReopen) {
5159 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5160 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5161 preferredMixerAttrInfo->getFlags())) {
5162 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5163 }
5164 }
5165 return NO_ERROR;
5166}
5167
Eric Laurent6a94d692014-05-20 11:18:06 -07005168status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5169 audio_port_type_t type,
5170 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005171 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005172 unsigned int *generation)
5173{
jiabin19cdba52020-11-24 11:28:58 -08005174 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5175 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005176 return BAD_VALUE;
5177 }
5178 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005179 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 *num_ports = 0;
5181 }
5182
5183 size_t portsWritten = 0;
5184 size_t portsMax = *num_ports;
5185 *num_ports = 0;
5186 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005187 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5188 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005190 for (const auto& dev : mAvailableOutputDevices) {
5191 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005192 continue;
5193 }
5194 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005195 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005196 }
5197 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005198 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005199 }
5200 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005201 for (const auto& dev : mAvailableInputDevices) {
5202 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005203 continue;
5204 }
5205 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005206 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005207 }
5208 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005209 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 }
5211 }
5212 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5213 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5214 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5215 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5216 }
5217 *num_ports += mInputs.size();
5218 }
5219 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005220 size_t numOutputs = 0;
5221 for (size_t i = 0; i < mOutputs.size(); i++) {
5222 if (!mOutputs[i]->isDuplicated()) {
5223 numOutputs++;
5224 if (portsWritten < portsMax) {
5225 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5226 }
5227 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005228 }
Eric Laurent84c70242014-06-23 08:46:27 -07005229 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005230 }
5231 }
jiabina84c3d32022-12-02 18:59:55 +00005232
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005234 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 return NO_ERROR;
5236}
5237
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005238status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5239 std::vector<media::AudioPortFw>* _aidl_return) {
5240 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5241 audio_port_v7 port;
5242 dev->toAudioPort(&port);
5243 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5244 _aidl_return->push_back(std::move(aidlPort));
5245 return OK;
5246 };
5247
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005248 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005249 for (const auto& dev : module->getDeclaredDevices()) {
5250 if (role == media::AudioPortRole::NONE ||
5251 ((role == media::AudioPortRole::SOURCE)
5252 == audio_is_input_device(dev->type()))) {
5253 RETURN_STATUS_IF_ERROR(pushPort(dev));
5254 }
5255 }
5256 }
5257 return OK;
5258}
5259
jiabin19cdba52020-11-24 11:28:58 -08005260status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005261{
Eric Laurent99fcae42018-05-17 16:59:18 -07005262 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5263 return BAD_VALUE;
5264 }
5265 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5266 if (dev != 0) {
5267 dev->toAudioPort(port);
5268 return NO_ERROR;
5269 }
5270 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5271 if (dev != 0) {
5272 dev->toAudioPort(port);
5273 return NO_ERROR;
5274 }
5275 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5276 if (out != 0) {
5277 out->toAudioPort(port);
5278 return NO_ERROR;
5279 }
5280 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5281 if (in != 0) {
5282 in->toAudioPort(port);
5283 return NO_ERROR;
5284 }
5285 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005286}
5287
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005288status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5289 audio_patch_handle_t *handle,
5290 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005291{
François Gaffieafd4cea2019-11-18 15:50:22 +01005292 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005293 if (handle == NULL || patch == NULL) {
5294 return BAD_VALUE;
5295 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005296 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005297 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005298 return BAD_VALUE;
5299 }
5300 // only one source per audio patch supported for now
5301 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005302 return INVALID_OPERATION;
5303 }
Eric Laurent874c42872014-08-08 15:13:39 -07005304 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005305 return INVALID_OPERATION;
5306 }
Eric Laurent874c42872014-08-08 15:13:39 -07005307 for (size_t i = 0; i < patch->num_sinks; i++) {
5308 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5309 return INVALID_OPERATION;
5310 }
5311 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005312
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005313 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5314 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5315 if (srcDevice == nullptr || sinkDevice == nullptr) {
5316 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5317 return BAD_VALUE;
5318 }
5319 ALOGV("%s between source %s and sink %s", __func__,
5320 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5321 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5322 // Default attributes, default volume priority, not to infer with non raw audio patches.
5323 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5324 const struct audio_port_config *source = &patch->sources[0];
5325 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005326 new SourceClientDescriptor(
5327 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5328 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005329 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005330 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005331
5332 status_t status =
5333 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5334
5335 if (status != NO_ERROR) {
5336 return INVALID_OPERATION;
5337 }
5338 mAudioSources.add(portId, sourceDesc);
5339 return NO_ERROR;
5340}
5341
5342status_t AudioPolicyManager::connectAudioSourceToSink(
5343 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5344 const struct audio_patch *patch,
5345 audio_patch_handle_t &handle,
5346 uid_t uid, uint32_t delayMs)
5347{
5348 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5349 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5350 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5351 return INVALID_OPERATION;
5352 }
5353 sourceDesc->connect(handle, sinkDevice);
5354 if (isMsdPatch(handle)) {
5355 return NO_ERROR;
5356 }
5357 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5358 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5359 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5360 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5361 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5362 goto FailurePatchAdded;
5363 }
5364 status = swOutput->start();
5365 if (status != NO_ERROR) {
5366 goto FailureSourceAdded;
5367 }
5368 swOutput->addClient(sourceDesc);
5369 status = startSource(swOutput, sourceDesc, &delayMs);
5370 if (status != NO_ERROR) {
5371 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5372 goto FailureSourceActive;
5373 }
5374 if (delayMs != 0) {
5375 usleep(delayMs * 1000);
5376 }
5377 return NO_ERROR;
5378
5379FailureSourceActive:
5380 swOutput->stop();
5381 releaseOutput(sourceDesc->portId());
5382FailureSourceAdded:
5383 sourceDesc->setSwOutput(nullptr);
5384FailurePatchAdded:
5385 releaseAudioPatchInternal(handle);
5386 return INVALID_OPERATION;
5387}
5388
5389status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5390 audio_patch_handle_t *handle,
5391 uid_t uid, uint32_t delayMs,
5392 const sp<SourceClientDescriptor>& sourceDesc)
5393{
5394 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 sp<AudioPatch> patchDesc;
5396 ssize_t index = mAudioPatches.indexOfKey(*handle);
5397
François Gaffieafd4cea2019-11-18 15:50:22 +01005398 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5399 patch->sources[0].role,
5400 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005401#if LOG_NDEBUG == 0
5402 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005403 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5404 patch->sinks[i].role,
5405 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005406 }
5407#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005408
5409 if (index >= 0) {
5410 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005411 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5412 __func__, mUidCached, patchDesc->getUid(), uid);
5413 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005414 return INVALID_OPERATION;
5415 }
5416 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005417 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005418 }
5419
5420 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005421 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005422 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005423 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005424 return BAD_VALUE;
5425 }
Eric Laurent84c70242014-06-23 08:46:27 -07005426 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5427 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005428 if (patchDesc != 0) {
5429 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005430 ALOGV("%s source id differs for patch current id %d new id %d",
5431 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005432 return BAD_VALUE;
5433 }
5434 }
Eric Laurent874c42872014-08-08 15:13:39 -07005435 DeviceVector devices;
5436 for (size_t i = 0; i < patch->num_sinks; i++) {
5437 // Only support mix to devices connection
5438 // TODO add support for mix to mix connection
5439 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005440 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005441 return INVALID_OPERATION;
5442 }
5443 sp<DeviceDescriptor> devDesc =
5444 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5445 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005446 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005447 return BAD_VALUE;
5448 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005449
jiabin66acc432024-02-06 00:57:36 +00005450 if (outputDesc->mProfile->getCompatibilityScore(
5451 DeviceVector(devDesc),
5452 patch->sources[0].sample_rate,
5453 nullptr, // updatedSamplingRate
5454 patch->sources[0].format,
5455 nullptr, // updatedFormat
5456 patch->sources[0].channel_mask,
5457 nullptr, // updatedChannelMask
5458 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005459 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005460 return INVALID_OPERATION;
5461 }
5462 devices.add(devDesc);
5463 }
5464 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 return INVALID_OPERATION;
5466 }
Eric Laurent874c42872014-08-08 15:13:39 -07005467
Eric Laurent6a94d692014-05-20 11:18:06 -07005468 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005469 ALOGV("%s setting device %s on output %d",
5470 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305471 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005472 index = mAudioPatches.indexOfKey(*handle);
5473 if (index >= 0) {
5474 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005475 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005476 }
5477 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005478 patchDesc->setUid(uid);
5479 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005480 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005481 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005482 return INVALID_OPERATION;
5483 }
5484 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5485 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5486 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005487 // only one sink supported when connecting an input device to a mix
5488 if (patch->num_sinks > 1) {
5489 return INVALID_OPERATION;
5490 }
François Gaffie53615e22015-03-19 09:24:12 +01005491 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005492 if (inputDesc == NULL) {
5493 return BAD_VALUE;
5494 }
5495 if (patchDesc != 0) {
5496 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5497 return BAD_VALUE;
5498 }
5499 }
François Gaffie11d30102018-11-02 16:09:09 +01005500 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005501 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005502 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005503 return BAD_VALUE;
5504 }
5505
jiabin66acc432024-02-06 00:57:36 +00005506 if (inputDesc->mProfile->getCompatibilityScore(
5507 DeviceVector(device),
5508 patch->sinks[0].sample_rate,
5509 nullptr, /*updatedSampleRate*/
5510 patch->sinks[0].format,
5511 nullptr, /*updatedFormat*/
5512 patch->sinks[0].channel_mask,
5513 nullptr, /*updatedChannelMask*/
5514 // FIXME for the parameter type,
5515 // and the NONE
5516 (audio_output_flags_t)
5517 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005518 return INVALID_OPERATION;
5519 }
5520 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005521 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005522 device->toString().c_str(), inputDesc->mIoHandle);
5523 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005524 index = mAudioPatches.indexOfKey(*handle);
5525 if (index >= 0) {
5526 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005527 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005528 }
5529 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005530 patchDesc->setUid(uid);
5531 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005532 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005533 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005534 return INVALID_OPERATION;
5535 }
5536 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5537 // device to device connection
5538 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005539 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005540 return BAD_VALUE;
5541 }
5542 }
François Gaffie11d30102018-11-02 16:09:09 +01005543 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005544 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005545 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005546 return BAD_VALUE;
5547 }
Eric Laurent874c42872014-08-08 15:13:39 -07005548
Eric Laurent6a94d692014-05-20 11:18:06 -07005549 //update source and sink with our own data as the data passed in the patch may
5550 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005551 PatchBuilder patchBuilder;
5552 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005553
5554 // if first sink is to MSD, establish single MSD patch
5555 if (getMsdAudioOutDevices().contains(
5556 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5557 ALOGV("%s patching to MSD", __FUNCTION__);
5558 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5559 goto installPatch;
5560 }
5561
François Gaffieafd4cea2019-11-18 15:50:22 +01005562 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5563 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005564
Eric Laurent874c42872014-08-08 15:13:39 -07005565 for (size_t i = 0; i < patch->num_sinks; i++) {
5566 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005567 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005568 return INVALID_OPERATION;
5569 }
François Gaffie11d30102018-11-02 16:09:09 +01005570 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005571 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005572 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005573 return BAD_VALUE;
5574 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005575 audio_port_config sinkPortConfig = {};
5576 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5577 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005578
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005579 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5580 // volume management purpose (tracking activity)
5581 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5582 // in config XML to reach the sink so that is can be declared as available.
5583 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005584 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005585 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005586 // take care of dynamic routing for SwOutput selection,
5587 audio_attributes_t attributes = sourceDesc->attributes();
5588 audio_stream_type_t stream = sourceDesc->stream();
5589 audio_attributes_t resultAttr;
5590 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5591 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005592 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5593 config.channel_mask =
5594 (audio_channel_mask_get_representation(sourceMask)
5595 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5596 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005597 config.format = sourceDesc->config().format;
5598 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5599 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5600 bool isRequestedDeviceForExclusiveUse = false;
5601 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005602 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005603 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005604 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5605 &stream, sourceDesc->uid(), &config, &flags,
5606 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005607 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005608 if (output == AUDIO_IO_HANDLE_NONE) {
5609 ALOGV("%s no output for device %s",
5610 __FUNCTION__, sinkDevice->toString().c_str());
5611 return INVALID_OPERATION;
5612 }
5613 outputDesc = mOutputs.valueFor(output);
5614 if (outputDesc->isDuplicated()) {
5615 ALOGE("%s output is duplicated", __func__);
5616 return INVALID_OPERATION;
5617 }
François Gaffie7e39df22022-04-26 12:48:49 +02005618 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5619 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005620 } else {
5621 // Same for "raw patches" aka created from createAudioPatch API
5622 SortedVector<audio_io_handle_t> outputs =
5623 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5624 // if the sink device is reachable via an opened output stream, request to
5625 // go via this output stream by adding a second source to the patch
5626 // description
5627 output = selectOutput(outputs);
5628 if (output == AUDIO_IO_HANDLE_NONE) {
5629 ALOGE("%s no output available for internal patch sink", __func__);
5630 return INVALID_OPERATION;
5631 }
5632 outputDesc = mOutputs.valueFor(output);
5633 if (outputDesc->isDuplicated()) {
5634 ALOGV("%s output for device %s is duplicated",
5635 __func__, sinkDevice->toString().c_str());
5636 return INVALID_OPERATION;
5637 }
François Gaffie7e39df22022-04-26 12:48:49 +02005638 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005639 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005640 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005641 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005642 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005643 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005644 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5645 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005646 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5647 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005648 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005649 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005650 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005651 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005652 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005653 return INVALID_OPERATION;
5654 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005655 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005656 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005657 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005658 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005659 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005660 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005661 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005662 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5663 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005664 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005665 }
Eric Laurent83b88082014-06-20 18:31:16 -07005666 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005667 }
5668 // TODO: check from routing capabilities in config file and other conflicting patches
5669
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005670installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005671 status_t status = installPatch(
5672 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005673 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005674 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005675 return INVALID_OPERATION;
5676 }
5677 } else {
5678 return BAD_VALUE;
5679 }
5680 } else {
5681 return BAD_VALUE;
5682 }
5683 return NO_ERROR;
5684}
5685
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005686status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005687{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005688 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005689 ssize_t index = mAudioPatches.indexOfKey(handle);
5690
5691 if (index < 0) {
5692 return BAD_VALUE;
5693 }
5694 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005695 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5696 __func__, mUidCached, patchDesc->getUid(), uid);
5697 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005698 return INVALID_OPERATION;
5699 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005700 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5701 for (size_t i = 0; i < mAudioSources.size(); i++) {
5702 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5703 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5704 portId = sourceDesc->portId();
5705 break;
5706 }
5707 }
5708 return portId != AUDIO_PORT_HANDLE_NONE ?
5709 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005710}
Eric Laurent6a94d692014-05-20 11:18:06 -07005711
François Gaffieafd4cea2019-11-18 15:50:22 +01005712status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005713 uint32_t delayMs,
5714 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005715{
5716 ALOGV("%s patch %d", __func__, handle);
5717 if (mAudioPatches.indexOfKey(handle) < 0) {
5718 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5719 return BAD_VALUE;
5720 }
5721 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005722 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005723 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005724 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005725 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005726 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005727 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005728 return BAD_VALUE;
5729 }
5730
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305731 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005732 getNewOutputDevices(outputDesc, true /*fromCache*/),
5733 true,
5734 0,
5735 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005736 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5737 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005738 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005739 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005740 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005741 return BAD_VALUE;
5742 }
5743 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005744 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005745 true,
5746 NULL);
5747 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005748 status_t status =
5749 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5750 ALOGV("%s patch panel returned %d patchHandle %d",
5751 __func__, status, patchDesc->getAfHandle());
5752 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005753 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005754 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005755 // SW or HW Bridge
5756 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5757 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005758 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005759 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5760 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5761 outputDesc = sourceDesc->swOutput().promote();
5762 }
5763 if (outputDesc == nullptr) {
5764 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5765 // releaseOutput has already called closeOutput in case of direct output
5766 return NO_ERROR;
5767 }
François Gaffie7e39df22022-04-26 12:48:49 +02005768 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005769 // While using a HwBridge, force reconsidering device only if not reusing an existing
5770 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005771 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005772 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5773 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5774 // Reconsider device only for cases:
5775 // 1 / Active Output
5776 // 2 / Inactive Output previously hosting HwBridge
5777 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5778 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5779 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305780 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005781 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5782 outputDesc->devices(),
5783 force,
5784 0,
5785 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005786 } else {
5787 return BAD_VALUE;
5788 }
5789 } else {
5790 return BAD_VALUE;
5791 }
5792 return NO_ERROR;
5793}
5794
5795status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5796 struct audio_patch *patches,
5797 unsigned int *generation)
5798{
François Gaffie53615e22015-03-19 09:24:12 +01005799 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005800 return BAD_VALUE;
5801 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005802 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005803 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005804}
5805
Eric Laurente1715a42014-05-20 11:30:42 -07005806status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005807{
Eric Laurente1715a42014-05-20 11:30:42 -07005808 ALOGV("setAudioPortConfig()");
5809
5810 if (config == NULL) {
5811 return BAD_VALUE;
5812 }
5813 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5814 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005815 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5816 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005817 }
5818
Eric Laurenta121f902014-06-03 13:32:54 -07005819 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005820 if (config->type == AUDIO_PORT_TYPE_MIX) {
5821 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005822 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005823 if (outputDesc == NULL) {
5824 return BAD_VALUE;
5825 }
Eric Laurent84c70242014-06-23 08:46:27 -07005826 ALOG_ASSERT(!outputDesc->isDuplicated(),
5827 "setAudioPortConfig() called on duplicated output %d",
5828 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005829 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005830 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005831 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005832 if (inputDesc == NULL) {
5833 return BAD_VALUE;
5834 }
Eric Laurenta121f902014-06-03 13:32:54 -07005835 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005836 } else {
5837 return BAD_VALUE;
5838 }
5839 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5840 sp<DeviceDescriptor> deviceDesc;
5841 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5842 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5843 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5844 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5845 } else {
5846 return BAD_VALUE;
5847 }
5848 if (deviceDesc == NULL) {
5849 return BAD_VALUE;
5850 }
Eric Laurenta121f902014-06-03 13:32:54 -07005851 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005852 } else {
5853 return BAD_VALUE;
5854 }
5855
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005856 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005857 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5858 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005859 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005860 audioPortConfig->toAudioPortConfig(&newConfig, config);
5861 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005862 }
Eric Laurenta121f902014-06-03 13:32:54 -07005863 if (status != NO_ERROR) {
5864 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005865 }
Eric Laurente1715a42014-05-20 11:30:42 -07005866
5867 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005868}
5869
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005870void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5871{
Eric Laurentd60560a2015-04-10 11:31:20 -07005872 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005873 clearAudioPatches(uid);
5874 clearSessionRoutes(uid);
5875}
5876
Eric Laurent6a94d692014-05-20 11:18:06 -07005877void AudioPolicyManager::clearAudioPatches(uid_t uid)
5878{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005879 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005880 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005881 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005882 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005883 }
5884 }
5885}
5886
François Gaffiec005e562018-11-06 15:04:49 +01005887void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005888{
François Gaffiec005e562018-11-06 15:04:49 +01005889 // Take the first attributes following the product strategy as it is used to retrieve the routed
5890 // device. All attributes wihin a strategy follows the same "routing strategy"
5891 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5892 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005893 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005894 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005895 for (size_t j = 0; j < mOutputs.size(); j++) {
5896 if (mOutputs.keyAt(j) == ouptutToSkip) {
5897 continue;
5898 }
5899 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005900 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005901 continue;
5902 }
5903 // If the default device for this strategy is on another output mix,
5904 // invalidate all tracks in this strategy to force re connection.
5905 // Otherwise select new device on the output mix.
5906 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005907 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005908 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005909 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005910 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005911 // If the device is using preferred mixer attributes, the output need to reopen
5912 // with default configuration when the new selected devices are different from
5913 // current routing devices.
5914 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5915 continue;
5916 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305917 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005918 }
5919 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005920 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005921}
5922
5923void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5924{
5925 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005926 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005927 for (size_t i = 0; i < mOutputs.size(); i++) {
5928 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005929 for (const auto& client : outputDesc->getClientIterable()) {
5930 if (client->hasPreferredDevice() && client->uid() == uid) {
5931 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005932 auto clientStrategy = client->strategy();
5933 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5934 end(affectedStrategies)) {
5935 continue;
5936 }
5937 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005938 }
5939 }
5940 }
5941 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005942 for (const auto& strategy : affectedStrategies) {
5943 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005944 }
5945
5946 // remove input routes associated with this uid
5947 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005948 for (size_t i = 0; i < mInputs.size(); i++) {
5949 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005950 for (const auto& client : inputDesc->getClientIterable()) {
5951 if (client->hasPreferredDevice() && client->uid() == uid) {
5952 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5953 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005954 }
5955 }
5956 }
5957 // reroute inputs if necessary
5958 SortedVector<audio_io_handle_t> inputsToClose;
5959 for (size_t i = 0; i < mInputs.size(); i++) {
5960 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005961 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005962 inputsToClose.add(inputDesc->mIoHandle);
5963 }
5964 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005965 for (const auto& input : inputsToClose) {
5966 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005967 }
5968}
5969
Eric Laurentd60560a2015-04-10 11:31:20 -07005970void AudioPolicyManager::clearAudioSources(uid_t uid)
5971{
5972 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005973 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5974 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005975 stopAudioSource(mAudioSources.keyAt(i));
5976 }
5977 }
5978}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005979
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005980status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5981 audio_io_handle_t *ioHandle,
5982 audio_devices_t *device)
5983{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005984 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5985 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005986 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005987 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5988 if (deviceDesc == nullptr) {
5989 return INVALID_OPERATION;
5990 }
5991 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005992
François Gaffiedf372692015-03-19 10:43:27 +01005993 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005994}
5995
Eric Laurentd60560a2015-04-10 11:31:20 -07005996status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005997 const audio_attributes_t *attributes,
5998 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005999 uid_t uid) {
6000 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00006001 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00006002}
6003
6004status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
6005 const audio_attributes_t *attributes,
6006 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00006007 uid_t uid, bool internal, bool isCallRx,
6008 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07006009{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006010 ALOGV("%s", __FUNCTION__);
6011 *portId = AUDIO_PORT_HANDLE_NONE;
6012
6013 if (source == NULL || attributes == NULL || portId == NULL) {
6014 ALOGW("%s invalid argument: source %p attributes %p handle %p",
6015 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006016 return BAD_VALUE;
6017 }
6018
Eric Laurentd60560a2015-04-10 11:31:20 -07006019 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6020 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006021 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6022 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006023 return INVALID_OPERATION;
6024 }
6025
François Gaffie11d30102018-11-02 16:09:09 +01006026 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006027 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006028 String8(source->ext.device.address),
6029 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006030 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006031 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006032 return BAD_VALUE;
6033 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006034
jiabin4ef93452019-09-10 14:29:54 -07006035 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006036
François Gaffieaaac0fd2018-11-22 17:56:39 +01006037 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006038 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006039 mEngine->getStreamTypeForAttributes(*attributes),
6040 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006041 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006042
David Lif85c5e32024-07-01 13:14:10 +00006043 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006044 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006045 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006046 }
6047 return status;
6048}
6049
David Lif85c5e32024-07-01 13:14:10 +00006050status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6051 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006052{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006053 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006054
6055 // make sure we only have one patch per source.
6056 disconnectAudioSource(sourceDesc);
6057
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006058 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006059 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6060 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6061 sourceDesc->srcDevice()->type(),
6062 String8(sourceDesc->srcDevice()->address().c_str()),
6063 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006064 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006065 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006066 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006067 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006068 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6069 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6070 return INVALID_OPERATION;
6071 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006072 PatchBuilder patchBuilder;
6073 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6074 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006075
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006076 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006077 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006078}
6079
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006080status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006081{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006082 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6083 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006084 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006085 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006086 return BAD_VALUE;
6087 }
6088 status_t status = disconnectAudioSource(sourceDesc);
6089
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006090 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006091 return status;
6092}
6093
Andy Hung2ddee192015-12-18 17:34:44 -08006094status_t AudioPolicyManager::setMasterMono(bool mono)
6095{
6096 if (mMasterMono == mono) {
6097 return NO_ERROR;
6098 }
6099 mMasterMono = mono;
6100 // if enabling mono we close all offloaded devices, which will invalidate the
6101 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6102 // for recreating the new AudioTrack as non-offloaded PCM.
6103 //
6104 // If disabling mono, we leave all tracks as is: we don't know which clients
6105 // and tracks are able to be recreated as offloaded. The next "song" should
6106 // play back offloaded.
6107 if (mMasterMono) {
6108 Vector<audio_io_handle_t> offloaded;
6109 for (size_t i = 0; i < mOutputs.size(); ++i) {
6110 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6111 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6112 offloaded.push(desc->mIoHandle);
6113 }
6114 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006115 for (const auto& handle : offloaded) {
6116 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006117 }
6118 }
6119 // update master mono for all remaining outputs
6120 for (size_t i = 0; i < mOutputs.size(); ++i) {
6121 updateMono(mOutputs.keyAt(i));
6122 }
6123 return NO_ERROR;
6124}
6125
6126status_t AudioPolicyManager::getMasterMono(bool *mono)
6127{
6128 *mono = mMasterMono;
6129 return NO_ERROR;
6130}
6131
Eric Laurentac9cef52017-06-09 15:46:26 -07006132float AudioPolicyManager::getStreamVolumeDB(
6133 audio_stream_type_t stream, int index, audio_devices_t device)
6134{
Vlad Popa9d482762024-06-21 16:40:23 -07006135 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6136 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006137}
6138
jiabin81772902018-04-02 17:52:27 -07006139status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6140 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006141 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006142{
Kriti Dang6537def2021-03-02 13:46:59 +01006143 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6144 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006145 return BAD_VALUE;
6146 }
Kriti Dang6537def2021-03-02 13:46:59 +01006147 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6148 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006149
6150 size_t formatsWritten = 0;
6151 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006152
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006153 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006154 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6155 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006156 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006157 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006158 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006159 bool formatEnabled = true;
6160 switch (forceUse) {
6161 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006162 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006163 break;
6164 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6165 formatEnabled = false;
6166 break;
6167 default: // AUTO or ALWAYS => true
6168 break;
jiabin81772902018-04-02 17:52:27 -07006169 }
6170 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6171 }
jiabin81772902018-04-02 17:52:27 -07006172 }
6173 return NO_ERROR;
6174}
6175
Kriti Dang6537def2021-03-02 13:46:59 +01006176status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6177 audio_format_t *surroundFormats) {
6178 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6179 return BAD_VALUE;
6180 }
6181 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6182 __func__, *numSurroundFormats, surroundFormats);
6183
6184 size_t formatsWritten = 0;
6185 size_t formatsMax = *numSurroundFormats;
6186 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6187
6188 // Return formats from all device profiles that have already been resolved by
6189 // checkOutputsForDevice().
6190 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6191 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6192 audio_devices_t deviceType = device->type();
6193 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6194 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006195 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6196 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006197 continue;
6198 }
6199 // Formats reported by sink devices
6200 std::unordered_set<audio_format_t> formatset;
6201 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6202 formatset.insert(it->second.begin(), it->second.end());
6203 }
6204
6205 // Formats hard-coded in the in policy configuration file (if any).
6206 FormatVector encodedFormats = device->encodedFormats();
6207 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6208 // Filter the formats which are supported by the vendor hardware.
6209 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006210 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006211 formats.insert(*it);
6212 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006213 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006214 if (pair.second.count(*it) != 0) {
6215 formats.insert(pair.first);
6216 break;
6217 }
6218 }
6219 }
6220 }
6221 }
6222 *numSurroundFormats = formats.size();
6223 for (const auto& format: formats) {
6224 if (formatsWritten < formatsMax) {
6225 surroundFormats[formatsWritten++] = format;
6226 }
6227 }
6228 return NO_ERROR;
6229}
6230
jiabin81772902018-04-02 17:52:27 -07006231status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6232{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006233 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006234 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6235 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006236 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006237 return BAD_VALUE;
6238 }
6239
Mikhail Naganov100f0122018-11-29 11:22:16 -08006240 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6241 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006242 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006243 return INVALID_OPERATION;
6244 }
6245
Mikhail Naganov100f0122018-11-29 11:22:16 -08006246 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006247 return NO_ERROR;
6248 }
6249
Mikhail Naganov100f0122018-11-29 11:22:16 -08006250 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006251 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006252 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006253 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006254 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006255 }
6256 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006257 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006258 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006259 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006260 }
6261 }
6262
6263 sp<SwAudioOutputDescriptor> outputDesc;
6264 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006265 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6266 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006267 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6268 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006269 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006270 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006271 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006272 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6273 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006274 name.c_str(),
6275 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006276 if (status != NO_ERROR) {
6277 continue;
6278 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006279 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006280 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6281 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006282 name.c_str(),
6283 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006284 profileUpdated |= (status == NO_ERROR);
6285 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006286 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006287 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006288 AUDIO_DEVICE_IN_HDMI);
6289 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6290 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006291 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006292 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006293 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6294 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6295 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006296 name.c_str(),
6297 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006298 if (status != NO_ERROR) {
6299 continue;
6300 }
6301 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6302 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6303 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006304 name.c_str(),
6305 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006306 profileUpdated |= (status == NO_ERROR);
6307 }
6308
jiabin81772902018-04-02 17:52:27 -07006309 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006310 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006311 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006312 }
6313
6314 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6315}
6316
Eric Laurent5ada82e2019-08-29 17:53:54 -07006317void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006318{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006319 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006320 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006321 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006322 }
6323}
6324
jiabin6012f912018-11-02 17:06:30 -07006325bool AudioPolicyManager::isHapticPlaybackSupported()
6326{
6327 for (const auto& hwModule : mHwModules) {
6328 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6329 for (const auto &outProfile : outputProfiles) {
6330 struct audio_port audioPort;
6331 outProfile->toAudioPort(&audioPort);
6332 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6333 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6334 return true;
6335 }
6336 }
6337 }
6338 }
6339 return false;
6340}
6341
Carter Hsu325a8eb2022-01-19 19:56:51 +08006342bool AudioPolicyManager::isUltrasoundSupported()
6343{
6344 bool hasUltrasoundOutput = false;
6345 bool hasUltrasoundInput = false;
6346 for (const auto& hwModule : mHwModules) {
6347 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6348 if (!hasUltrasoundOutput) {
6349 for (const auto &outProfile : outputProfiles) {
6350 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6351 hasUltrasoundOutput = true;
6352 break;
6353 }
6354 }
6355 }
6356
6357 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6358 if (!hasUltrasoundInput) {
6359 for (const auto &inputProfile : inputProfiles) {
6360 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6361 hasUltrasoundInput = true;
6362 break;
6363 }
6364 }
6365 }
6366
6367 if (hasUltrasoundOutput && hasUltrasoundInput)
6368 return true;
6369 }
6370 return false;
6371}
6372
Atneya Nair698f5ef2022-12-15 16:15:09 -08006373bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6374{
6375 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6376 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6377 for (const auto& hwModule : mHwModules) {
6378 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6379 for (const auto &inputProfile : inputProfiles) {
6380 if ((inputProfile->getFlags() & mask) == mask) {
6381 return true;
6382 }
6383 }
6384 }
6385 return false;
6386}
6387
Eric Laurent8340e672019-11-06 11:01:08 -08006388bool AudioPolicyManager::isCallScreenModeSupported()
6389{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006390 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006391}
6392
6393
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006394status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006395{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006396 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006397 if (!sourceDesc->isConnected()) {
6398 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6399 return NO_ERROR;
6400 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006401 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6402 if (swOutput != 0) {
6403 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006404 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006405 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006406 }
jiabinbce0c1d2020-10-05 11:20:18 -07006407 if (releaseOutput(sourceDesc->portId())) {
6408 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6409 // no need to release audio patch here but just return NO_ERROR.
6410 return NO_ERROR;
6411 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006412 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006413 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006414 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006415 // close Hwoutput and remove from mHwOutputs
6416 } else {
6417 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6418 }
6419 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006420 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006421 sourceDesc->disconnect();
6422 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006423}
6424
François Gaffiec005e562018-11-06 15:04:49 +01006425sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6426 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006427{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006428 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006429 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006430 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006431 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006432 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6433 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006434 source = sourceDesc;
6435 break;
6436 }
6437 }
6438 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006439}
6440
Eric Laurentb4f42a92022-01-17 17:37:31 +01006441bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006442 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006443 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006444{
6445 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6446 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006447 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006448 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006449 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6450 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6451 return false;
6452 }
6453 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6454 return false;
6455 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006456 }
6457
Eric Laurentd332bc82023-08-04 11:45:23 +02006458 // The caller can have the audio config criteria ignored by either passing a null ptr or
6459 // the AUDIO_CONFIG_INITIALIZER value.
6460 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006461 // some positional channel masks and PCM format and for stereo if low latency performance
6462 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006463
6464 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006465 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006466 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6467 ? audio_channel_mask_contains_stereo(config->channel_mask)
6468 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006469 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006470 return false;
6471 }
6472 if (!audio_is_linear_pcm(config->format)) {
6473 return false;
6474 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006475 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6476 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6477 return false;
6478 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006479 }
6480
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006481 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006482 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006483 if (profile == nullptr) {
6484 return false;
6485 }
6486
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006487 return true;
6488}
6489
Shunkai Yao4c3af932024-04-26 04:12:21 +00006490// The Spatializer output is compatible with Haptic use cases if:
6491// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6492// with client if client haptic channel bits were set, or
6493// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6494// including the haptic bits or creating the HapticGenerator effect for same session.
6495bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6496 const audio_config_t* config, audio_session_t sessionId) const {
6497 const auto clientHapticChannel =
6498 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6499 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6500 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6501
6502 if (threadOutputHapticChannel) {
6503 // check format and sampleRate match if client haptic channel mask exist
6504 if (clientHapticChannel) {
6505 return mSpatializerOutput->getFormat() == config->format &&
6506 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6507 }
6508 return true;
6509 } else {
6510 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6511 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6512 // HapticGenerator effect for this session) are not supported.
6513 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006514 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006515 }
6516}
6517
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006518void AudioPolicyManager::checkVirtualizerClientRoutes() {
6519 std::set<audio_stream_type_t> streamsToInvalidate;
6520 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006521 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6522 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006523 audio_attributes_t attr = client->attributes();
6524 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6525 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6526 audio_config_base_t clientConfig = client->config();
6527 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006528 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006529 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006530 streamsToInvalidate.insert(client->stream());
6531 }
6532 }
6533 }
6534
jiabinc44b3462022-12-08 12:52:31 -08006535 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006536}
6537
Eric Laurente191d1b2022-04-15 11:59:25 +02006538
6539bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6540 const sp<SwAudioOutputDescriptor>& outputDesc) {
6541 if (outputDesc->isDuplicated()) {
6542 return false;
6543 }
6544 DeviceVector devices = outputDesc->supportedDevices();
6545 for (size_t i = 0; i < mOutputs.size(); i++) {
6546 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6547 if (desc == outputDesc || desc->isDuplicated()) {
6548 continue;
6549 }
6550 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6551 if (!sharedDevices.isEmpty()
6552 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6553 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6554 return false;
6555 }
6556 }
6557 return true;
6558}
6559
6560
Eric Laurentfa0f6742021-08-17 18:39:44 +02006561status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006562 const audio_attributes_t *attr,
6563 audio_io_handle_t *output) {
6564 *output = AUDIO_IO_HANDLE_NONE;
6565
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006566 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6567 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6568 audio_config_t *configPtr = nullptr;
6569 audio_config_t config;
6570 if (mixerConfig != nullptr) {
6571 config = audio_config_initializer(mixerConfig);
6572 configPtr = &config;
6573 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006574 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006575 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006576 return BAD_VALUE;
6577 }
6578
6579 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006580 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006581 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006582 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006583 return BAD_VALUE;
6584 }
6585
Eric Laurente191d1b2022-04-15 11:59:25 +02006586 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006587 for (size_t i = 0; i < mOutputs.size(); i++) {
6588 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006589 if (!desc->isDuplicated()
6590 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6591 spatializerOutputs.push_back(desc);
6592 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006593 }
6594 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006595 mSpatializerOutput.clear();
6596 bool outputsChanged = false;
6597 for (const auto& desc : spatializerOutputs) {
6598 if (desc->mProfile == profile
6599 && (configPtr == nullptr
6600 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6601 mSpatializerOutput = desc;
6602 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6603 } else {
6604 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6605 " and devices %s", __func__, desc->mIoHandle,
6606 configPtr != nullptr ? configPtr->channel_mask : 0,
6607 devices.toString().c_str());
6608 closeOutput(desc->mIoHandle);
6609 outputsChanged = true;
6610 }
Eric Laurent39095982021-08-24 18:29:27 +02006611 }
6612
Eric Laurente191d1b2022-04-15 11:59:25 +02006613 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006614 sp<SwAudioOutputDescriptor> desc =
6615 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006616 if (desc != nullptr) {
6617 mSpatializerOutput = desc;
6618 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006619 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006620 }
6621
6622 checkVirtualizerClientRoutes();
6623
Eric Laurente191d1b2022-04-15 11:59:25 +02006624 if (outputsChanged) {
6625 mPreviousOutputs = mOutputs;
6626 mpClientInterface->onAudioPortListUpdate();
6627 }
6628
6629 if (mSpatializerOutput == nullptr) {
6630 ALOGV("%s could not open spatializer output with requested config", __func__);
6631 return BAD_VALUE;
6632 }
Eric Laurent39095982021-08-24 18:29:27 +02006633 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006634 ALOGV("%s returning new spatializer output %d", __func__, *output);
6635 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006636}
6637
Eric Laurentfa0f6742021-08-17 18:39:44 +02006638status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6639 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006640 return INVALID_OPERATION;
6641 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006642 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006643 return BAD_VALUE;
6644 }
Eric Laurent39095982021-08-24 18:29:27 +02006645
Eric Laurente191d1b2022-04-15 11:59:25 +02006646 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6647 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6648 closeOutput(mSpatializerOutput->mIoHandle);
6649 //from now on mSpatializerOutput is null
6650 checkVirtualizerClientRoutes();
6651 }
Eric Laurent39095982021-08-24 18:29:27 +02006652
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006653 return NO_ERROR;
6654}
6655
Eric Laurente552edb2014-03-10 17:42:56 -07006656// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006657// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006658// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006659uint32_t AudioPolicyManager::nextAudioPortGeneration()
6660{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006661 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006662}
6663
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006664AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006665 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006666 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006667 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006668 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006669 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006670 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006671 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006672 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006673 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006674 mAudioPortGeneration(1),
6675 mBeaconMuteRefCount(0),
6676 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006677 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006678 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006679 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006680 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006681{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006682}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006683
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006684status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006685 if (mEngine == nullptr) {
6686 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006687 }
6688 mEngine->setObserver(this);
6689 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006690 if (status != NO_ERROR) {
6691 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6692 return status;
6693 }
François Gaffie2110e042015-03-24 08:41:51 +01006694
jiabin29230182023-04-04 21:02:36 +00006695 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6696 // at the end of this function.
6697 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006698 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6699 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6700
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006701 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006702 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006703 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006704
Eric Laurent3a4311c2014-03-17 12:00:47 -07006705 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006706 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6707 defaultOutputDevice == nullptr ||
6708 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6709 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6710 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006711 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006712 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006713 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006714
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006715 // Silence ALOGV statements
6716 property_set("log.tag." LOG_TAG, "D");
6717
Eric Laurente552edb2014-03-10 17:42:56 -07006718 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006719 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006720}
6721
Eric Laurente0720872014-03-11 09:30:41 -07006722AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006723{
Eric Laurente552edb2014-03-10 17:42:56 -07006724 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006725 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006726 }
6727 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006728 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006729 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006730 mAvailableOutputDevices.clear();
6731 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006732 mOutputs.clear();
6733 mInputs.clear();
6734 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006735 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006736 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006737}
6738
Eric Laurente0720872014-03-11 09:30:41 -07006739status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006740{
Eric Laurent87ffa392015-05-22 10:32:38 -07006741 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006742}
6743
Eric Laurente552edb2014-03-10 17:42:56 -07006744// ---
6745
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006746void AudioPolicyManager::onNewAudioModulesAvailable()
6747{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006748 DeviceVector newDevices;
6749 onNewAudioModulesAvailableInt(&newDevices);
6750 if (!newDevices.empty()) {
6751 nextAudioPortGeneration();
6752 mpClientInterface->onAudioPortListUpdate();
6753 }
6754}
6755
6756void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6757{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006758 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006759 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6760 continue;
6761 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006762 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006763 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6764 handle != AUDIO_MODULE_HANDLE_NONE) {
6765 hwModule->setHandle(handle);
6766 } else {
6767 ALOGW("could not load HW module %s", hwModule->getName());
6768 continue;
6769 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006770 }
6771 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006772 // open all output streams needed to access attached devices.
6773 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006774 // This also validates mAvailableOutputDevices list
6775 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6776 if (!outProfile->canOpenNewIo()) {
6777 ALOGE("Invalid Output profile max open count %u for profile %s",
6778 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6779 continue;
6780 }
6781 if (!outProfile->hasSupportedDevices()) {
6782 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6783 continue;
6784 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006785 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6786 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006787 mTtsOutputAvailable = true;
6788 }
6789
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006790 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006791 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006792 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006793 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6794 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006795 } else {
6796 // choose first device present in profile's SupportedDevices also part of
6797 // mAvailableOutputDevices.
6798 if (availProfileDevices.isEmpty()) {
6799 continue;
6800 }
6801 supportedDevice = availProfileDevices.itemAt(0);
6802 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006803 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006804 continue;
6805 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306806
6807 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6808 && availProfileDevices.areAllDevicesAttached()) {
6809 ALOGV("%s skip opening output for mmap profile %s", __func__,
6810 outProfile->getTagName().c_str());
6811 continue;
6812 }
6813
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006814 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6815 mpClientInterface);
6816 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006817 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006818 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006819 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6820 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006821 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006822 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006823 if (status != NO_ERROR) {
6824 ALOGW("Cannot open output stream for devices %s on hw module %s",
6825 supportedDevice->toString().c_str(), hwModule->getName());
6826 continue;
6827 }
6828 for (const auto &device : availProfileDevices) {
6829 // give a valid ID to an attached device once confirmed it is reachable
6830 if (!device->isAttached()) {
6831 device->attach(hwModule);
6832 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006833 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006834 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006835 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6836 }
6837 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006838 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006839 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6840 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006841 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006842 }
Eric Laurent39095982021-08-24 18:29:27 +02006843 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006844 outputDesc->close();
6845 } else {
6846 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306847 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006848 DeviceVector(supportedDevice),
6849 true,
6850 0,
6851 NULL);
6852 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006853 }
6854 // open input streams needed to access attached devices to validate
6855 // mAvailableInputDevices list
6856 for (const auto& inProfile : hwModule->getInputProfiles()) {
6857 if (!inProfile->canOpenNewIo()) {
6858 ALOGE("Invalid Input profile max open count %u for profile %s",
6859 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6860 continue;
6861 }
6862 if (!inProfile->hasSupportedDevices()) {
6863 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6864 continue;
6865 }
6866 // chose first device present in profile's SupportedDevices also part of
6867 // available input devices
6868 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006869 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006870 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006871 ALOGV("%s: Input device list is empty! for profile %s",
6872 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006873 continue;
6874 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306875
6876 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6877 && availProfileDevices.areAllDevicesAttached()) {
6878 ALOGV("%s skip opening input for mmap profile %s", __func__,
6879 inProfile->getTagName().c_str());
6880 continue;
6881 }
6882
Eric Laurentc71b11b2024-06-03 12:54:53 +00006883 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6884 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006885
6886 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6887 status_t status = inputDesc->open(nullptr,
6888 availProfileDevices.itemAt(0),
6889 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306890 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006891 &input);
6892 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306893 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6894 __func__, availProfileDevices.toString().c_str(),
6895 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006896 continue;
6897 }
6898 for (const auto &device : availProfileDevices) {
6899 // give a valid ID to an attached device once confirmed it is reachable
6900 if (!device->isAttached()) {
6901 device->attach(hwModule);
6902 device->importAudioPortAndPickAudioProfile(inProfile, true);
6903 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006904 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006905 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6906 }
6907 }
6908 inputDesc->close();
6909 }
6910 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006911
6912 // Check if spatializer outputs can be closed until used.
6913 // mOutputs vector never contains duplicated outputs at this point.
6914 std::vector<audio_io_handle_t> outputsClosed;
6915 for (size_t i = 0; i < mOutputs.size(); i++) {
6916 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6917 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6918 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6919 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006920 nextAudioPortGeneration();
6921 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6922 if (index >= 0) {
6923 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6924 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6925 patchDesc->getAfHandle(), 0);
6926 mAudioPatches.removeItemsAt(index);
6927 mpClientInterface->onAudioPatchListUpdate();
6928 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006929 desc->close();
6930 }
6931 }
6932 for (auto output : outputsClosed) {
6933 removeOutput(output);
6934 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006935}
6936
Eric Laurent98e38192018-02-15 18:31:53 -08006937void AudioPolicyManager::addOutput(audio_io_handle_t output,
6938 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006939{
Eric Laurent1c333e22014-05-20 10:48:17 -07006940 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006941 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006942 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006943 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006944 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006945}
6946
François Gaffie53615e22015-03-19 09:24:12 +01006947void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6948{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006949 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6950 ALOGV("%s: removing primary output", __func__);
6951 mPrimaryOutput = nullptr;
6952 }
François Gaffie53615e22015-03-19 09:24:12 +01006953 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006954 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006955}
6956
Eric Laurent98e38192018-02-15 18:31:53 -08006957void AudioPolicyManager::addInput(audio_io_handle_t input,
6958 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006959{
Eric Laurent1c333e22014-05-20 10:48:17 -07006960 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006961 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006962}
Eric Laurente552edb2014-03-10 17:42:56 -07006963
François Gaffie11d30102018-11-02 16:09:09 +01006964status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006965 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006966 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006967{
François Gaffie11d30102018-11-02 16:09:09 +01006968 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006969 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006970 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006971
François Gaffie11d30102018-11-02 16:09:09 +01006972 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006973 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006974 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006975 }
Eric Laurente552edb2014-03-10 17:42:56 -07006976
Eric Laurent3b73df72014-03-11 09:06:29 -07006977 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006978 // first call getAudioPort to get the supported attributes from the HAL
6979 struct audio_port_v7 port = {};
6980 device->toAudioPort(&port);
6981 status_t status = mpClientInterface->getAudioPort(&port);
6982 if (status == NO_ERROR) {
6983 device->importAudioPort(port);
6984 }
6985
6986 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006987 for (size_t i = 0; i < mOutputs.size(); i++) {
6988 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006989 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006990 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006991 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6992 mOutputs.keyAt(i), device->toString().c_str());
6993 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006994 }
6995 }
6996 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006997 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006998 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006999 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7000 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01007001 if (profile->supportsDevice(device)) {
7002 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307003 ALOGV("%s(): adding profile %s from module %s",
7004 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07007005 }
7006 }
7007 }
7008
Eric Laurent7b279bb2015-12-14 10:18:23 -08007009 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007010
Eric Laurente552edb2014-03-10 17:42:56 -07007011 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007012 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007013 return BAD_VALUE;
7014 }
7015
7016 // open outputs for matching profiles if needed. Direct outputs are also opened to
7017 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7018 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007019 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007020
7021 // nothing to do if one output is already opened for this profile
7022 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007023 for (j = 0; j < outputs.size(); j++) {
7024 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007025 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007026 // matching profile: save the sample rates, format and channel masks supported
7027 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007028 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007029 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007030 }
Eric Laurente552edb2014-03-10 17:42:56 -07007031 break;
7032 }
7033 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007034 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007035 continue;
7036 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307037 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7038 ALOGV("%s skip opening output for mmap profile %s",
7039 __func__, profile->getTagName().c_str());
7040 continue;
7041 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007042 if (!profile->canOpenNewIo()) {
7043 ALOGW("Max Output number %u already opened for this profile %s",
7044 profile->maxOpenCount, profile->getTagName().c_str());
7045 continue;
7046 }
7047
Eric Laurent83efe1c2017-07-09 16:51:08 -07007048 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007049 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007050 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7051 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007052 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007053 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007054 profiles.removeAt(profile_index);
7055 profile_index--;
7056 } else {
7057 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007058 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007059 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007060 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7061 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007062 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007063 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007064
François Gaffie11d30102018-11-02 16:09:09 +01007065 if (device_distinguishes_on_address(deviceType)) {
7066 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7067 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307068 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7069 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007070 }
Eric Laurente552edb2014-03-10 17:42:56 -07007071 ALOGV("checkOutputsForDevice(): adding output %d", output);
7072 }
7073 }
7074
7075 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007076 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007077 return BAD_VALUE;
7078 }
Eric Laurentd4692962014-05-05 18:13:44 -07007079 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007080 // check if one opened output is not needed any more after disconnecting one device
7081 for (size_t i = 0; i < mOutputs.size(); i++) {
7082 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007083 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007084 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007085 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007086 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007087 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007088 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007089 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7090 mOutputs.keyAt(i));
7091 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007092 }
Eric Laurente552edb2014-03-10 17:42:56 -07007093 }
7094 }
Eric Laurentd4692962014-05-05 18:13:44 -07007095 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007096 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007097 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7098 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007099 if (!profile->supportsDevice(device)) {
7100 continue;
7101 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307102 ALOGV("%s(): clearing direct output profile %s on module %s",
7103 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007104 profile->clearAudioProfiles();
7105 if (!profile->hasDynamicAudioProfile()) {
7106 continue;
7107 }
7108 // When a device is disconnected, if there is an IOProfile that contains dynamic
7109 // profiles and supports the disconnected device, call getAudioPort to repopulate
7110 // the capabilities of the devices that is supported by the IOProfile.
7111 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7112 if (supportedDevice == device ||
7113 !mAvailableOutputDevices.contains(supportedDevice)) {
7114 continue;
7115 }
7116 struct audio_port_v7 port;
7117 supportedDevice->toAudioPort(&port);
7118 status_t status = mpClientInterface->getAudioPort(&port);
7119 if (status == NO_ERROR) {
7120 supportedDevice->importAudioPort(port);
7121 }
Eric Laurente552edb2014-03-10 17:42:56 -07007122 }
7123 }
7124 }
7125 }
7126 return NO_ERROR;
7127}
7128
François Gaffie11d30102018-11-02 16:09:09 +01007129status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007130 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007131{
François Gaffie11d30102018-11-02 16:09:09 +01007132 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007133 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007134 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007135 }
7136
Eric Laurentd4692962014-05-05 18:13:44 -07007137 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007138 sp<AudioInputDescriptor> desc;
7139
jiabinbf5f4262023-04-12 21:48:34 +00007140 // first call getAudioPort to get the supported attributes from the HAL
7141 struct audio_port_v7 port = {};
7142 device->toAudioPort(&port);
7143 status_t status = mpClientInterface->getAudioPort(&port);
7144 if (status == NO_ERROR) {
7145 device->importAudioPort(port);
7146 }
7147
Eric Laurent0dd51852019-04-19 18:18:58 -07007148 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007149 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007150 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007151 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007152 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007153 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007154 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007155
François Gaffie11d30102018-11-02 16:09:09 +01007156 if (profile->supportsDevice(device)) {
7157 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307158 ALOGV("%s : adding profile %s from module %s", __func__,
7159 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007160 }
7161 }
7162 }
7163
Eric Laurent0dd51852019-04-19 18:18:58 -07007164 if (profiles.isEmpty()) {
7165 ALOGW("%s: No input profile available for device %s",
7166 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007167 return BAD_VALUE;
7168 }
7169
7170 // open inputs for matching profiles if needed. Direct inputs are also opened to
7171 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7172 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7173
Eric Laurent1c333e22014-05-20 10:48:17 -07007174 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007175
Eric Laurentd4692962014-05-05 18:13:44 -07007176 // nothing to do if one input is already opened for this profile
7177 size_t input_index;
7178 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7179 desc = mInputs.valueAt(input_index);
7180 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007181 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007182 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007183 }
Eric Laurentd4692962014-05-05 18:13:44 -07007184 break;
7185 }
7186 }
7187 if (input_index != mInputs.size()) {
7188 continue;
7189 }
7190
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307191 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7192 ALOGV("%s skip opening input for mmap profile %s",
7193 __func__, profile->getTagName().c_str());
7194 continue;
7195 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007196 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307197 ALOGW("%s Max Input number %u already opened for this profile %s",
7198 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007199 continue;
7200 }
7201
Eric Laurentc71b11b2024-06-03 12:54:53 +00007202 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007203 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307204 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307205 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7206 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007207
Eric Laurentcf2c0212014-07-25 16:20:43 -07007208 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007209 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007210 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007211 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007212 mpClientInterface->setParameters(input, String8(param));
7213 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007214 }
jiabin12537fc2023-10-12 17:56:08 +00007215 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007216 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307217 ALOGW("%s direct input missing param for profile %s", __func__,
7218 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007219 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007220 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007221 }
7222
Eric Laurent0dd51852019-04-19 18:18:58 -07007223 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007224 addInput(input, desc);
7225 }
7226 } // endif input != 0
7227
Eric Laurentcf2c0212014-07-25 16:20:43 -07007228 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307229 ALOGW("%s could not open input for device %s on profile %s", __func__,
7230 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007231 profiles.removeAt(profile_index);
7232 profile_index--;
7233 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007234 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007235 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007236 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307237 ALOGV("%s: adding input %d for profile %s", __func__,
7238 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007239
7240 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307241 ALOGV("%s: closing input %d for profile %s", __func__,
7242 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007243 closeInput(input);
7244 }
Eric Laurentd4692962014-05-05 18:13:44 -07007245 }
7246 } // end scan profiles
7247
7248 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007249 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007250 return BAD_VALUE;
7251 }
7252 } else {
7253 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007254 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007255 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007256 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007257 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007258 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007259 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007260 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307261 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7262 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007263 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007264 }
7265 }
7266 }
7267 } // end disconnect
7268
7269 return NO_ERROR;
7270}
7271
7272
Eric Laurente0720872014-03-11 09:30:41 -07007273void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007274{
7275 ALOGV("closeOutput(%d)", output);
7276
François Gaffie1c878552018-11-22 16:53:21 +01007277 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7278 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007279 ALOGW("closeOutput() unknown output %d", output);
7280 return;
7281 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007282 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007283 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007284
Eric Laurente552edb2014-03-10 17:42:56 -07007285 // look for duplicated outputs connected to the output being removed.
7286 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007287 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7288 if (dupOutput->isDuplicated() &&
7289 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7290 sp<SwAudioOutputDescriptor> remainingOutput =
7291 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007292 // As all active tracks on duplicated output will be deleted,
7293 // and as they were also referenced on the other output, the reference
7294 // count for their stream type must be adjusted accordingly on
7295 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007296 const bool wasActive = remainingOutput->isActive();
7297 // Note: no-op on the closing output where all clients has already been set inactive
7298 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007299 // stop() will be a no op if the output is still active but is needed in case all
7300 // active streams refcounts where cleared above
7301 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007302 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007303 }
Eric Laurente552edb2014-03-10 17:42:56 -07007304 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7305 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7306
7307 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007308 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007309 }
7310 }
7311
Eric Laurent05b90f82014-08-27 15:32:29 -07007312 nextAudioPortGeneration();
7313
François Gaffie1c878552018-11-22 16:53:21 +01007314 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007315 if (index >= 0) {
7316 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007317 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7318 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007319 mAudioPatches.removeItemsAt(index);
7320 mpClientInterface->onAudioPatchListUpdate();
7321 }
7322
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007323 if (closingOutputWasActive) {
7324 closingOutput->stop();
7325 }
François Gaffie1c878552018-11-22 16:53:21 +01007326 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007327 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007328 for (const auto device : closingOutput->devices()) {
7329 device->setPreferredConfig(nullptr);
7330 }
7331 }
Eric Laurente552edb2014-03-10 17:42:56 -07007332
François Gaffie53615e22015-03-19 09:24:12 +01007333 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007334 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007335 if (closingOutput == mSpatializerOutput) {
7336 mSpatializerOutput.clear();
7337 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007338
7339 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7340 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007341 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007342 bool directOutputOpen = false;
7343 for (size_t i = 0; i < mOutputs.size(); i++) {
7344 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7345 directOutputOpen = true;
7346 break;
7347 }
7348 }
7349 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007350 ALOGV("no direct outputs open, reset MSD patches");
7351 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7352 // how output devices for patching are resolved. Avoid by caching and reusing the
7353 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7354 // devices to patch to. This may be complicated by the fact that devices may become
7355 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007356 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007357 }
7358 }
jiabin220eea12024-05-17 17:55:20 +00007359
7360 if (closingOutput->mPreferredAttrInfo != nullptr) {
7361 closingOutput->mPreferredAttrInfo->resetActiveClient();
7362 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007363}
7364
7365void AudioPolicyManager::closeInput(audio_io_handle_t input)
7366{
7367 ALOGV("closeInput(%d)", input);
7368
7369 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7370 if (inputDesc == NULL) {
7371 ALOGW("closeInput() unknown input %d", input);
7372 return;
7373 }
7374
Eric Laurent6a94d692014-05-20 11:18:06 -07007375 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007376
François Gaffie11d30102018-11-02 16:09:09 +01007377 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007378 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007379 if (index >= 0) {
7380 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007381 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7382 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007383 mAudioPatches.removeItemsAt(index);
7384 mpClientInterface->onAudioPatchListUpdate();
7385 }
7386
François Gaffie6ebbce02023-07-19 13:27:53 +02007387 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007388 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007389 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007390
François Gaffie11d30102018-11-02 16:09:09 +01007391 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7392 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007393 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007394 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007395 }
Eric Laurente552edb2014-03-10 17:42:56 -07007396}
7397
François Gaffie11d30102018-11-02 16:09:09 +01007398SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7399 const DeviceVector &devices,
7400 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007401{
7402 SortedVector<audio_io_handle_t> outputs;
7403
François Gaffie11d30102018-11-02 16:09:09 +01007404 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007405 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007406 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007407 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007408 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007409 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007410 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007411 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007412 outputs.add(openOutputs.keyAt(i));
7413 }
7414 }
7415 return outputs;
7416}
7417
Mikhail Naganov37977152018-07-11 15:54:44 -07007418void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7419{
7420 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7421 // output is suspended before any tracks are moved to it
7422 checkA2dpSuspend();
7423 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007424 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007425 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007426 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007427 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007428 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7429 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7430 // configuration changes will ultimately be rerouted correctly. We can still avoid
7431 // unnecessary rerouting by caching and reusing the arguments to
7432 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7433 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007434 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007435 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007436 // an event that changed routing likely occurred, inform upper layers
7437 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007438}
7439
François Gaffiec005e562018-11-06 15:04:49 +01007440bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7441 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007442{
François Gaffiec005e562018-11-06 15:04:49 +01007443 return mEngine->getProductStrategyForAttributes(lAttr) ==
7444 mEngine->getProductStrategyForAttributes(rAttr);
7445}
7446
Francois Gaffieff1eb522020-05-06 18:37:04 +02007447void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7448{
7449 for (size_t i = 0; i < mAudioSources.size(); i++) {
7450 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7451 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007452 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007453 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007454 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007455 }
7456 }
7457}
7458
7459void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7460{
7461 for (size_t i = 0; i < mAudioSources.size(); i++) {
7462 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7463 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7464 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7465 disconnectAudioSource(sourceDesc);
7466 }
7467 }
7468}
7469
François Gaffiec005e562018-11-06 15:04:49 +01007470void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7471{
7472 auto psId = mEngine->getProductStrategyForAttributes(attr);
7473
7474 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7475 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007476
François Gaffie11d30102018-11-02 16:09:09 +01007477 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7478 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007479
Eric Laurentc209fe42020-06-05 18:11:23 -07007480 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007481 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007482 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007483 // take into account dynamic audio policies related changes: if a client is now associated
7484 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007485 // invalidate clients on outputs that do not support all the newly selected devices for the
7486 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007487 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007488 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007489 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007490 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007491 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007492
Eric Laurentc209fe42020-06-05 18:11:23 -07007493 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7494 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7495 continue;
7496 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007497 if (!desc->supportsAllDevices(newDevices)) {
7498 invalidatedOutputs.push_back(desc);
7499 break;
7500 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007501 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007502 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007503 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7504 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7505 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007506 if (status == OK) {
7507 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7508 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7509 maxLatency = desc->latency();
7510 }
7511 invalidatedOutputs.push_back(desc);
7512 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007513 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007514 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007515 }
7516 }
7517
Eric Laurent56ed8842022-11-15 16:04:41 +01007518 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007519 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7520 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007521 for (audio_io_handle_t srcOut : srcOutputs) {
7522 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007523 if (desc == nullptr) continue;
7524
7525 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007526 maxLatency = desc->latency();
7527 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007528
Eric Laurent56ed8842022-11-15 16:04:41 +01007529 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007530 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007531 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007532 // a client on a non direct outputs has necessarily a linear PCM format
7533 // so we can call selectOutput() safely
7534 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7535 client->flags(),
7536 client->config().format,
7537 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007538 client->config().sample_rate,
7539 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007540 if (newOutput != srcOut) {
7541 invalidate = true;
7542 break;
7543 }
7544 } else {
7545 sp<IOProfile> profile = getProfileForOutput(newDevices,
7546 client->config().sample_rate,
7547 client->config().format,
7548 client->config().channel_mask,
7549 client->flags(),
7550 true /* directOnly */);
7551 if (profile != desc->mProfile) {
7552 invalidate = true;
7553 break;
7554 }
7555 }
7556 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007557 // mute strategy while moving tracks from one output to another
7558 if (invalidate) {
7559 invalidatedOutputs.push_back(desc);
7560 if (desc->isStrategyActive(psId)) {
7561 setStrategyMute(psId, true, desc);
7562 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7563 newDevices.types());
7564 }
Eric Laurente552edb2014-03-10 17:42:56 -07007565 }
François Gaffiec005e562018-11-06 15:04:49 +01007566 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007567 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007568 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007569 }
Eric Laurente552edb2014-03-10 17:42:56 -07007570 }
7571
Eric Laurent56ed8842022-11-15 16:04:41 +01007572 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7573 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7574 std::to_string(srcOutputs[0]).c_str(),
7575 std::to_string(dstOutputs[0]).c_str());
7576
François Gaffiec005e562018-11-06 15:04:49 +01007577 // Move effects associated to this stream from previous output to new output
7578 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007579 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007580 }
François Gaffiec005e562018-11-06 15:04:49 +01007581 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007582 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007583 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007584 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007585 desc->setTracksInvalidatedStatusByStrategy(psId);
7586 }
Eric Laurente552edb2014-03-10 17:42:56 -07007587 }
7588 }
7589}
7590
Eric Laurente0720872014-03-11 09:30:41 -07007591void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007592{
François Gaffiec005e562018-11-06 15:04:49 +01007593 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7594 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7595 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007596 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007597 }
Eric Laurente552edb2014-03-10 17:42:56 -07007598}
7599
Kevin Rocard153f92d2018-12-18 18:33:28 -08007600void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007601 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007602 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007603 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007604 for (size_t i = 0; i < mOutputs.size(); i++) {
7605 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7606 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007607 sp<AudioPolicyMix> primaryMix;
7608 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007609 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007610 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7611 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7612 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007613 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7614 for (auto &secondaryMix : secondaryMixes) {
7615 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7616 if (outputDesc != nullptr &&
7617 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7618 secondaryDescs.push_back(outputDesc);
7619 }
7620 }
7621
jiabinc44b3462022-12-08 12:52:31 -08007622 if (status != OK &&
7623 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7624 // When it failed to query secondary output, only invalidate the client that is not
7625 // MMAP. The reason is that MMAP stream will not support secondary output.
7626 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007627 } else if (!std::equal(
7628 client->getSecondaryOutputs().begin(),
7629 client->getSecondaryOutputs().end(),
7630 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007631 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7632 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007633 // If the format is not PCM, the tracks should be invalidated to get correct
7634 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007635 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007636 } else {
7637 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7638 std::vector<audio_io_handle_t> secondaryOutputIds;
7639 for (const auto &secondaryDesc: secondaryDescs) {
7640 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7641 weakSecondaryDescs.push_back(secondaryDesc);
7642 }
7643 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7644 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007645 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007646 }
7647 }
7648 }
jiabin10a03f12021-05-07 23:46:28 +00007649 if (!trackSecondaryOutputs.empty()) {
7650 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7651 }
jiabinc44b3462022-12-08 12:52:31 -08007652 if (!clientsToInvalidate.empty()) {
7653 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7654 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007655 }
7656}
7657
Eric Laurent2517af32020-11-25 15:31:27 +01007658bool AudioPolicyManager::isScoRequestedForComm() const {
7659 AudioDeviceTypeAddrVector devices;
7660 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7661 for (const auto &device : devices) {
7662 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7663 return true;
7664 }
7665 }
7666 return false;
7667}
7668
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007669bool AudioPolicyManager::isHearingAidUsedForComm() const {
7670 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7671 true /*fromCache*/);
7672 for (const auto &device : devices) {
7673 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7674 return true;
7675 }
7676 }
7677 return false;
7678}
7679
7680
Eric Laurente0720872014-03-11 09:30:41 -07007681void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007682{
François Gaffie53615e22015-03-19 09:24:12 +01007683 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007684 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007685 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007686 return;
7687 }
7688
Eric Laurent3a4311c2014-03-17 12:00:47 -07007689 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007690 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7691 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007692 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007693
7694 // if suspended, restore A2DP output if:
7695 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007696 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007697 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007698 //
Eric Laurentf732e072016-08-03 19:30:28 -07007699 // if not suspended, suspend A2DP output if:
7700 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007701 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007702 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007703 //
7704 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007705 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007706 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007707 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007708 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007709
7710 mpClientInterface->restoreOutput(a2dpOutput);
7711 mA2dpSuspended = false;
7712 }
7713 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007714 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007715 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007716 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007717 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007718
7719 mpClientInterface->suspendOutput(a2dpOutput);
7720 mA2dpSuspended = true;
7721 }
7722 }
7723}
7724
François Gaffie11d30102018-11-02 16:09:09 +01007725DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7726 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007727{
François Gaffiedb1755b2023-09-01 11:50:35 +02007728 if (outputDesc == nullptr) {
7729 return DeviceVector{};
7730 }
François Gaffie11d30102018-11-02 16:09:09 +01007731
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007732 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007733 if (index >= 0) {
7734 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007735 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007736 ALOGV("%s device %s forced by patch %d", __func__,
7737 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7738 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007739 }
7740 }
7741
Dean Wheatley514b4312020-06-17 21:45:00 +10007742 // Do not retrieve engine device for outputs through MSD
7743 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7744 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7745 return outputDesc->devices();
7746 }
7747
Eric Laurent97ac8712018-07-27 18:59:02 -07007748 // Honor explicit routing requests only if no client using default routing is active on this
7749 // input: a specific app can not force routing for other apps by setting a preferred device.
7750 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007751 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007752 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007753 if (device != nullptr) {
7754 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007755 }
7756
François Gaffiea807ef92018-11-05 10:44:33 +01007757 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7758 // of setForceUse / Default Bus device here
7759 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7760 if (device != nullptr) {
7761 return DeviceVector(device);
7762 }
7763
François Gaffiedb1755b2023-09-01 11:50:35 +02007764 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007765 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7766 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307767 auto hasStreamActive = [&](auto stream) {
7768 return hasStream(streams, stream) && isStreamActive(stream, 0);
7769 };
Eric Laurent484e9272018-06-07 17:29:23 -07007770
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307771 auto doGetOutputDevicesForVoice = [&]() {
7772 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007773 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307774 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007775 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7776 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307777 };
7778
7779 // With low-latency playing on speaker, music on WFD, when the first low-latency
7780 // output is stopped, getNewOutputDevices checks for a product strategy
7781 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007782 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307783 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7784 // stream is associated to the output descriptor.
7785 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7786 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7787 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7788 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007789 // Retrieval of devices for voice DL is done on primary output profile, cannot
7790 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007791 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007792 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7793 break;
7794 }
Eric Laurente552edb2014-03-10 17:42:56 -07007795 }
François Gaffiec005e562018-11-06 15:04:49 +01007796 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007797 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007798}
7799
François Gaffie11d30102018-11-02 16:09:09 +01007800sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7801 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007802{
François Gaffie11d30102018-11-02 16:09:09 +01007803 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007804
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007805 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007806 if (index >= 0) {
7807 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007808 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007809 ALOGV("getNewInputDevice() device %s forced by patch %d",
7810 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7811 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007812 }
7813 }
7814
Eric Laurent97ac8712018-07-27 18:59:02 -07007815 // Honor explicit routing requests only if no client using default routing is active on this
7816 // input: a specific app can not force routing for other apps by setting a preferred device.
7817 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007818 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7819 if (device != nullptr) {
7820 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007821 }
7822
Eric Laurentdc95a252018-04-12 12:46:56 -07007823 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007824 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007825 audio_attributes_t attributes;
7826 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007827 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007828 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7829 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007830 attributes = topClient->attributes();
7831 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007832 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007833 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007834 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7835 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007836 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007837 }
7838
Francois Gaffie716e1432019-01-14 16:58:59 +01007839 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7840 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007841 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007842 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007843 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007844 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007845
Eric Laurente552edb2014-03-10 17:42:56 -07007846 return device;
7847}
7848
Eric Laurent794fde22016-03-11 09:50:45 -08007849bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7850 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007851 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007852}
7853
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007854status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007855 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007856 if (devices == nullptr) {
7857 return BAD_VALUE;
7858 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007859
Andy Hung6d23c0f2022-02-16 09:37:15 -08007860 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007861 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7862 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007863 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007864 for (const auto& device : curDevices) {
7865 devices->push_back(device->getDeviceTypeAddr());
7866 }
7867 return NO_ERROR;
7868}
7869
Eric Laurente0720872014-03-11 09:30:41 -07007870void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007871 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007872 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007873 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007874 updateDevicesAndOutputs();
7875 break;
7876 default:
7877 break;
7878 }
7879}
7880
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007881uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007882
7883 // skip beacon mute management if a dedicated TTS output is available
7884 if (mTtsOutputAvailable) {
7885 return 0;
7886 }
7887
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007888 switch(event) {
7889 case STARTING_OUTPUT:
7890 mBeaconMuteRefCount++;
7891 break;
7892 case STOPPING_OUTPUT:
7893 if (mBeaconMuteRefCount > 0) {
7894 mBeaconMuteRefCount--;
7895 }
7896 break;
7897 case STARTING_BEACON:
7898 mBeaconPlayingRefCount++;
7899 break;
7900 case STOPPING_BEACON:
7901 if (mBeaconPlayingRefCount > 0) {
7902 mBeaconPlayingRefCount--;
7903 }
7904 break;
7905 }
7906
7907 if (mBeaconMuteRefCount > 0) {
7908 // any playback causes beacon to be muted
7909 return setBeaconMute(true);
7910 } else {
7911 // no other playback: unmute when beacon starts playing, mute when it stops
7912 return setBeaconMute(mBeaconPlayingRefCount == 0);
7913 }
7914}
7915
7916uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7917 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7918 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7919 // keep track of muted state to avoid repeating mute/unmute operations
7920 if (mBeaconMuted != mute) {
7921 // mute/unmute AUDIO_STREAM_TTS on all outputs
7922 ALOGV("\t muting %d", mute);
7923 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007924 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7925 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7926 ALOGV("\t no tts volume source available");
7927 return 0;
7928 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007929 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007930 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa1e865e62024-08-15 19:11:42 -07007931 setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
7932 DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007933 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007934 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007935 maxLatency = latency;
7936 }
7937 }
7938 mBeaconMuted = mute;
7939 return maxLatency;
7940 }
7941 return 0;
7942}
7943
Eric Laurente0720872014-03-11 09:30:41 -07007944void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007945{
François Gaffiec005e562018-11-06 15:04:49 +01007946 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007947 mPreviousOutputs = mOutputs;
7948}
7949
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007950uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007951 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007952 uint32_t delayMs)
7953{
7954 // mute/unmute strategies using an incompatible device combination
7955 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7956 // if unmuting, unmute only after the specified delay
7957 if (outputDesc->isDuplicated()) {
7958 return 0;
7959 }
7960
7961 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007962 DeviceVector devices = outputDesc->devices();
7963 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007964
François Gaffiec005e562018-11-06 15:04:49 +01007965 auto productStrategies = mEngine->getOrderedProductStrategies();
7966 for (const auto &productStrategy : productStrategies) {
7967 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7968 DeviceVector curDevices =
7969 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7970 curDevices = curDevices.filter(outputDesc->supportedDevices());
7971 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007972 bool doMute = false;
7973
François Gaffiec005e562018-11-06 15:04:49 +01007974 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007975 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007976 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7977 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007978 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007979 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007980 }
Eric Laurent99401132014-05-07 19:48:15 -07007981 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007982 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007983 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007984 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007985 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007986 continue;
7987 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307988 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007989 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7990 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7991 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007992 if (mute) {
7993 // FIXME: should not need to double latency if volume could be applied
7994 // immediately by the audioflinger mixer. We must account for the delay
7995 // between now and the next time the audioflinger thread for this output
7996 // will process a buffer (which corresponds to one buffer size,
7997 // usually 1/2 or 1/4 of the latency).
7998 if (muteWaitMs < desc->latency() * 2) {
7999 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07008000 }
8001 }
8002 }
8003 }
8004 }
8005 }
8006
Eric Laurent99401132014-05-07 19:48:15 -07008007 // temporary mute output if device selection changes to avoid volume bursts due to
8008 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01008009 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07008010 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008011
Eric Laurentdc462862016-07-19 12:29:53 -07008012 if (muteWaitMs < tempMuteWaitMs) {
8013 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07008014 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008015
8016 // If recommended duration is defined, replace temporary mute duration to avoid
8017 // truncated notifications at beginning, which depends on duration of changing path in HAL.
8018 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8019 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8020 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8021 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8022
François Gaffieaaac0fd2018-11-22 17:56:39 +01008023 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8024 // make sure that we do not start the temporary mute period too early in case of
8025 // delayed device change
Vlad Popa1e865e62024-08-15 19:11:42 -07008026 setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8027 setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8028 delayMs + tempMuteDurationMs,
8029 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008030 }
8031 }
8032
Eric Laurente552edb2014-03-10 17:42:56 -07008033 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8034 if (muteWaitMs > delayMs) {
8035 muteWaitMs -= delayMs;
8036 usleep(muteWaitMs * 1000);
8037 return muteWaitMs;
8038 }
8039 return 0;
8040}
8041
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308042uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8043 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008044 const DeviceVector &devices,
8045 bool force,
8046 int delayMs,
8047 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008048 bool requiresMuteCheck, bool requiresVolumeCheck,
8049 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008050{
jiabin3ff8d7d2022-12-13 06:27:44 +00008051 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308052 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8053 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8054 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008055 uint32_t muteWaitMs;
8056
8057 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308058 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008059 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308060 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008061 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008062 return muteWaitMs;
8063 }
Eric Laurente552edb2014-03-10 17:42:56 -07008064
8065 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008066 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008067 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008068 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008069
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308070 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8071 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008072
8073 if (!filteredDevices.isEmpty()) {
8074 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008075 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008076
8077 // if the outputs are not materially active, there is no need to mute.
8078 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008079 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008080 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308081 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8082 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008083 muteWaitMs = 0;
8084 }
Eric Laurente552edb2014-03-10 17:42:56 -07008085
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008086 bool outputRouted = outputDesc->isRouted();
8087
Eric Laurent79ea9582020-06-11 18:49:24 -07008088 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8089 // output profile or if new device is not supported AND previous device(s) is(are) still
8090 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008091 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308092 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8093 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008094 // restore previous device after evaluating strategy mute state
8095 outputDesc->setDevices(prevDevices);
8096 return muteWaitMs;
8097 }
8098
Eric Laurente552edb2014-03-10 17:42:56 -07008099 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008100 // the requested device is AUDIO_DEVICE_NONE
8101 // OR the requested device is the same as current device
8102 // AND force is not specified
8103 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008104 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008105 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308106 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8107 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8108 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008109 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308110 ALOGV("%s %s setting same device on routed output, force apply volumes",
8111 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008112 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8113 }
Eric Laurente552edb2014-03-10 17:42:56 -07008114 return muteWaitMs;
8115 }
8116
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308117 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8118 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008119
Eric Laurente552edb2014-03-10 17:42:56 -07008120 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008121 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008122 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008123 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008124 PatchBuilder patchBuilder;
8125 patchBuilder.addSource(outputDesc);
8126 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8127 for (const auto &filteredDevice : filteredDevices) {
8128 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008129 }
8130
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008131 // Add half reported latency to delayMs when muteWaitMs is null in order
8132 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008133 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8134 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8135 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008136 }
Eric Laurente552edb2014-03-10 17:42:56 -07008137
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008138 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8139 if (!skipMuteDelay) {
8140 // update stream volumes according to new device
8141 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8142 }
Eric Laurente552edb2014-03-10 17:42:56 -07008143
8144 return muteWaitMs;
8145}
8146
Eric Laurentc75307b2015-03-17 15:29:32 -07008147status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008148 int delayMs,
8149 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008150{
Eric Laurent6a94d692014-05-20 11:18:06 -07008151 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008152 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8153 return INVALID_OPERATION;
8154 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008155 if (patchHandle) {
8156 index = mAudioPatches.indexOfKey(*patchHandle);
8157 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008158 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008159 }
8160 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008161 return INVALID_OPERATION;
8162 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008163 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008164 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008165 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008166 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008167 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008168 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008169 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008170 return status;
8171}
8172
8173status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008174 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008175 bool force,
8176 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008177{
8178 status_t status = NO_ERROR;
8179
Eric Laurent1f2f2232014-06-02 12:01:23 -07008180 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008181 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8182 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008183
François Gaffie11d30102018-11-02 16:09:09 +01008184 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008185 PatchBuilder patchBuilder;
8186 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008187 // AUDIO_SOURCE_HOTWORD is for internal use only:
8188 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008189 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8190 auto result = usecase;
8191 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8192 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8193 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008194 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008195 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008196 if (audio_is_remote_submix_device(device->type())) {
8197 // remote submix HAL does not support audio conversion, need source device
8198 // audio config to match the sink input descriptor audio config, otherwise AIDL
8199 // HAL patching will fail
8200 audio_port_config srcDevicePortConfig = {};
8201 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8202 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8203 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8204 srcDevicePortConfig.format = inputDesc->getFormat();
8205 patchBuilder.addSource(srcDevicePortConfig);
8206 } else {
8207 patchBuilder.addSource(device);
8208 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008209 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008210 }
8211 }
8212 return status;
8213}
8214
Eric Laurent6a94d692014-05-20 11:18:06 -07008215status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8216 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008217{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008218 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008219 ssize_t index;
8220 if (patchHandle) {
8221 index = mAudioPatches.indexOfKey(*patchHandle);
8222 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008223 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008224 }
8225 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008226 return INVALID_OPERATION;
8227 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008228 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008229 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008230 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008231 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008232 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008233 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008234 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008235 return status;
8236}
8237
François Gaffie11d30102018-11-02 16:09:09 +01008238sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008239 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008240 audio_format_t& format,
8241 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008242 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008243{
8244 // Choose an input profile based on the requested capture parameters: select the first available
8245 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008246 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008247
Atneya Nair0f0a8032022-12-12 16:20:12 -08008248 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8249 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8250 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8251
8252 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008253
jiabin2fd710d2022-05-02 23:20:22 +00008254 for (;;) {
jiabin91beb492024-10-16 21:53:36 +00008255 sp<IOProfile> inexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008256 uint32_t inexactSamplingRate = 0;
8257 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8258 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008259 uint32_t updatedSamplingRate = 0;
8260 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8261 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8262 for (const auto& hwModule : mHwModules) {
8263 for (const auto& profile : hwModule->getInputProfiles()) {
8264 // profile->log();
8265 //updatedFormat = format;
jiabin91beb492024-10-16 21:53:36 +00008266 auto compatibleScore = profile->getCompatibilityScore(
jiabin66acc432024-02-06 00:57:36 +00008267 DeviceVector(device),
8268 samplingRate,
8269 &updatedSamplingRate,
8270 format,
8271 &updatedFormat,
8272 channelMask,
8273 &updatedChannelMask,
8274 // FIXME ugly cast
jiabin91beb492024-10-16 21:53:36 +00008275 (audio_output_flags_t) flags);
8276 if (compatibleScore == IOProfile::EXACT_MATCH) {
jiabin66acc432024-02-06 00:57:36 +00008277 samplingRate = updatedSamplingRate;
8278 format = updatedFormat;
8279 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008280 return profile;
jiabin91beb492024-10-16 21:53:36 +00008281 } else if ((flags != AUDIO_INPUT_FLAG_NONE
8282 && compatibleScore == IOProfile::PARTIAL_MATCH_WITH_FLAG)
8283 || (inexact == nullptr && compatibleScore != IOProfile::NO_MATCH)) {
8284 inexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008285 inexactSamplingRate = updatedSamplingRate;
8286 inexactFormat = updatedFormat;
8287 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008288 }
8289 }
8290 }
8291
jiabin91beb492024-10-16 21:53:36 +00008292 if (inexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008293 samplingRate = inexactSamplingRate;
8294 format = inexactFormat;
8295 channelMask = inexactChannelMask;
jiabin91beb492024-10-16 21:53:36 +00008296 return inexact;
jiabin2fd710d2022-05-02 23:20:22 +00008297 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8298 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8299 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8300 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8301 flags = AUDIO_INPUT_FLAG_NONE;
8302 } else { // fail
8303 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8304 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8305 samplingRate, format, channelMask, oriFlags);
8306 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008307 }
8308 }
jiabin2fd710d2022-05-02 23:20:22 +00008309
8310 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008311}
8312
Vlad Popa87e0e582024-05-20 18:49:20 -07008313float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8314 VolumeSource volumeSource,
8315 int index,
8316 const DeviceTypeSet &deviceTypes)
8317{
8318 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8319 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8320 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8321
8322 if (com_android_media_audio_abs_volume_index_fix()) {
Vlad Popa08502d82024-10-22 20:17:47 -07008323 const auto it = mAbsoluteVolumeDrivingStreams.find(volumeDevice);
8324 if (it != mAbsoluteVolumeDrivingStreams.end()) {
8325 audio_attributes_t attributesToDriveAbs = it->second;
Vlad Popa87e0e582024-05-20 18:49:20 -07008326 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8327 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8328 ALOGD("%s: no group matching with %s", __FUNCTION__,
8329 toString(attributesToDriveAbs).c_str());
8330 return volumeDb;
8331 }
8332
8333 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8334 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8335 if (vsToDriveAbs == volumeSource) {
8336 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008337 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008338 } else {
8339 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8340 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8341 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8342 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8343 curvesAbs.getVolumeIndexMax());
8344 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8345 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8346 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8347 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8348 return newVolumeDb;
8349 }
8350 }
8351 return volumeDb;
8352 } else {
8353 return volumeDb;
8354 }
8355}
8356
François Gaffieaaac0fd2018-11-22 17:56:39 +01008357float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8358 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008359 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008360 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008361 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008362 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008363{
Vlad Popa9d482762024-06-21 16:40:23 -07008364 float volumeDb;
8365 if (adjustAttenuation) {
8366 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8367 } else {
8368 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8369 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008370 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8371 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8372
8373 if (!computeInternalInteraction) {
8374 return volumeDb;
8375 }
8376
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008377 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8378 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8379 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8380 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008381 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8382 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8383 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8384 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8385 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008386 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008387 mOutputs.isActive(ringVolumeSrc, 0)) {
8388 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008389 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008390 adjustAttenuation,
8391 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008392 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008393 }
8394
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008395 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008396 if ((volumeSource != callVolumeSrc && (isInCall() ||
8397 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008398 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008399 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8400 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008401 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8402 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8403 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008404 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008405 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008406 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008407 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008408 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008409 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008410 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008411 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8412 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8413 // programmatically muted.
8414 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8415 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8416 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008417 bool exemptFromCapping =
8418 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8419 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008420 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8421 volumeSource, volumeDb);
8422 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008423 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8424 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8425 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008426 }
8427 }
Eric Laurente552edb2014-03-10 17:42:56 -07008428 // if a headset is connected, apply the following rules to ring tones and notifications
8429 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008430 // - always attenuate notifications volume by 6dB
8431 // - attenuate ring tones volume by 6dB unless music is not playing and
8432 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008433 // - if music is playing, always limit the volume to current music volume,
8434 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008435 if (!Intersection(deviceTypes,
8436 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8437 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008438 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8439 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008440 ((volumeSource == alarmVolumeSrc ||
8441 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008442 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8443 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8444 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008445 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8446 curves.canBeMuted()) {
8447
Eric Laurente552edb2014-03-10 17:42:56 -07008448 // when the phone is ringing we must consider that music could have been paused just before
8449 // by the music application and behave as if music was active if the last music track was
8450 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008451 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8452 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008453 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008454 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008455 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8456 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008457 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008458 float musicVolDb = computeVolume(musicCurves,
8459 musicVolumeSrc,
8460 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008461 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008462 adjustAttenuation,
8463 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008464 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8465 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8466 if (volumeDb > minVolDb) {
8467 volumeDb = minVolDb;
8468 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008469 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008470 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8471 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008472 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8473 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8474 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8475 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008476 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008477 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008478 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8479 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008480 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8481 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008482 }
8483 }
jiabin9a3361e2019-10-01 09:38:30 -07008484 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008485 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008486 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008487 }
8488 }
8489
François Gaffie43c73442018-11-08 08:21:55 +01008490 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008491}
8492
Eric Laurent3839bc02018-07-10 18:33:34 -07008493int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008494 VolumeSource fromVolumeSource,
8495 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008496{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008497 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008498 return srcIndex;
8499 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008500 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8501 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008502 float minSrc = (float)srcCurves.getVolumeIndexMin();
8503 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8504 float minDst = (float)dstCurves.getVolumeIndexMin();
8505 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008506
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008507 // preserve mute request or correct range
8508 if (srcIndex < minSrc) {
8509 if (srcIndex == 0) {
8510 return 0;
8511 }
8512 srcIndex = minSrc;
8513 } else if (srcIndex > maxSrc) {
8514 srcIndex = maxSrc;
8515 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008516 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8517}
8518
François Gaffieaaac0fd2018-11-22 17:56:39 +01008519status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8520 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008521 int index,
8522 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008523 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008524 int delayMs,
8525 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008526{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008527 // APM is single threaded, and single instance.
8528 static std::set<IVolumeCurves*> invalidCurvesReported;
8529
François Gaffieaaac0fd2018-11-22 17:56:39 +01008530 // do not change actual attributes volume if the attributes is muted
Vlad Popa1e865e62024-08-15 19:11:42 -07008531 if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008532 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8533 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008534 return NO_ERROR;
8535 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008536
Eric Laurentae6e88c2024-01-10 14:42:57 +01008537 bool isVoiceVolSrc;
8538 bool isBtScoVolSrc;
8539 if (!isVolumeConsistentForCalls(
8540 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008541 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008542 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008543 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008544 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008545
jiabin9a3361e2019-10-01 09:38:30 -07008546 if (deviceTypes.empty()) {
8547 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008548 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008549 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008550 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008551 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008552
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008553 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008554 if (!invalidCurvesReported.count(&curves)) {
8555 invalidCurvesReported.insert(&curves);
8556 String8 dump;
8557 curves.dump(&dump);
8558 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8559 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008560 return BAD_VALUE;
8561 }
8562
jiabin9a3361e2019-10-01 09:38:30 -07008563 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008564 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008565 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008566 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008567 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8568 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008569 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8570 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008571 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008572 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008573
8574 bool muted;
8575 if (!com_android_media_audio_ring_my_car()) {
8576 muted = (index == 0) && (volumeDb != 0.0f);
8577 } else {
8578 muted = curves.isMuted();
8579 }
Eric Laurent31a428a2023-08-11 12:16:28 +02008580 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8581 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008582
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008583 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008584 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8585 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8586 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008587 }
Eric Laurente552edb2014-03-10 17:42:56 -07008588 return NO_ERROR;
8589}
8590
Eric Laurentae6e88c2024-01-10 14:42:57 +01008591void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008592 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008593 float voiceVolume;
Vlad Popa1e865e62024-08-15 19:11:42 -07008594
8595 if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8596 index = 0;
8597 }
8598
chenxin2095559032024-06-15 13:59:29 +08008599 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008600 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008601 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008602 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8603 } else {
8604 voiceVolume = index == 0 ? 0.0 : 1.0;
8605 }
8606 if (voiceVolume != mLastVoiceVolume) {
8607 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8608 mLastVoiceVolume = voiceVolume;
8609 }
8610}
8611
8612bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8613 const DeviceTypeSet& deviceTypes,
8614 bool& isVoiceVolSrc,
8615 bool& isBtScoVolSrc,
8616 const char* caller) {
8617 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008618 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8619
Eric Laurentae6e88c2024-01-10 14:42:57 +01008620 const bool isScoRequested = isScoRequestedForComm();
8621 const bool isHAUsed = isHearingAidUsedForComm();
8622
Vlad Popa695b76b2024-06-14 16:49:25 -07008623 if (com_android_media_audio_replace_stream_bt_sco()) {
8624 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8625 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8626 (isScoRequested || isHAUsed);
8627 return true;
8628 }
8629
8630 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008631 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8632
8633 if ((callVolSrc != btScoVolSrc) &&
8634 ((isVoiceVolSrc && isScoRequested) ||
8635 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8636 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8637 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8638 volumeSource, isScoRequested ? " " : " not ");
8639 return false;
8640 }
8641 return true;
8642}
8643
Eric Laurentc75307b2015-03-17 15:29:32 -07008644void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008645 const DeviceTypeSet& deviceTypes,
8646 int delayMs,
8647 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008648{
jiabincd510522020-01-22 09:40:55 -08008649 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008650 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8651 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
Vlad Popa1e865e62024-08-15 19:11:42 -07008652 checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
jiabin9a3361e2019-10-01 09:38:30 -07008653 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008654 }
8655}
8656
François Gaffiec005e562018-11-06 15:04:49 +01008657void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8658 bool on,
8659 const sp<AudioOutputDescriptor>& outputDesc,
8660 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008661 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008662{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008663 std::vector<VolumeSource> sourcesToMute;
8664 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8665 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8666 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008667 VolumeSource source = toVolumeSource(attributes, false);
8668 if ((source != VOLUME_SOURCE_NONE) &&
8669 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8670 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008671 sourcesToMute.push_back(source);
8672 }
Eric Laurente552edb2014-03-10 17:42:56 -07008673 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008674 for (auto source : sourcesToMute) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008675 setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008676 }
8677
Eric Laurente552edb2014-03-10 17:42:56 -07008678}
8679
Vlad Popa1e865e62024-08-15 19:11:42 -07008680void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8681 bool on,
8682 const sp<AudioOutputDescriptor>& outputDesc,
8683 int delayMs,
8684 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008685{
jiabin9a3361e2019-10-01 09:38:30 -07008686 if (deviceTypes.empty()) {
8687 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008688 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008689 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008690 if (on) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008691 if (!outputDesc->isMutedInternally(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008692 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008693 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008694 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8695 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008696 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008697 }
8698 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008699 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8700 // ignored
8701 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008702 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07008703 if (!outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008704 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008705 return;
8706 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008707 if (outputDesc->decMuteCount(volumeSource) == 0) {
8708 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008709 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008710 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008711 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008712 delayMs);
8713 }
8714 }
8715}
8716
François Gaffie53615e22015-03-19 09:24:12 +01008717bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8718{
François Gaffiec005e562018-11-06 15:04:49 +01008719 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008720 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8721 return true;
8722 }
8723
8724 // has known usage?
8725 switch (paa->usage) {
8726 case AUDIO_USAGE_UNKNOWN:
8727 case AUDIO_USAGE_MEDIA:
8728 case AUDIO_USAGE_VOICE_COMMUNICATION:
8729 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8730 case AUDIO_USAGE_ALARM:
8731 case AUDIO_USAGE_NOTIFICATION:
8732 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8733 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8734 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8735 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8736 case AUDIO_USAGE_NOTIFICATION_EVENT:
8737 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8738 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8739 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8740 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008741 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008742 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008743 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008744 case AUDIO_USAGE_EMERGENCY:
8745 case AUDIO_USAGE_SAFETY:
8746 case AUDIO_USAGE_VEHICLE_STATUS:
8747 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008748 break;
8749 default:
8750 return false;
8751 }
8752 return true;
8753}
8754
François Gaffie2110e042015-03-24 08:41:51 +01008755audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8756{
8757 return mEngine->getForceUse(usage);
8758}
8759
Eric Laurent96d1dda2022-03-14 17:14:19 +01008760bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008761 return isStateInCall(mEngine->getPhoneState());
8762}
8763
Eric Laurent96d1dda2022-03-14 17:14:19 +01008764bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008765 return is_state_in_call(state);
8766}
8767
Eric Laurentf9cccec2022-11-16 19:12:00 +01008768bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008769 audio_mode_t mode = mEngine->getPhoneState();
8770 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008771 || (mode == AUDIO_MODE_CALL_SCREEN)
8772 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008773}
8774
Eric Laurentf9cccec2022-11-16 19:12:00 +01008775bool AudioPolicyManager::isInCallOrScreening() const {
8776 audio_mode_t mode = mEngine->getPhoneState();
8777 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8778}
8779
Eric Laurentd60560a2015-04-10 11:31:20 -07008780void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8781{
8782 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008783 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008784 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008785 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008786 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008787 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008788 }
8789 }
8790
8791 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8792 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8793 bool release = false;
8794 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8795 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8796 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8797 source->ext.device.type == deviceDesc->type()) {
8798 release = true;
8799 }
8800 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008801 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008802 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8803 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8804 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008805 sink->ext.device.type == deviceDesc->type() &&
8806 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8807 || strncmp(sink->ext.device.address, address,
8808 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008809 release = true;
8810 }
8811 }
8812 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008813 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8814 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008815 }
8816 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008817
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008818 mInputs.clearSessionRoutesForDevice(deviceDesc);
8819
Francois Gaffie716e1432019-01-14 16:58:59 +01008820 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008821}
8822
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008823void AudioPolicyManager::modifySurroundFormats(
8824 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008825 std::unordered_set<audio_format_t> enforcedSurround(
8826 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008827 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008828 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008829 allSurround.insert(pair.first);
8830 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8831 }
Phil Burk09bc4612016-02-24 15:58:15 -08008832
8833 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8834 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008835 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008836 // This is the resulting set of formats depending on the surround mode:
8837 // 'all surround' = allSurround
8838 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8839 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8840 // 'manual surround' = mManualSurroundFormats
8841 // AUTO: formats v 'enforced surround'
8842 // ALWAYS: formats v 'all surround' v 'enforced surround'
8843 // NEVER: formats ^ 'non-surround'
8844 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008845
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008846 std::unordered_set<audio_format_t> formatSet;
8847 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8848 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008849 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008850 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008851 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008852 formatSet.insert(*formatIter);
8853 }
8854 }
8855 } else {
8856 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8857 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008858 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008859
jiabin81772902018-04-02 17:52:27 -07008860 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008861 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008862 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8863 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8864 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008865 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008866 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8867 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8868 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008869 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008870 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008871 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008872 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008873 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008874 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008875}
8876
jiabin06e4bab2019-07-29 10:13:34 -07008877void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8878 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008879 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8880 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8881
8882 // If NEVER, then remove support for channelMasks > stereo.
8883 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008884 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8885 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008886 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008887 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008888 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008889 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008890 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008891 }
8892 }
jiabin81772902018-04-02 17:52:27 -07008893 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8894 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8895 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008896 bool supports5dot1 = false;
8897 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008898 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008899 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8900 supports5dot1 = true;
8901 break;
8902 }
8903 }
8904 // If not then add 5.1 support.
8905 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008906 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008907 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008908 }
Phil Burk09bc4612016-02-24 15:58:15 -08008909 }
8910}
8911
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008912void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008913 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008914 const sp<IOProfile>& profile) {
8915 if (!profile->hasDynamicAudioProfile()) {
8916 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008917 }
François Gaffie112b0af2015-11-19 16:13:25 +01008918
jiabin12537fc2023-10-12 17:56:08 +00008919 audio_port_v7 devicePort;
8920 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008921
jiabin12537fc2023-10-12 17:56:08 +00008922 audio_port_v7 mixPort;
8923 profile->toAudioPort(&mixPort);
8924 mixPort.ext.mix.handle = ioHandle;
8925
8926 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8927 if (status != NO_ERROR) {
8928 ALOGE("%s failed to query the attributes of the mix port", __func__);
8929 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008930 }
jiabin12537fc2023-10-12 17:56:08 +00008931
8932 std::set<audio_format_t> supportedFormats;
8933 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8934 supportedFormats.insert(mixPort.audio_profiles[i].format);
8935 }
8936 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8937 mReportedFormatsMap[devDesc] = formats;
8938
8939 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008940 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8941 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008942 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8943 modifySurroundFormats(devDesc, &formats);
8944 size_t modifiedNumProfiles = 0;
8945 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8946 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8947 formats.end()) {
8948 // Skip the format that is not present after modifying surround formats.
8949 continue;
8950 }
8951 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8952 sizeof(struct audio_profile));
8953 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8954 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8955 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8956 modifySurroundChannelMasks(&channels);
8957 std::copy(channels.begin(), channels.end(),
8958 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8959 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8960 }
8961 mixPort.num_audio_profiles = modifiedNumProfiles;
8962 }
8963 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008964}
Eric Laurentd60560a2015-04-10 11:31:20 -07008965
Mikhail Naganovdc769682018-05-04 15:34:08 -07008966status_t AudioPolicyManager::installPatch(const char *caller,
8967 audio_patch_handle_t *patchHandle,
8968 AudioIODescriptorInterface *ioDescriptor,
8969 const struct audio_patch *patch,
8970 int delayMs)
8971{
8972 ssize_t index = mAudioPatches.indexOfKey(
8973 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8974 *patchHandle : ioDescriptor->getPatchHandle());
8975 sp<AudioPatch> patchDesc;
8976 status_t status = installPatch(
8977 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8978 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008979 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008980 }
8981 return status;
8982}
8983
8984status_t AudioPolicyManager::installPatch(const char *caller,
8985 ssize_t index,
8986 audio_patch_handle_t *patchHandle,
8987 const struct audio_patch *patch,
8988 int delayMs,
8989 uid_t uid,
8990 sp<AudioPatch> *patchDescPtr)
8991{
8992 sp<AudioPatch> patchDesc;
8993 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8994 if (index >= 0) {
8995 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008996 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008997 }
8998
8999 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
9000 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
9001 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
9002 if (status == NO_ERROR) {
9003 if (index < 0) {
9004 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01009005 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009006 } else {
9007 patchDesc->mPatch = *patch;
9008 }
François Gaffieafd4cea2019-11-18 15:50:22 +01009009 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009010 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009011 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009012 }
9013 nextAudioPortGeneration();
9014 mpClientInterface->onAudioPatchListUpdate();
9015 }
9016 if (patchDescPtr) *patchDescPtr = patchDesc;
9017 return status;
9018}
9019
jiabinbce0c1d2020-10-05 11:20:18 -07009020bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9021{
9022 const TrackClientVector activeClients = output->getActiveClients();
9023 if (activeClients.empty()) {
9024 return true;
9025 }
9026 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9027 if (index < 0) {
9028 ALOGE("%s, no audio patch found while there are active clients on output %d",
9029 __func__, output->getId());
9030 return false;
9031 }
9032 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9033 DeviceVector routedDevices;
9034 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9035 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9036 patchDesc->mPatch.sinks[i].id);
9037 if (device == nullptr) {
9038 ALOGE("%s, no audio device found with id(%d)",
9039 __func__, patchDesc->mPatch.sinks[i].id);
9040 return false;
9041 }
9042 routedDevices.add(device);
9043 }
9044 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009045 if (client->isInvalid()) {
9046 // No need to take care about invalidated clients.
9047 continue;
9048 }
jiabinbce0c1d2020-10-05 11:20:18 -07009049 sp<DeviceDescriptor> preferredDevice =
9050 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9051 if (mEngine->getOutputDevicesForAttributes(
9052 client->attributes(), preferredDevice, false) == routedDevices) {
9053 return false;
9054 }
9055 }
9056 return true;
9057}
9058
9059sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009060 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009061 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9062 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009063{
9064 for (const auto& device : devices) {
9065 // TODO: This should be checking if the profile supports the device combo.
9066 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009067 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9068 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009069 return nullptr;
9070 }
9071 }
9072 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9073 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009074 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009075 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009076 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009077 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009078 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009079 return nullptr;
9080 }
jiabin14b50cc2023-12-13 19:01:52 +00009081 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9082 auto portConfig = desc->getConfig();
9083 for (const auto& device : devices) {
9084 device->setPreferredConfig(&portConfig);
9085 }
9086 }
jiabinbce0c1d2020-10-05 11:20:18 -07009087
9088 // Here is where the out_set_parameters() for card & device gets called
9089 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9090 const audio_devices_t deviceType = device->type();
9091 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009092 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009093 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9094 mpClientInterface->setParameters(output, String8(param));
9095 free(param);
9096 }
jiabin12537fc2023-10-12 17:56:08 +00009097 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009098 if (!profile->hasValidAudioProfile()) {
9099 ALOGW("%s() missing param", __func__);
9100 desc->close();
9101 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009102 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9103 // Reopen the output with the best audio profile picked by APM when the profile supports
9104 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009105 desc->close();
9106 output = AUDIO_IO_HANDLE_NONE;
9107 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9108 profile->pickAudioProfile(
9109 config.sample_rate, config.channel_mask, config.format);
9110 config.offload_info.sample_rate = config.sample_rate;
9111 config.offload_info.channel_mask = config.channel_mask;
9112 config.offload_info.format = config.format;
9113
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009114 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009115 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009116 if (status != NO_ERROR) {
9117 return nullptr;
9118 }
9119 }
9120
9121 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009122 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9123 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9124 hwModule->getHalVersionMajor() >= 3) {
9125 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9126 }
baek.kim -61c20122022-07-27 10:05:32 +00009127 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9128 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9129
jiabinbce0c1d2020-10-05 11:20:18 -07009130 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9131 sp<AudioPolicyMix> policyMix;
9132 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9133 policyMix->setOutput(desc);
9134 desc->mPolicyMix = policyMix;
9135 } else {
9136 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009137 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009138 }
9139
baek.kim -61c20122022-07-27 10:05:32 +00009140 } else if (hasPrimaryOutput() && speaker != nullptr
9141 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009142 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9143 // no duplicated output for:
9144 // - direct outputs
9145 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009146 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009147 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9148
9149 //TODO: configure audio effect output stage here
9150
9151 // open a duplicating output thread for the new output and the primary output
9152 sp<SwAudioOutputDescriptor> dupOutputDesc =
9153 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9154 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9155 if (status == NO_ERROR) {
9156 // add duplicated output descriptor
9157 addOutput(duplicatedOutput, dupOutputDesc);
9158 } else {
9159 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9160 mPrimaryOutput->mIoHandle, output);
9161 desc->close();
9162 removeOutput(output);
9163 nextAudioPortGeneration();
9164 return nullptr;
9165 }
9166 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009167 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9168 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9169 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009170 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009171 }
jiabinbce0c1d2020-10-05 11:20:18 -07009172 return desc;
9173}
9174
jiabinf1c73972022-04-14 16:28:52 -07009175status_t AudioPolicyManager::getDevicesForAttributes(
9176 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009177 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9178 // over any usage or content type also present in attr.
9179 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9180 attr.source != AUDIO_SOURCE_INVALID) {
9181 return getInputDevicesForAttributes(attr, devices);
9182 }
9183
jiabinf1c73972022-04-14 16:28:52 -07009184 // Devices are determined in the following precedence:
9185 //
9186 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9187 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9188 //
9189 // If no such dynamic policy then
9190 // 2) Devices containing an active client using setPreferredDevice
9191 // with same strategy as the attributes.
9192 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9193 //
9194 // If no corresponding active client with setPreferredDevice then
9195 // 3) Devices associated with the strategy determined by the attributes
9196 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9197 //
9198 // See related getOutputForAttrInt().
9199
9200 // check dynamic policies but only for primary descriptors (secondary not used for audible
9201 // audio routing, only used for duplication for playback capture)
9202 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009203 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009204 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009205 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9206 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9207 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009208 if (status != OK) {
9209 return status;
9210 }
9211
9212 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9213 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9214 // as they are unaffected by device/stream volume
9215 // (per SwAudioOutputDescriptor::isFixedVolume()).
9216 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9217 ) {
9218 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9219 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9220 devices.add(deviceDesc);
9221 } else {
9222 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9223 // which selects setPreferredDevice if active. This means forVolume call
9224 // will take an active setPreferredDevice, if such exists.
9225
9226 devices = mEngine->getOutputDevicesForAttributes(
9227 attr, nullptr /* preferredDevice */, false /* fromCache */);
9228 }
9229
9230 if (forVolume) {
9231 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9232 // for single volume control in AudioService (such relationship should exist if
9233 // SPEAKER_SAFE is present).
9234 //
9235 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9236 DeviceVector speakerSafeDevices =
9237 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9238 if (!speakerSafeDevices.isEmpty()) {
9239 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9240 devices.remove(speakerSafeDevices);
9241 }
9242 }
9243
9244 return NO_ERROR;
9245}
9246
wenyu zhang8558a332024-09-09 15:12:48 +00009247status_t AudioPolicyManager::getInputDevicesForAttributes(
9248 const audio_attributes_t &attr, DeviceVector &devices) {
9249 devices = DeviceVector(
9250 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9251 AUDIO_SESSION_NONE,
9252 nullptr /* mix */));
9253 return NO_ERROR;
9254}
9255
jiabinf1c73972022-04-14 16:28:52 -07009256status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9257 AudioProfileVector& audioProfiles,
9258 uint32_t flags,
9259 bool isInput) {
9260 for (const auto& hwModule : mHwModules) {
9261 // the MSD module checks for different conditions
9262 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9263 continue;
9264 }
9265 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9266 : hwModule->getOutputProfiles();
9267 for (const auto& profile : ioProfiles) {
9268 if (!profile->areAllDevicesSupported(devices) ||
jiabin91beb492024-10-16 21:53:36 +00009269 !profile->isCompatibleProfileForFlags(flags)) {
jiabinf1c73972022-04-14 16:28:52 -07009270 continue;
9271 }
9272 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9273 }
9274 }
9275
9276 if (!isInput) {
9277 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9278 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9279 if (msdModule != nullptr) {
9280 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9281 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9282 for (const auto &profile: msdModule->getOutputProfiles()) {
9283 if (!profile->asAudioPort()->isDirectOutput()) {
9284 continue;
9285 }
9286 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9287 }
9288 } else {
9289 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9290 }
9291 }
9292 }
9293
9294 return NO_ERROR;
9295}
9296
jiabin3ff8d7d2022-12-13 06:27:44 +00009297sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9298 const audio_config_t *config,
9299 audio_output_flags_t flags,
9300 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009301 closeOutput(outputDesc->mIoHandle);
9302 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9303 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9304 if (preferredOutput == nullptr) {
9305 ALOGE("%s failed to reopen output device=%d, caller=%s",
9306 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009307 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009308 return preferredOutput;
9309}
9310
9311void AudioPolicyManager::reopenOutputsWithDevices(
9312 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9313 for (const auto& [output, devices] : outputsToReopen) {
9314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9315 closeOutput(output);
9316 openOutputWithProfileAndDevice(desc->mProfile, devices);
9317 }
jiabina84c3d32022-12-02 18:59:55 +00009318}
9319
jiabinc44b3462022-12-08 12:52:31 -08009320PortHandleVector AudioPolicyManager::getClientsForStream(
9321 audio_stream_type_t streamType) const {
9322 PortHandleVector clients;
9323 for (size_t i = 0; i < mOutputs.size(); ++i) {
9324 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9325 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9326 }
9327 return clients;
9328}
9329
9330void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9331 PortHandleVector clients;
9332 for (auto stream : streams) {
9333 PortHandleVector clientsForStream = getClientsForStream(stream);
9334 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9335 }
9336 mpClientInterface->invalidateTracks(clients);
9337}
9338
jiabin220eea12024-05-17 17:55:20 +00009339void AudioPolicyManager::updateClientsInternalMute(
9340 const sp<android::SwAudioOutputDescriptor> &desc) {
9341 if (!desc->isBitPerfect() ||
9342 !com::android::media::audioserver::
9343 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9344 // This is only used for bit perfect output now.
9345 return;
9346 }
9347 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9348 bool bitPerfectClientInternalMute = false;
9349 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9350 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9351 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9352 bitPerfectClient = client;
9353 continue;
9354 }
9355 bool muted = false;
9356 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9357 // System sound is muted.
9358 muted = true;
9359 } else {
9360 bitPerfectClientInternalMute = true;
9361 }
9362 if (client->setInternalMute(muted)) {
9363 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9364 if (!result.ok()) {
9365 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9366 continue;
9367 }
9368 media::TrackInternalMuteInfo info;
9369 info.portId = result.value();
9370 info.muted = client->getInternalMute();
9371 clientsInternalMute.push_back(std::move(info));
9372 }
9373 }
9374 if (bitPerfectClient != nullptr &&
9375 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9376 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9377 if (result.ok()) {
9378 media::TrackInternalMuteInfo info;
9379 info.portId = result.value();
9380 info.muted = bitPerfectClient->getInternalMute();
9381 clientsInternalMute.push_back(std::move(info));
9382 } else {
9383 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9384 __func__, bitPerfectClient->portId());
9385 }
9386 }
9387 if (!clientsInternalMute.empty()) {
9388 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9389 status != NO_ERROR) {
9390 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9391 }
9392 }
9393}
9394
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00009395status_t AudioPolicyManager::getMmapPolicyInfos(AudioMMapPolicyType policyType,
9396 std::vector<AudioMMapPolicyInfo> *policyInfos) {
9397 if (policyType != AudioMMapPolicyType::DEFAULT &&
9398 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9399 return BAD_VALUE;
9400 }
9401 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9402 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9403 return status;
9404 }
9405 }
9406 *policyInfos = mMmapPolicyInfos[policyType];
9407 return NO_ERROR;
9408}
9409
9410status_t AudioPolicyManager::getMmapPolicyForDevice(
9411 AudioMMapPolicyType policyType, AudioMMapPolicyInfo *policyInfo) {
9412 if (policyType != AudioMMapPolicyType::DEFAULT &&
9413 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9414 return BAD_VALUE;
9415 }
9416 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9417 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9418 return status;
9419 }
9420 }
9421 auto it = mMmapPolicyByDeviceType[policyType].find(policyInfo->device.type);
9422 policyInfo->mmapPolicy = it == mMmapPolicyByDeviceType[policyType].end()
9423 ? AudioMMapPolicy::NEVER : it->second;
9424 return NO_ERROR;
9425}
9426
9427status_t AudioPolicyManager::updateMmapPolicyInfos(AudioMMapPolicyType policyType) {
9428 std::vector<AudioMMapPolicyInfo> policyInfos;
9429 if (status_t status = mpClientInterface->getMmapPolicyInfos(policyType, &policyInfos);
9430 status != NO_ERROR) {
9431 ALOGE("%s, failed, error = %d", __func__, status);
9432 return status;
9433 }
9434 std::map<AudioDeviceDescription, AudioMMapPolicy> mmapPolicyByDeviceType;
9435 if (policyInfos.size() == 1 && policyInfos[0].device == AudioDevice()) {
9436 // When there is only one AudioMMapPolicyInfo instance and the device is a default value,
9437 // it indicates the mmap policy is reported via system property. In that case, use the
9438 // routing information to fill details for how mmap is supported for a particular device.
9439 for (const auto &hwModule: mHwModules) {
9440 for (const auto &profile: hwModule->getInputProfiles()) {
9441 if ((profile->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ)
9442 != AUDIO_INPUT_FLAG_MMAP_NOIRQ) {
9443 continue;
9444 }
9445 for (const auto &device: profile->getSupportedDevices()) {
9446 auto deviceDesc =
9447 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9448 if (deviceDesc.ok()) {
9449 mmapPolicyByDeviceType.emplace(
9450 deviceDesc.value(), policyInfos[0].mmapPolicy);
9451 }
9452 }
9453 }
9454 for (const auto &profile: hwModule->getOutputProfiles()) {
9455 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)
9456 != AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
9457 continue;
9458 }
9459 for (const auto &device: profile->getSupportedDevices()) {
9460 auto deviceDesc =
9461 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9462 if (deviceDesc.ok()) {
9463 mmapPolicyByDeviceType.emplace(
9464 deviceDesc.value(), policyInfos[0].mmapPolicy);
9465 }
9466 }
9467 }
9468 }
9469 } else {
9470 for (const auto &info: policyInfos) {
9471 mmapPolicyByDeviceType[info.device.type] = info.mmapPolicy;
9472 }
9473 }
9474 mMmapPolicyByDeviceType.emplace(policyType, mmapPolicyByDeviceType);
9475 mMmapPolicyInfos.emplace(policyType, policyInfos);
9476 return NO_ERROR;
9477}
9478
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009479} // namespace android