blob: 3ec3fb336c86d5986f0cbb00245dfe5b83c31144 [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
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
Ping Tsai2a5a5242024-08-16 13:39:10 +0800125status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
Ping Tsai2a5a5242024-08-16 13:39:10 +0800130 status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
131 ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
132 static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
133
134 return status;
François Gaffie44481e72016-04-20 07:49:57 +0200135}
136
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100137status_t AudioPolicyManager::setDeviceConnectionStateInt(
138 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
139 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100140 if (port.ext.getTag() != AudioPortExt::device) {
141 return BAD_VALUE;
142 }
143 audio_devices_t device_type;
144 std::string device_address;
145 if (status_t status = aidl2legacy_AudioDevice_audio_device(
146 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
147 status != OK) {
148 return status;
149 };
150 const char* device_name = port.name.c_str();
151 // connect/disconnect only 1 device at a time
152 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
153 return BAD_VALUE;
154
155 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
156 device_type, device_address.c_str(), device_name, encodedFormat,
157 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000158 if (device == nullptr) {
159 return INVALID_OPERATION;
160 }
161 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
162 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
163 }
164 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100165}
166
François Gaffie11d30102018-11-02 16:09:09 +0100167status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800168 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100169 const char* device_address,
170 const char* device_name,
171 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800172 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100173 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
174 status == OK) {
175 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
176 } else {
177 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
178 return status;
179 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700180}
Paul McLeane743a472015-01-28 11:07:31 -0800181
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
183 audio_policy_dev_state_t state)
184{
Eric Laurente552edb2014-03-10 17:42:56 -0700185 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700186 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700187 SortedVector <audio_io_handle_t> outputs;
188
François Gaffie11d30102018-11-02 16:09:09 +0100189 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // save a copy of the opened output descriptors before any output is opened or closed
192 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
193 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100194
195 bool wasLeUnicastActive = isLeUnicastActive();
196
Eric Laurente552edb2014-03-10 17:42:56 -0700197 switch (state)
198 {
199 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800200 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700201 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100202 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700203 return INVALID_OPERATION;
204 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800205 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700206 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700207
Eric Laurente552edb2014-03-10 17:42:56 -0700208 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200209 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700210 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
212
François Gaffie44481e72016-04-20 07:49:57 +0200213 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
214 // parameters on newly connected devices (instead of opening the outputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800215 if (broadcastDeviceConnectionState(
216 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
217 mAvailableOutputDevices.remove(device);
218 mHwModules.cleanUpForDevice(device);
219 ALOGE("%s() device %s format %x connection failed", __func__,
220 device->toString().c_str(), device->getEncodedFormat());
221 return INVALID_OPERATION;
222 }
François Gaffie44481e72016-04-20 07:49:57 +0200223
François Gaffie11d30102018-11-02 16:09:09 +0100224 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
225 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200226
jiabinc0048632023-04-27 22:04:31 +0000227 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganov3754b642024-04-17 18:31:04 +0000228
229 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 return INVALID_OPERATION;
231 }
François Gaffie2110e042015-03-24 08:41:51 +0100232
jiabin1c4794b2020-05-05 10:08:05 -0700233 // Populate encapsulation information when a output device is connected.
234 device->setEncapsulationInfoFromHal(mpClientInterface);
235
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700236 // outputs should never be empty here
237 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
238 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800240
Eric Laurent3ae5f312015-02-03 17:12:08 -0800241 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700242 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700243 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700244 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100245 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700246 return INVALID_OPERATION;
247 }
248
François Gaffie11d30102018-11-02 16:09:09 +0100249 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700250
jiabinc0048632023-04-27 22:04:31 +0000251 // Notify the HAL to prepare to disconnect device
252 broadcastDeviceConnectionState(
253 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700254
Eric Laurente552edb2014-03-10 17:42:56 -0700255 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100256 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700257
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100258 mOutputs.clearSessionRoutesForDevice(device);
259
François Gaffie11d30102018-11-02 16:09:09 +0100260 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100261
jiabinc0048632023-04-27 22:04:31 +0000262 // Send Disconnect to HALs
263 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
264
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800265 // Reset active device codec
266 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
267
Kriti Dangef6be8f2020-11-05 11:58:19 +0100268 // remove device from mReportedFormatsMap cache
269 mReportedFormatsMap.erase(device);
270
jiabina84c3d32022-12-02 18:59:55 +0000271 // remove preferred mixer configurations
272 mPreferredMixerAttrInfos.erase(device->getId());
273
Eric Laurente552edb2014-03-10 17:42:56 -0700274 } break;
275
276 default:
François Gaffie11d30102018-11-02 16:09:09 +0100277 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700278 return BAD_VALUE;
279 }
280
Eric Laurent736a1022019-03-27 18:28:46 -0700281 // Propagate device availability to Engine
282 setEngineDeviceConnectionState(device, state);
283
Eric Laurentae970022019-01-29 14:25:04 -0800284 // No need to evaluate playback routing when connecting a remote submix
285 // output device used by a dynamic policy of type recorder as no
286 // playback use case is affected.
287 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700288 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800289 for (audio_io_handle_t output : outputs) {
290 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800291 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
292 if (policyMix != nullptr
293 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000294 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800295 doCheckForDeviceAndOutputChanges = false;
296 break;
297 }
298 }
299 }
300
301 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700302 // outputs must be closed after checkOutputForAllStrategies() is executed
303 if (!outputs.isEmpty()) {
304 for (audio_io_handle_t output : outputs) {
305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100306 // close unused outputs after device disconnection or direct outputs that have
307 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200308 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200309 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
310 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200311 (desc->mDirectOpenCount == 0))
312 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
313 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200314 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 closeOutput(output);
316 }
Eric Laurente552edb2014-03-10 17:42:56 -0700317 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700318 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
319 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700320 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700321 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800322 };
323
324 if (doCheckForDeviceAndOutputChanges) {
325 checkForDeviceAndOutputChanges(checkCloseOutputs);
326 } else {
327 checkCloseOutputs();
328 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100329 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100330 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700331 const DeviceVector activeMediaDevices =
332 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000333 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700334 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700335 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530336 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
337 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100338 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // do not force device change on duplicated output because if device is 0, it will
340 // also force a device 0 for the two outputs it is duplicated to which may override
341 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100342 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100343 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700344 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700345 // always force when disconnecting (a non-duplicated device)
346 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000347 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000348 // If the device is using preferred mixer attributes, the output need to reopen
349 // with default configuration when the new selected devices are different from
350 // current routing devices
351 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
352 continue;
353 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530354 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700355 }
jiabinbce0c1d2020-10-05 11:20:18 -0700356 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000357 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700358 desc->supportsDevicesForPlayback(activeMediaDevices)) {
359 // Reopen the output to query the dynamic profiles when there is not active
360 // clients or all active clients will be rerouted. Otherwise, set the flag
361 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
362 // can be reopened to query dynamic profiles when all clients are inactive.
363 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000364 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700365 } else {
366 desc->mPendingReopenToQueryProfiles = true;
367 }
368 }
369 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
370 // Clear the flag that previously set for re-querying profiles.
371 desc->mPendingReopenToQueryProfiles = false;
372 }
373 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000374 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700375
Eric Laurentd60560a2015-04-10 11:31:20 -0700376 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100377 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700378 }
379
Eric Laurent96d1dda2022-03-14 17:14:19 +0100380 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
381
Eric Laurent72aa32f2014-05-30 18:51:48 -0700382 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530383 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700384 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700385 } // end if is output device
386
Eric Laurente552edb2014-03-10 17:42:56 -0700387 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700388 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700390 switch (state)
391 {
392 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700393 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700396 return INVALID_OPERATION;
397 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700398
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530399 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
400
Eric Laurent0dd51852019-04-19 18:18:58 -0700401 if (mAvailableInputDevices.add(device) < 0) {
402 return NO_MEMORY;
403 }
404
François Gaffie44481e72016-04-20 07:49:57 +0200405 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
406 // parameters on newly connected devices (instead of opening the inputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800407 if (broadcastDeviceConnectionState(
408 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
409 mAvailableInputDevices.remove(device);
410 mHwModules.cleanUpForDevice(device);
411 ALOGE("%s() device %s format %x connection failed", __func__,
412 device->toString().c_str(), device->getEncodedFormat());
413 return INVALID_OPERATION;
414 }
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700415 // Propagate device availability to Engine
416 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200417
Eric Laurent0dd51852019-04-19 18:18:58 -0700418 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700419 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
420
Eric Laurent0dd51852019-04-19 18:18:58 -0700421 mAvailableInputDevices.remove(device);
422
jiabinc0048632023-04-27 22:04:31 +0000423 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100424
425 mHwModules.cleanUpForDevice(device);
426
Eric Laurentd4692962014-05-05 18:13:44 -0700427 return INVALID_OPERATION;
428 }
429
Eric Laurentd4692962014-05-05 18:13:44 -0700430 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700431
432 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700433 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100435 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700436 return INVALID_OPERATION;
437 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700438
François Gaffie11d30102018-11-02 16:09:09 +0100439 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700440
jiabinc0048632023-04-27 22:04:31 +0000441 // Notify the HAL to prepare to disconnect device
442 broadcastDeviceConnectionState(
443 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700444
François Gaffie11d30102018-11-02 16:09:09 +0100445 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700446
447 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100448
jiabinc0048632023-04-27 22:04:31 +0000449 // Set Disconnect to HALs
450 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
451
Kriti Dangef6be8f2020-11-05 11:58:19 +0100452 // remove device from mReportedFormatsMap cache
453 mReportedFormatsMap.erase(device);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700454
455 // Propagate device availability to Engine
456 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700457 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700458
459 default:
François Gaffie11d30102018-11-02 16:09:09 +0100460 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700461 return BAD_VALUE;
462 }
463
Eric Laurent0dd51852019-04-19 18:18:58 -0700464 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700465 // As the input device list can impact the output device selection, update
466 // getDeviceForStrategy() cache
467 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700468
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100469 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200470 // Reconnect Audio Source
471 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
472 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
473 checkAudioSourceForAttributes(attributes);
474 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700475 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100476 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700477 }
478
Eric Laurentb52c1522014-05-20 11:27:36 -0700479 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530480 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700481 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700482 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700483
François Gaffie11d30102018-11-02 16:09:09 +0100484 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700485 return BAD_VALUE;
486}
487
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100488status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
489 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800490 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000491 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
492 devDescr->setName(device_name);
493 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100494}
495
Eric Laurent736a1022019-03-27 18:28:46 -0700496void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
497 audio_policy_dev_state_t state) {
498
499 // the Engine does not have to know about remote submix devices used by dynamic audio policies
500 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
501 return;
502 }
503 mEngine->setDeviceConnectionState(device, state);
504}
505
506
Eric Laurente0720872014-03-11 09:30:41 -0700507audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100508 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700509{
Eric Laurent634b7142016-04-20 13:48:02 -0700510 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
512 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700513 (strlen(device_address) != 0)/*matchAddress*/);
514
515 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100516 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700517 device, device_address);
518 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
519 }
François Gaffie53615e22015-03-19 09:24:12 +0100520
Eric Laurent3a4311c2014-03-17 12:00:47 -0700521 DeviceVector *deviceVector;
522
Eric Laurente552edb2014-03-10 17:42:56 -0700523 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700524 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700525 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700526 deviceVector = &mAvailableInputDevices;
527 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100528 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700529 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700530 }
Eric Laurent634b7142016-04-20 13:48:02 -0700531
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800532 return (deviceVector->getDevice(
533 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700534 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800535}
536
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800537status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
538 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800539 const char *device_name,
540 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800541{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
543 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800544
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800545 // connect/disconnect only 1 device at a time
546 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
547
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800548 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700549 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800550 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800551 // Nothing to do: device is not connected
552 return NO_ERROR;
553 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800554 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800555
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700556 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800557 // configure codecs.
558 // Handle two specific cases by sending a set parameter to
559 // configure A2DP codecs. No need to toggle device state.
560 // Case 1: A2DP active device switches from primary to primary
561 // module
562 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100563 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700564 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800565 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
566 if (availablePrimaryOutputDevices().contains(devDesc) &&
567 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100568 bool isA2dp = audio_is_a2dp_out_device(device);
569 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
570 : String8(AudioParameter::keyReconfigLeSupported);
571 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800572 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100573 int isReconfigSupported;
574 repliedParameters.getInt(supportKey, isReconfigSupported);
575 if (isReconfigSupported) {
576 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
577 : String8(AudioParameter::keyReconfigLe);
578 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800579 param.add(key, String8("true"));
580 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
581 devDesc->setEncodedFormat(encodedFormat);
582 return NO_ERROR;
583 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700584 }
585 }
cnx421bd2dcc42020-07-11 14:58:44 +0800586 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000587 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800588 for (size_t i = 0; i < mOutputs.size(); i++) {
589 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000590 // mute media strategies to avoid sending the music tail into
591 // the earpiece or headset.
592 if (desc->isStrategyActive(musicStrategy)) {
593 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
594 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
595 tempRecommendedMuteDuration : desc->latency() * 4;
596 if (muteWaitMs < tempMuteDurationMs) {
597 muteWaitMs = tempMuteDurationMs;
598 }
599 }
cnx421bd2dcc42020-07-11 14:58:44 +0800600 setStrategyMute(musicStrategy, true, desc);
601 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
602 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
603 nullptr, true /*fromCache*/).types());
604 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000605 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
606 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
607 // happens after the actual device switch.
608 if (muteWaitMs > 0) {
609 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
610 usleep(muteWaitMs * 1000);
611 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800612 // Toggle the device state: UNAVAILABLE -> AVAILABLE
613 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100614 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800615 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800616 device_address, device_name,
617 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800618 if (status != NO_ERROR) {
619 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
620 status);
621 return status;
622 }
623
624 status = setDeviceConnectionState(device,
625 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800626 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800627 if (status != NO_ERROR) {
628 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
629 status);
630 return status;
631 }
632
633 return NO_ERROR;
634}
635
Pattydd807582021-11-04 21:01:03 +0800636status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
637 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800638{
Pattydd807582021-11-04 21:01:03 +0800639 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800640 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800641 std::unordered_set<audio_format_t> formatSet;
642 sp<HwModule> primaryModule =
643 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700644 if (primaryModule == nullptr) {
645 ALOGE("%s() unable to get primary module", __func__);
646 return NO_INIT;
647 }
Pattydd807582021-11-04 21:01:03 +0800648
649 DeviceTypeSet audioDeviceSet;
650
651 switch(device) {
652 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
653 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
654 break;
655 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800656 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
657 break;
658 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
659 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800660 break;
661 default:
662 ALOGE("%s() device type 0x%08x not supported", __func__, device);
663 return BAD_VALUE;
664 }
665
jiabin9a3361e2019-10-01 09:38:30 -0700666 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800667 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800668 for (const auto& device : declaredDevices) {
669 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800670 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800671 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800672 return status;
673}
674
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100675DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
676{
677 DeviceVector rxSinkdevices{};
678 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
679 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
680 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
681 auto rxSinkDevice = rxSinkdevices.itemAt(0);
682 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
683 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
684 // retrieve Rx Source device descriptor
685 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
686 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
687
688 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
689 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
690 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
691 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
692 return DeviceVector(rxSinkDevice);
693 }
694 }
695 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
696 // the device returned is not necessarily reachable via this output
697 // (filter later by setOutputDevices())
698 return getNewOutputDevices(mPrimaryOutput, fromCache);
699}
700
701status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
702{
François Gaffiedb1755b2023-09-01 11:50:35 +0200703 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100704 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
705 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
706 }
707 return INVALID_OPERATION;
708}
709
710status_t AudioPolicyManager::updateCallRoutingInternal(
711 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700712{
713 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100714 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700715 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200716 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700717 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100718 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700719 }
François Gaffie11d30102018-11-02 16:09:09 +0100720
Francois Gaffie716e1432019-01-14 16:58:59 +0100721 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100722 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200723
724 disconnectTelephonyAudioSource(mCallRxSourceClient);
725 disconnectTelephonyAudioSource(mCallTxSourceClient);
726
727 if (rxDevices.isEmpty()) {
728 ALOGW("%s() no selected output device", __func__);
729 return INVALID_OPERATION;
730 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000731 if (txSourceDevice == nullptr) {
732 ALOGE("%s() selected input device not available", __func__);
733 return INVALID_OPERATION;
734 }
François Gaffiec005e562018-11-06 15:04:49 +0100735
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100736 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100737 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700738
François Gaffie9eb18552018-11-05 10:33:26 +0100739 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700740 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100741 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700742 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100743 // retrieve Rx Source and Tx Sink device descriptors
744 sp<DeviceDescriptor> rxSourceDevice =
745 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
746 String8(),
747 AUDIO_FORMAT_DEFAULT);
748 sp<DeviceDescriptor> txSinkDevice =
749 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
750 String8(),
751 AUDIO_FORMAT_DEFAULT);
752
753 // RX and TX Telephony device are declared by Primary Audio HAL
754 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
755 (telephonyRxModule->getHalVersionMajor() >= 3)) {
756 if (rxSourceDevice == 0 || txSinkDevice == 0) {
757 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100758 ALOGE("%s() no telephony Tx and/or RX device", __func__);
759 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100760 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100761 // createAudioPatchInternal now supports both HW / SW bridging
762 createRxPatch = true;
763 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100764 } else {
765 // If the RX device is on the primary HW module, then use legacy routing method for
766 // voice calls via setOutputDevice() on primary output.
767 // Otherwise, create two audio patches for TX and RX path.
768 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
769 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700770 // If the TX device is also on the primary HW module, setOutputDevice() will take care
771 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100772 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
773 (txSinkDevice != 0);
774 }
775 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
776 // Otherwise, create two audio patches for TX and RX path.
777 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200778 if (!hasPrimaryOutput()) {
779 ALOGW("%s() no primary output available", __func__);
780 return INVALID_OPERATION;
781 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530782 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700783 } else { // create RX path audio patch
David Li48b6a832024-07-01 13:14:10 +0000784 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800785 // If the TX device is on the primary HW module but RX device is
786 // on other HW module, SinkMetaData of telephony input should handle it
787 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700788 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700789 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100790 // terminate active capture if on the same HW module as the call TX source device
791 // FIXME: would be better to refine to only inputs whose profile connects to the
792 // call TX device but this information is not in the audio patch and logic here must be
793 // symmetric to the one in startInput()
794 for (const auto& activeDesc : mInputs.getActiveInputs()) {
795 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
796 closeActiveClients(activeDesc);
797 }
798 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200799 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800800 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100801 if (waitMs != nullptr) {
802 *waitMs = muteWaitMs;
803 }
804 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800805}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700806
Mikhail Naganov100f0122018-11-29 11:22:16 -0800807bool AudioPolicyManager::isDeviceOfModule(
808 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
809 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
810 if (module != 0) {
811 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
812 .indexOf(devDesc) != NAME_NOT_FOUND
813 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
814 .indexOf(devDesc) != NAME_NOT_FOUND;
815 }
816 return false;
817}
818
David Li48b6a832024-07-01 13:14:10 +0000819void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200820{
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200822 const struct audio_port_config source = {
823 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
824 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
825 };
826 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100827
828 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent963dbcc2024-06-20 12:34:15 +0000829 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Li48b6a832024-07-01 13:14:10 +0000830 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100831 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
832 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200833 ALOGE_IF(mCallRxSourceClient == nullptr,
834 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200835}
836
Francois Gaffie601801d2021-06-22 13:27:39 +0200837void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200838{
Francois Gaffie601801d2021-06-22 13:27:39 +0200839 if (clientDesc == nullptr) {
840 return;
841 }
842 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
843 "%s error stopping audio source", __func__);
844 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200845}
846
847void AudioPolicyManager::connectTelephonyTxAudioSource(
848 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
849 uint32_t delayMs)
850{
Francois Gaffie601801d2021-06-22 13:27:39 +0200851 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200852 if (srcDevice == nullptr || sinkDevice == nullptr) {
853 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
854 return;
855 }
856 PatchBuilder patchBuilder;
857 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
858 ALOGV("%s between source %s and sink %s", __func__,
859 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200860 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200861 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
862
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200863 struct audio_port_config source = {};
864 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100865 mCallTxSourceClient = new SourceClientDescriptor(
866 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurent963dbcc2024-06-20 12:34:15 +0000867 mCommunnicationStrategy, toVolumeSource(aa), true,
868 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100869 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
870
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200871 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
872 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200873 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
874 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200875 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
876 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200877 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200878 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200879}
880
Eric Laurente0720872014-03-11 09:30:41 -0700881void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700882{
883 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100884 // store previous phone state for management of sonification strategy below
885 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100886 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100887
888 if (mEngine->setPhoneState(state) != NO_ERROR) {
889 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700890 return;
891 }
François Gaffie2110e042015-03-24 08:41:51 +0100892 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700893 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700894 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700895 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800896 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700897 }
898
François Gaffie2110e042015-03-24 08:41:51 +0100899 /**
900 * Switching to or from incall state or switching between telephony and VoIP lead to force
901 * routing command.
902 */
Eric Laurent74b71512019-11-06 17:21:57 -0800903 bool force = ((isStateInCall(oldState) != isStateInCall(state))
904 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700905
906 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700907 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700908
Eric Laurente552edb2014-03-10 17:42:56 -0700909 int delayMs = 0;
910 if (isStateInCall(state)) {
911 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100912 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
913 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700914 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700915 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700916 // mute media and sonification strategies and delay device switch by the largest
917 // latency of any output where either strategy is active.
918 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100919 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
920 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
921 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700922 (delayMs < (int)desc->latency()*2)) {
923 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700924 }
François Gaffiec005e562018-11-06 15:04:49 +0100925 setStrategyMute(musicStrategy, true, desc);
926 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
927 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
928 nullptr, true /*fromCache*/).types());
929 setStrategyMute(sonificationStrategy, true, desc);
930 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
931 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
932 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700933 }
934 }
935
François Gaffiedb1755b2023-09-01 11:50:35 +0200936 if (state == AUDIO_MODE_IN_CALL) {
937 (void)updateCallRouting(false /*fromCache*/, delayMs);
938 } else {
939 if (oldState == AUDIO_MODE_IN_CALL) {
940 disconnectTelephonyAudioSource(mCallRxSourceClient);
941 disconnectTelephonyAudioSource(mCallTxSourceClient);
942 }
943 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100944 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
945 // force routing command to audio hardware when ending call
946 // even if no device change is needed
947 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
948 rxDevices = mPrimaryOutput->devices();
949 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530950 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700951 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700952 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700953
jiabin3ff8d7d2022-12-13 06:27:44 +0000954 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700955 // reevaluate routing on all outputs in case tracks have been started during the call
956 for (size_t i = 0; i < mOutputs.size(); i++) {
957 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100958 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000959 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
960 && desc->mPreferredAttrInfo != nullptr) {
961 // If the output is using preferred mixer attributes and the audio mode is not normal,
962 // the output need to reopen with default configuration.
963 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
964 continue;
965 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200966 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
967 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530968 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200969 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700970 }
971 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000972 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700973
Eric Laurent96d1dda2022-03-14 17:14:19 +0100974 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
975
Eric Laurente552edb2014-03-10 17:42:56 -0700976 if (isStateInCall(state)) {
977 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700978 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800979 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700980 }
981
982 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100983 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
984 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700985}
986
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700987audio_mode_t AudioPolicyManager::getPhoneState() {
988 return mEngine->getPhoneState();
989}
990
Eric Laurente0720872014-03-11 09:30:41 -0700991void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100992 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700993{
François Gaffie2110e042015-03-24 08:41:51 +0100994 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700995 if (config == mEngine->getForceUse(usage)) {
996 return;
997 }
Eric Laurente552edb2014-03-10 17:42:56 -0700998
François Gaffie2110e042015-03-24 08:41:51 +0100999 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1000 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1001 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001002 }
François Gaffie2110e042015-03-24 08:41:51 +01001003 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1004 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1005 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001006
1007 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001008 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001009
Eric Laurent22fcda22019-05-17 16:28:47 -07001010 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1011 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001012 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001013 }
1014
Eric Laurentdc462862016-07-19 12:29:53 -07001015 //FIXME: workaround for truncated touch sounds
1016 // to be removed when the problem is handled by system UI
1017 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001018 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1019 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1020 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001021
1022 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001023 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001024}
1025
Eric Laurente0720872014-03-11 09:30:41 -07001026void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001027{
1028 ALOGV("setSystemProperty() property %s, value %s", property, value);
1029}
1030
Dorin Drimusecc9f422022-03-09 17:57:40 +01001031// Find an MSD output profile compatible with the parameters passed.
1032// When "directOnly" is set, restrict search to profiles for direct outputs.
1033sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1034 const DeviceVector& devices,
1035 uint32_t samplingRate,
1036 audio_format_t format,
1037 audio_channel_mask_t channelMask,
1038 audio_output_flags_t flags,
1039 bool directOnly)
1040{
1041 flags = getRelevantFlags(flags, directOnly);
1042
1043 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1044 if (msdModule != nullptr) {
1045 // for the msd module check if there are patches to the output devices
1046 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1047 HwModuleCollection modules;
1048 modules.add(msdModule);
1049 return searchCompatibleProfileHwModules(
1050 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1051 flags, directOnly);
1052 }
1053 }
1054 return nullptr;
1055}
1056
Michael Chana94fbb22018-04-24 14:31:19 +10001057// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1058// search to profiles for direct outputs.
1059sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001060 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001061 uint32_t samplingRate,
1062 audio_format_t format,
1063 audio_channel_mask_t channelMask,
1064 audio_output_flags_t flags,
1065 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001066{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 flags = getRelevantFlags(flags, directOnly);
1068
1069 return searchCompatibleProfileHwModules(
1070 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1071}
1072
1073audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1074 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001075 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001076 // only retain flags that will drive the direct output profile selection
1077 // if explicitly requested
1078 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001079 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001080 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1081 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001082 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001083 return flags;
1084}
Eric Laurent861a6282015-05-18 15:40:16 -07001085
Dorin Drimusecc9f422022-03-09 17:57:40 +01001086sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1087 const HwModuleCollection& hwModules,
1088 const DeviceVector& devices,
1089 uint32_t samplingRate,
1090 audio_format_t format,
1091 audio_channel_mask_t channelMask,
1092 audio_output_flags_t flags,
1093 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001094 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001095 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001096 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001097 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001098 samplingRate, NULL /*updatedSamplingRate*/,
1099 format, NULL /*updatedFormat*/,
1100 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001101 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001102 continue;
1103 }
1104 // reject profiles not corresponding to a device currently available
1105 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1106 continue;
1107 }
1108 // reject profiles if connected device does not support codec
1109 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1110 continue;
1111 }
1112 if (!directOnly) {
1113 return curProfile;
1114 }
1115
1116 // when searching for direct outputs, if several profiles are compatible, give priority
1117 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001118 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001119 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001120 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001121 }
1122 profile = curProfile;
1123 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1124 break;
1125 }
Eric Laurente552edb2014-03-10 17:42:56 -07001126 }
1127 }
Eric Laurent861a6282015-05-18 15:40:16 -07001128 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001129}
1130
Eric Laurentfa0f6742021-08-17 18:39:44 +02001131sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001132 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001133{
1134 for (const auto& hwModule : mHwModules) {
1135 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001136 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001137 continue;
1138 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001139 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001140 // reject profiles not corresponding to a device currently available
1141 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1142 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1143 continue;
1144 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001145 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1146 != devices.size()) {
1147 continue;
1148 }
1149 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001150 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1151 return curProfile;
1152 }
1153 }
1154 return nullptr;
1155}
1156
Eric Laurentf4e63452017-11-06 19:31:46 +00001157audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001158{
François Gaffiec005e562018-11-06 15:04:49 +01001159 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001160
1161 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1162 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1163 // format, flags, etc. This may result in some discrepancy for functions that utilize
1164 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1165 // and AudioSystem::getOutputSamplingRate().
1166
François Gaffie11d30102018-11-02 16:09:09 +01001167 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001168 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov285c1732024-09-05 17:26:50 -07001169 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001170 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1171 }
1172 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001173
François Gaffie11d30102018-11-02 16:09:09 +01001174 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1175 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001176 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001177}
1178
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001179status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1180 const audio_attributes_t *srcAttr,
1181 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001182{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001183 if (srcAttr != NULL) {
1184 if (!isValidAttributes(srcAttr)) {
1185 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1186 __func__,
1187 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1188 srcAttr->tags);
1189 return BAD_VALUE;
1190 }
1191 *dstAttr = *srcAttr;
1192 } else {
1193 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1194 ALOGE("%s: invalid stream type", __func__);
1195 return BAD_VALUE;
1196 }
François Gaffiec005e562018-11-06 15:04:49 +01001197 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001198 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001199
1200 // Only honor audibility enforced when required. The client will be
1201 // forced to reconnect if the forced usage changes.
1202 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001203 dstAttr->flags = static_cast<audio_flags_mask_t>(
1204 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001205 }
1206
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001207 return NO_ERROR;
1208}
1209
Kevin Rocard153f92d2018-12-18 18:33:28 -08001210status_t AudioPolicyManager::getOutputForAttrInt(
1211 audio_attributes_t *resultAttr,
1212 audio_io_handle_t *output,
1213 audio_session_t session,
1214 const audio_attributes_t *attr,
1215 audio_stream_type_t *stream,
1216 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001217 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001218 audio_output_flags_t *flags,
1219 audio_port_handle_t *selectedDeviceId,
1220 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001221 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001222 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001223 bool *isSpatialized,
1224 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001225{
François Gaffiec005e562018-11-06 15:04:49 +01001226 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001227 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001228 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001229 const sp<DeviceDescriptor> requestedDevice =
1230 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1231
Eric Laurent8a1095a2019-11-08 14:44:16 -08001232 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001233 *isSpatialized = false;
1234
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001235 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1236 if (status != NO_ERROR) {
1237 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001238 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001239 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001240 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001241 }
François Gaffiec005e562018-11-06 15:04:49 +01001242 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001243
François Gaffiec005e562018-11-06 15:04:49 +01001244 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1245 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001246
Oscar Azucena873d10f2023-01-12 18:34:42 -08001247 bool usePrimaryOutputFromPolicyMixes = false;
1248
Kevin Rocard153f92d2018-12-18 18:33:28 -08001249 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1250 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1251 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001252 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001253 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1254 .channel_mask = config->channel_mask,
1255 .format = config->format,
1256 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001257 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001258 mAvailableOutputDevices, requestedDevice, primaryMix,
1259 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001260 if (status != OK) {
1261 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001262 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001263
Kevin Rocard153f92d2018-12-18 18:33:28 -08001264 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001265 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungced57302024-08-14 11:37:57 -07001266 && (!audio_is_linear_pcm(config->format) ||
1267 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001268 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001269 return BAD_VALUE;
1270 }
1271 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001272 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001273 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1274 primaryMix->mDeviceAddress,
1275 AUDIO_FORMAT_DEFAULT);
1276 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001277 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001278 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1279 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001280 // if a direct output can be opened to deliver the track's multi-channel content to the
1281 // output rather than being downmixed by the primary output, then use this direct
1282 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1283 // mix.
1284 bool tryDirectForChannelMask = policyDesc != nullptr
1285 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1286 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001287 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001288 audio_io_handle_t newOutput;
1289 status = openDirectOutput(
1290 *stream, session, config,
1291 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001292 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001293 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001294 policyDesc = mOutputs.valueFor(newOutput);
1295 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001296 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001297 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001298 policyDesc = nullptr;
1299 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001300 }
1301 if (policyDesc != nullptr) {
1302 policyDesc->mPolicyMix = primaryMix;
1303 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001304 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1305 : AUDIO_PORT_HANDLE_NONE;
1306 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1307 // Remove direct flag as it is not on a direct output.
1308 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1309 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001310
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001311 ALOGV("getOutputForAttr() returns output %d", *output);
1312 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1313 *outputType = API_OUT_MIX_PLAYBACK;
1314 } else {
1315 *outputType = API_OUTPUT_LEGACY;
1316 }
1317 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001318 } else {
1319 if (policyMixDevice != nullptr) {
1320 ALOGE("%s, try to use primary mix but no output found", __func__);
1321 return INVALID_OPERATION;
1322 }
1323 // Fallback to default engine selection as the selected primary mix device is not
1324 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001325 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001326 }
François Gaffiec005e562018-11-06 15:04:49 +01001327 // Virtual sources must always be dynamicaly or explicitly routed
1328 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1329 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1330 return BAD_VALUE;
1331 }
1332 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1333 // in order to let the choice of the order to future vendor engine
1334 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001335
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001336 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001337 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001338 }
1339
Nadav Barb2f18162018-07-18 13:01:53 +03001340 // Set incall music only if device was explicitly set, and fallback to the device which is
1341 // chosen by the engine if not.
1342 // FIXME: provide a more generic approach which is not device specific and move this back
1343 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001344 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001345 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001346 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001347 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001348 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001349 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001350 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001351 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001352 }
1353 }
1354
François Gaffiec005e562018-11-06 15:04:49 +01001355 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1356 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1357 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001358
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001359 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001360 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001361 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001362 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001363 ALOGV("%s() Using MSD devices %s instead of devices %s",
1364 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001365 } else {
1366 *output = AUDIO_IO_HANDLE_NONE;
1367 }
1368 }
1369 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001370 sp<PreferredMixerAttributesInfo> info = nullptr;
1371 if (outputDevices.size() == 1) {
1372 info = getPreferredMixerAttributesInfo(
1373 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001374 mEngine->getProductStrategyForAttributes(*resultAttr),
1375 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001376 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1377 // and it is currently active.
1378 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001379 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001380 info = nullptr;
1381 }
jiabin220eea12024-05-17 17:55:20 +00001382 if (com::android::media::audioserver::
1383 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1384 if (info != nullptr && info->getUid() == uid &&
1385 info->configMatches(*config) &&
1386 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1387 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1388 [this, &outputDevices](audio_usage_t usage) {
1389 return mOutputs.isUsageActiveOnDevice(
1390 usage, outputDevices[0]); }))) {
1391 // Bit-perfect request is not allowed when the phone mode is not normal or
1392 // there is any higher priority user case active.
1393 return INVALID_OPERATION;
1394 }
1395 }
jiabina84c3d32022-12-02 18:59:55 +00001396 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001397 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001398 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001399 // The client will be active if the client is currently preferred mixer owner and the
1400 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001401 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001402 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001403 && info->getUid() == uid
1404 && *output != AUDIO_IO_HANDLE_NONE
1405 // When bit-perfect output is selected for the preferred mixer attributes owner,
1406 // only need to consider the config matches.
1407 && mOutputs.valueFor(*output)->isConfigurationMatched(
1408 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001409
1410 if (*isBitPerfect) {
1411 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1412 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001413 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001414 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001415 AudioProfileVector profiles;
1416 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1417 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001418 const auto channels = profiles[0]->getChannels();
1419 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1420 config->channel_mask = *channels.begin();
1421 }
1422 const auto sampleRates = profiles[0]->getSampleRates();
1423 if (!sampleRates.empty() &&
1424 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1425 config->sample_rate = *sampleRates.begin();
1426 }
jiabinf1c73972022-04-14 16:28:52 -07001427 config->format = profiles[0]->getFormat();
1428 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001429 return INVALID_OPERATION;
1430 }
Paul McLeanaa981192015-03-21 09:55:15 -07001431
François Gaffiec005e562018-11-06 15:04:49 +01001432 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001433 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001434 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001435 *selectedDeviceId = outputDevice->getId();
1436 break;
1437 }
1438 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001439
Eric Laurent8a1095a2019-11-08 14:44:16 -08001440 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1441 *outputType = API_OUTPUT_TELEPHONY_TX;
1442 } else {
1443 *outputType = API_OUTPUT_LEGACY;
1444 }
1445
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001446 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1447
1448 return NO_ERROR;
1449}
1450
1451status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1452 audio_io_handle_t *output,
1453 audio_session_t session,
1454 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001455 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001456 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001457 audio_output_flags_t *flags,
1458 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001459 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001460 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001461 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001462 bool *isSpatialized,
1463 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001464{
1465 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1466 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1467 return INVALID_OPERATION;
1468 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001469 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001470 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001471 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001472 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001473 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001474 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001475 const sp<DeviceDescriptor> requestedDevice =
1476 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1477
1478 // Prevent from storing invalid requested device id in clients
1479 const audio_port_handle_t sanitizedRequestedPortId =
1480 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1481 *selectedDeviceId = sanitizedRequestedPortId;
1482
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001483 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001484 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001485 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1486 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001487 if (status != NO_ERROR) {
1488 return status;
1489 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001490 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001491 if (secondaryOutputs != nullptr) {
1492 for (auto &secondaryMix : secondaryMixes) {
1493 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1494 if (outputDesc != nullptr &&
1495 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1496 secondaryOutputs->push_back(outputDesc->mIoHandle);
1497 weakSecondaryOutputDescs.push_back(outputDesc);
1498 }
1499 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001500 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001501
Eric Laurent8fc147b2018-07-22 19:13:55 -07001502 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001503 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001504 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001505 };
jiabin4ef93452019-09-10 14:29:54 -07001506 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001507
Eric Laurentc209fe42020-06-05 18:11:23 -07001508 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001509 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001510 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001511 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001512 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001513 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001514 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001515 std::move(weakSecondaryOutputDescs),
1516 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001517 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001518
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001519 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1520 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001521
Eric Laurente83b55d2014-11-14 10:06:21 -08001522 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001523}
1524
Eric Laurentc529cf62020-04-17 18:19:10 -07001525status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1526 audio_session_t session,
1527 const audio_config_t *config,
1528 audio_output_flags_t flags,
1529 const DeviceVector &devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001530 audio_io_handle_t *output,
1531 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001532
1533 *output = AUDIO_IO_HANDLE_NONE;
1534
1535 // skip direct output selection if the request can obviously be attached to a mixed output
1536 // and not explicitly requested
1537 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1538 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1539 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1540 return NAME_NOT_FOUND;
1541 }
1542
Mikhail Naganov285c1732024-09-05 17:26:50 -07001543 // Reject flag combinations that do not make sense. Note that the requested flags might not
1544 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1545 // combine the requested flags with its own flags, yielding an unsupported combination.
1546 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1547 return NAME_NOT_FOUND;
1548 }
1549
Eric Laurentc529cf62020-04-17 18:19:10 -07001550 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1551 // This prevents creating an offloaded track and tearing it down immediately after start
1552 // when audioflinger detects there is an active non offloadable effect.
1553 // FIXME: We should check the audio session here but we do not have it in this context.
1554 // This may prevent offloading in rare situations where effects are left active by apps
1555 // in the background.
1556 sp<IOProfile> profile;
1557 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1558 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1559 profile = getProfileForOutput(
1560 devices, config->sample_rate, config->format, config->channel_mask,
1561 flags, true /* directOnly */);
1562 }
1563
1564 if (profile == nullptr) {
1565 return NAME_NOT_FOUND;
1566 }
1567
1568 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1569 for (size_t i = 0; i < mOutputs.size(); i++) {
1570 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1571 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1572 // reuse direct output if currently open by the same client
1573 // and configured with same parameters
1574 if ((config->sample_rate == desc->getSamplingRate()) &&
1575 (config->format == desc->getFormat()) &&
1576 (config->channel_mask == desc->getChannelMask()) &&
1577 (session == desc->mDirectClientSession)) {
1578 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301579 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001580 mOutputs.keyAt(i), session);
1581 *output = mOutputs.keyAt(i);
1582 return NO_ERROR;
1583 }
1584 }
1585 }
1586
1587 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001588 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301589 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1590 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001591 return NAME_NOT_FOUND;
1592 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1593 // MMAP gracefully handles lack of an exclusive track resource by mixing
1594 // above the audio framework. For AAudio to know that the limit is reached,
1595 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301596 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1597 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001598 return NAME_NOT_FOUND;
1599 } else {
1600 // Close outputs on this profile, if available, to free resources for this request
1601 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1602 const auto desc = mOutputs.valueAt(i);
1603 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301604 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1605 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001606 closeOutput(desc->mIoHandle);
1607 }
1608 }
1609 }
1610 }
1611
1612 // Unable to close streams to find free resources for this request
1613 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301614 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1615 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001616 return NAME_NOT_FOUND;
1617 }
1618
Atneya Nairb16666a2023-12-11 20:18:33 -08001619 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001620
Michael Chan6fb34492020-12-08 15:44:49 +11001621 // An MSD patch may be using the only output stream that can service this request. Release
1622 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001623 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001624
Eric Laurentf1f22e72021-07-13 14:04:14 +02001625 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001626 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001627 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001628
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001629 // only accept an output with the requested parameters, unless the format can be IEC61937
1630 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1631 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1632 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1633 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001634 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001635 (!ignoreRequestedParametersCheck &&
1636 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1637 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1638 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001639 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1640 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1641 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1642 config->channel_mask, outputDesc->getChannelMask());
1643 if (*output != AUDIO_IO_HANDLE_NONE) {
1644 outputDesc->close();
1645 }
1646 // fall back to mixer output if possible when the direct output could not be open
1647 if (audio_is_linear_pcm(config->format) &&
1648 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1649 return NAME_NOT_FOUND;
1650 }
1651 *output = AUDIO_IO_HANDLE_NONE;
1652 return BAD_VALUE;
1653 }
1654 outputDesc->mDirectOpenCount = 1;
1655 outputDesc->mDirectClientSession = session;
1656
1657 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001658 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1659 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1660 hwModule->getHalVersionMajor() >= 3) {
1661 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1662 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001663 mPreviousOutputs = mOutputs;
1664 ALOGV("%s returns new direct output %d", __func__, *output);
1665 mpClientInterface->onAudioPortListUpdate();
1666 return NO_ERROR;
1667}
1668
François Gaffie11d30102018-11-02 16:09:09 +01001669audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1670 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001671 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001672 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001673 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001674 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001675 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001676 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001677 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001678{
Andy Hungc88b0642018-04-27 15:42:35 -07001679 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001680
jiabine375d412019-02-26 12:54:53 -08001681 // Discard haptic channel mask when forcing muting haptic channels.
1682 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001683 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1684 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001685
Eric Laurente552edb2014-03-10 17:42:56 -07001686 // open a direct output if required by specified parameters
1687 //force direct flag if offload flag is set: offloading implies a direct output stream
1688 // and all common behaviors are driven by checking only the direct flag
1689 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001690 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1691 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001692 }
Nadav Bar766fb022018-01-07 12:18:03 +02001693 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1694 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001695 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001696
1697 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1698
Eric Laurente83b55d2014-11-14 10:06:21 -08001699 // only allow deep buffering for music stream type
1700 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001701 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001702 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov285c1732024-09-05 17:26:50 -07001703 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001704 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001705 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001706 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001707 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001708 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001709 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001710 audio_is_linear_pcm(config->format) &&
1711 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001712 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001713 AUDIO_OUTPUT_FLAG_DIRECT);
1714 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001715 }
Eric Laurente552edb2014-03-10 17:42:56 -07001716
Carter Hsua3abb402021-10-26 11:11:20 +08001717 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1718 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1719 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1720 }
1721
Eric Laurentf9230d52024-01-26 18:49:09 +01001722 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001723 // was specified and offload or direct playback is not explicitly requested, and there is no
1724 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001725 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001726 if (mSpatializerOutput != nullptr &&
1727 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1728 prefMixerConfigInfo == nullptr &&
1729 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1730 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001731 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001732 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001733 }
1734
Eric Laurentc529cf62020-04-17 18:19:10 -07001735 audio_config_t directConfig = *config;
1736 directConfig.channel_mask = channelMask;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001737
1738 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1739 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001740 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001741 return output;
1742 }
1743
Eric Laurent14cbfca2016-03-17 09:42:16 -07001744 // A request for HW A/V sync cannot fallback to a mixed output because time
1745 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001746 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001747 return AUDIO_IO_HANDLE_NONE;
1748 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001749 // A request for Tuner cannot fallback to a mixed output
1750 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1751 return AUDIO_IO_HANDLE_NONE;
1752 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001753
Eric Laurente552edb2014-03-10 17:42:56 -07001754 // ignoring channel mask due to downmix capability in mixer
1755
1756 // open a non direct output
1757
1758 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001759 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001760 // get which output is suitable for the specified stream. The actual
1761 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001762 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001763 if (prefMixerConfigInfo != nullptr) {
1764 for (audio_io_handle_t outputHandle : outputs) {
1765 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1766 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1767 output = outputHandle;
1768 break;
1769 }
1770 }
1771 if (output == AUDIO_IO_HANDLE_NONE) {
1772 // No output open with the preferred profile. Open a new one.
1773 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1774 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1775 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1776 config.format = prefMixerConfigInfo->getConfigBase().format;
1777 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1778 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1779 &config, prefMixerConfigInfo->getFlags());
1780 if (preferredOutput == nullptr) {
1781 ALOGE("%s failed to open output with preferred mixer config", __func__);
1782 } else {
1783 output = preferredOutput->mIoHandle;
1784 }
1785 }
1786 } else {
1787 // at this stage we should ignore the DIRECT flag as no direct output could be
1788 // found earlier
1789 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001790 if (com::android::media::audioserver::
1791 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1792 // If the preferred mixer attributes is null, do not select the bit-perfect output
1793 // unless the bit-perfect output is the only output.
1794 // The bit-perfect output can exist while the passed in preferred mixer attributes
1795 // info is null when it is a high priority client. The high priority clients are
1796 // ringtone or alarm, which is not a bit-perfect use case.
1797 size_t i = 0;
1798 while (i < outputs.size() && outputs.size() > 1) {
1799 auto desc = mOutputs.valueFor(outputs[i]);
1800 // The output descriptor must not be null here.
1801 if (desc->isBitPerfect()) {
1802 outputs.removeItemsAt(i);
1803 } else {
1804 i += 1;
1805 }
1806 }
1807 }
jiabina84c3d32022-12-02 18:59:55 +00001808 output = selectOutput(
1809 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1810 }
Eric Laurente552edb2014-03-10 17:42:56 -07001811 }
François Gaffie11d30102018-11-02 16:09:09 +01001812 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001813 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001814 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001815
Eric Laurente552edb2014-03-10 17:42:56 -07001816 return output;
1817}
1818
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001819sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001820 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1821 mAvailableInputDevices);
1822 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1823}
1824
1825DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1826 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1827 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001828}
1829
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001830const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001831 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001832 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1833 if (msdModule != 0) {
1834 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1835 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1836 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1837 const struct audio_port_config *source = &patch->mPatch.sources[j];
1838 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1839 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001840 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001841 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 }
1843 }
1844 }
1845 return msdPatches;
1846}
1847
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001848bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1849 ssize_t index = mAudioPatches.indexOfKey(handle);
1850 if (index < 0) {
1851 return false;
1852 }
1853 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1854 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1855 if (msdModule == nullptr) {
1856 return false;
1857 }
1858 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1859 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1860 return true;
1861 }
1862 index = getMsdOutputPatches().indexOfKey(handle);
1863 if (index < 0) {
1864 return false;
1865 }
1866 return true;
1867}
1868
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001869status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1870 const InputProfileCollection &inputProfiles,
1871 const OutputProfileCollection &outputProfiles,
1872 const sp<DeviceDescriptor> &sourceDevice,
1873 const sp<DeviceDescriptor> &sinkDevice,
1874 AudioProfileVector& sourceProfiles,
1875 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001876 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001877 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001878 return NO_INIT;
1879 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001880 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001881 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001882 return NO_INIT;
1883 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001885 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1886 inProfile->supportsDevice(sourceDevice)) {
1887 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001888 }
1889 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001890 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001891 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001892 outProfile->supportsDevice(sinkDevice)) {
1893 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001894 }
1895 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001896 return NO_ERROR;
1897}
1898
1899status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1900 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1901 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1902{
Dean Wheatley16809da2022-12-09 14:55:46 +11001903 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1904 static const std::vector<audio_format_t> formatsOrder = {{
1905 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001906 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1907 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001908 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1909 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1910 // preferred).
1911 std::vector<audio_channel_mask_t> masks = {{
1912 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1913 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1914 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1915 // insert index masks (higher counts most preferred) as preferred over position masks
1916 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1917 masks.insert(
1918 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1919 }
1920 return masks;
1921 }();
1922
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001923 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001924 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1925 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001926 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001927 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1928 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001929 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001930 }
1931 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1932 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1933 sinkConfig->format = bestSinkConfig.format;
1934 // For encoded streams force direct flag to prevent downstream mixing.
1935 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1936 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001937 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1938 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001939 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001940 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1941 // raw and IEC61937 framed streams.
1942 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1943 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1944 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001945 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1946 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001947 sourceConfig->channel_mask =
1948 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1949 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1950 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951 sourceConfig->format = bestSinkConfig.format;
1952 // Copy input stream directly without any processing (e.g. resampling).
1953 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1954 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1955 if (hwAvSync) {
1956 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1957 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1958 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1959 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1960 }
1961 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1962 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1963 sinkConfig->config_mask |= config_mask;
1964 sourceConfig->config_mask |= config_mask;
1965 return NO_ERROR;
1966}
1967
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001968PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1969 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001970{
1971 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001972 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1973 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1974 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1975 if (deviceModule == nullptr) {
1976 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1977 return patchBuilder;
1978 }
1979 const InputProfileCollection inputProfiles = msdIsSource ?
1980 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1981 const OutputProfileCollection outputProfiles = msdIsSource ?
1982 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1983
1984 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1985 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1986 device : getMsdAudioOutDevices().itemAt(0);
1987 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1988
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001989 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1990 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001991 AudioProfileVector sourceProfiles;
1992 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001993 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1994 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001995 for (auto hwAvSync : { true, false }) {
1996 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1997 sourceProfiles, sinkProfiles) != NO_ERROR) {
1998 continue;
1999 }
2000 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2001 &sinkConfig) == NO_ERROR) {
2002 // Found a matching config. Re-create PatchBuilder with this config.
2003 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2004 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002005 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002006 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002007 " supporting PCM format conversion.", __func__);
2008 return patchBuilder;
2009}
2010
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002011status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002012 DeviceVector devices;
2013 if (outputDevices != nullptr && outputDevices->size() > 0) {
2014 devices.add(*outputDevices);
2015 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002016 // Use media strategy for unspecified output device. This should only
2017 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2018 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002019 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002020 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002021 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002022 }
Michael Chan6fb34492020-12-08 15:44:49 +11002023 std::vector<PatchBuilder> patchesToCreate;
2024 for (auto i = 0u; i < devices.size(); ++i) {
2025 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002026 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002027 }
2028 // Retain only the MSD patches associated with outputDevices request.
2029 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002030 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002031 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2032 auto retainedPatch = false;
2033 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2034 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2035 patchesToRemove.removeItemsAt(i);
2036 retainedPatch = true;
2037 break;
2038 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002039 }
Michael Chan6fb34492020-12-08 15:44:49 +11002040 if (retainedPatch) {
2041 it = patchesToCreate.erase(it);
2042 continue;
2043 }
2044 ++it;
2045 }
2046 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2047 return NO_ERROR;
2048 }
2049 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2050 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002051 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002052 }
Michael Chan6fb34492020-12-08 15:44:49 +11002053 status_t status = NO_ERROR;
2054 for (const auto &p : patchesToCreate) {
2055 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2056 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2057 char message[256];
2058 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2059 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2060 currStatus == NO_ERROR ? "Success" : "Error",
2061 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2062 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2063 if (currStatus == NO_ERROR) {
2064 ALOGD("%s", message);
2065 } else {
2066 ALOGE("%s", message);
2067 if (status == NO_ERROR) {
2068 status = currStatus;
2069 }
2070 }
2071 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002072 return status;
2073}
2074
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002075void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2076 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002077 for (size_t i = 0; i < msdPatches.size(); i++) {
2078 const auto& patch = msdPatches[i];
2079 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2080 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2081 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2082 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2083 releaseAudioPatch(patch->getHandle(), mUidCached);
2084 break;
2085 }
2086 }
2087 }
2088}
2089
Dorin Drimus94d94412022-02-02 09:05:02 +01002090bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002091 DeviceVector devicesToCheck =
2092 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002093 AudioPatchCollection msdPatches = getMsdOutputPatches();
2094 for (size_t i = 0; i < msdPatches.size(); i++) {
2095 const auto& patch = msdPatches[i];
2096 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2097 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2098 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2099 const auto& foundDevice = devicesToCheck.getDevice(
2100 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2101 if (foundDevice != nullptr) {
2102 devicesToCheck.remove(foundDevice);
2103 if (devicesToCheck.isEmpty()) {
2104 return true;
2105 }
2106 }
2107 }
2108 }
2109 }
2110 return false;
2111}
2112
Eric Laurente0720872014-03-11 09:30:41 -07002113audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002114 audio_output_flags_t flags,
2115 audio_format_t format,
2116 audio_channel_mask_t channelMask,
2117 uint32_t samplingRate,
2118 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002119{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002120 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2121 "%s called with format %#x", __func__, format);
2122
jiabinebb6af42020-06-09 17:31:17 -07002123 // Return the output that haptic-generating attached to when 1) session id is specified,
2124 // 2) haptic-generating effect exists for given session id and 3) the output that
2125 // haptic-generating effect attached to is in given outputs.
2126 if (sessionId != AUDIO_SESSION_NONE) {
2127 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2128 sessionId, FX_IID_HAPTICGENERATOR);
2129 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2130 return hapticGeneratingOutput;
2131 }
2132 }
2133
Eric Laurent16c66dd2019-05-01 17:54:10 -07002134 // Flags disqualifying an output: the match must happen before calling selectOutput()
2135 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2136 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2137
2138 // Flags expressing a functional request: must be honored in priority over
2139 // other criteria
2140 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2141 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002142 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2143 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002144 // Flags expressing a performance request: have lower priority than serving
2145 // requested sampling rate or channel mask
2146 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2147 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2148 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2149
2150 const audio_output_flags_t functionalFlags =
2151 (audio_output_flags_t)(flags & kFunctionalFlags);
2152 const audio_output_flags_t performanceFlags =
2153 (audio_output_flags_t)(flags & kPerformanceFlags);
2154
2155 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2156
Eric Laurente552edb2014-03-10 17:42:56 -07002157 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002158 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002159 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002160 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002161 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002162 // with tiebreak preferring the minimum number of extra functional flags
2163 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002164 // 3: the output supporting the exact channel mask
2165 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002166 // 5: the output with the highest sampling rate if the requested sample rate is
2167 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002168 // 6: the output with the highest number of requested performance flags
2169 // 7: the output with the bit depth the closest to the requested one
2170 // 8: the primary output
2171 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002172
Eric Laurent16c66dd2019-05-01 17:54:10 -07002173 // matching criteria values in priority order for best matching output so far
2174 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002175
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002176 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002177 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2178 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2179 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002180
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002181 for (audio_io_handle_t output : outputs) {
2182 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002183 // matching criteria values in priority order for current output
2184 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002185
Eric Laurent16c66dd2019-05-01 17:54:10 -07002186 if (outputDesc->isDuplicated()) {
2187 continue;
2188 }
2189 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2190 continue;
2191 }
Eric Laurent8838a382014-09-08 16:44:28 -07002192
Eric Laurent16c66dd2019-05-01 17:54:10 -07002193 // If haptic channel is specified, use the haptic output if present.
2194 // When using haptic output, same audio format and sample rate are required.
2195 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002196 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002197 // skip if haptic channel specified but output does not support it, or output support haptic
2198 // but there is no haptic channel requested AND no orphan haptic effect exist
2199 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2200 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002201 continue;
2202 }
Shunkai Yao808da212024-04-05 22:50:56 +00002203 // In the case of audio-coupled-haptic playback, there is no format conversion and
2204 // resampling in the framework, same format/channel/sampleRate for client and the output
2205 // thread is required. In the case of HapticGenerator effect, do not require format
2206 // matching.
2207 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2208 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002209 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002210 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002211 }
2212
2213 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002214 const int matchingFunctionalFlags =
2215 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2216 const int totalFunctionalFlags =
2217 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2218 // Prefer matching functional flags, but subtract unnecessary functional flags.
2219 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002220
2221 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002222 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2223 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002224 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2225 channelCount <= outputChannelCount) {
2226 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002227 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2228 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002229 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002230 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 currentMatchCriteria[3] = outputChannelCount;
2232 }
2233
2234 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002235 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002236 int diff; // avoid unsigned integer overflow.
2237 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2238
2239 // prefer the closest output sampling rate greater than or equal to target
2240 // if none exists, prefer the closest output sampling rate less than target.
2241 //
2242 // criteria is offset to make non-negative.
2243 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002244 }
2245
2246 // performance flags match
2247 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2248
2249 // format match
2250 if (format != AUDIO_FORMAT_INVALID) {
2251 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002252 PolicyAudioPort::kFormatDistanceMax -
2253 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002254 }
2255
2256 // primary output match
2257 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2258
2259 // compare match criteria by priority then value
2260 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2261 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2262 bestMatchCriteria = currentMatchCriteria;
2263 bestOutput = output;
2264
2265 std::stringstream result;
2266 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2267 std::ostream_iterator<int>(result, " "));
2268 ALOGV("%s new bestOutput %d criteria %s",
2269 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002270 }
2271 }
2272
Eric Laurent16c66dd2019-05-01 17:54:10 -07002273 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002274}
2275
Eric Laurent8fc147b2018-07-22 19:13:55 -07002276status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002277{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002278 ALOGV("%s portId %d", __FUNCTION__, portId);
2279
2280 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2281 if (outputDesc == 0) {
2282 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002283 return BAD_VALUE;
2284 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002285 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002286
Eric Laurent8fc147b2018-07-22 19:13:55 -07002287 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002288 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002289
jiabin220eea12024-05-17 17:55:20 +00002290 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2291 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2292 && outputDesc->isBitPerfect()) {
2293 // Usually, APM selects bit-perfect output for high priority use cases only when
2294 // bit-perfect output is the only output that can be routed to the selected device.
2295 // However, here is no need to play high priority use cases such as ringtone and alarm
2296 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2297 // can attach to new output.
2298 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2299 __func__, client->stream());
2300 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2301 return DEAD_OBJECT;
2302 }
2303
Eric Laurent733ce942017-12-07 12:18:25 -08002304 status_t status = outputDesc->start();
2305 if (status != NO_ERROR) {
2306 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002307 }
2308
Eric Laurent97ac8712018-07-27 18:59:02 -07002309 uint32_t delayMs;
2310 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002311
2312 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002313 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002314 if (status == DEAD_OBJECT) {
2315 sp<SwAudioOutputDescriptor> desc =
2316 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2317 if (desc == nullptr) {
2318 // This is not common, it may indicate something wrong with the HAL.
2319 ALOGE("%s unable to open output with default config", __func__);
2320 return status;
2321 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002322 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002323 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002324 }
jiabina84c3d32022-12-02 18:59:55 +00002325
2326 // If the client is the first one active on preferred mixer parameters, reopen the output
2327 // if the current mixer parameters doesn't match the preferred one.
2328 if (outputDesc->devices().size() == 1) {
2329 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2330 outputDesc->devices()[0]->getId(), client->strategy());
2331 if (info != nullptr && info->getUid() == client->uid()) {
2332 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2333 info->getConfigBase(), info->getFlags())) {
2334 stopSource(outputDesc, client);
2335 outputDesc->stop();
2336 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2337 config.channel_mask = info->getConfigBase().channel_mask;
2338 config.sample_rate = info->getConfigBase().sample_rate;
2339 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002340 sp<SwAudioOutputDescriptor> desc =
2341 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2342 if (desc == nullptr) {
2343 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002344 }
jiabin220eea12024-05-17 17:55:20 +00002345 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002346 // Intentionally return error to let the client side resending request for
2347 // creating and starting.
2348 return DEAD_OBJECT;
2349 }
2350 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002351 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002352 // If it is first bit-perfect client, reroute all clients that will be routed to
2353 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2354 PortHandleVector clientsToInvalidate;
2355 for (size_t i = 0; i < mOutputs.size(); i++) {
2356 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002357 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002358 continue;
2359 }
2360 for (const auto& c : mOutputs[i]->getClientIterable()) {
2361 clientsToInvalidate.push_back(c->portId());
2362 }
2363 }
2364 if (!clientsToInvalidate.empty()) {
2365 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2366 __func__);
2367 mpClientInterface->invalidateTracks(clientsToInvalidate);
2368 }
2369 }
jiabina84c3d32022-12-02 18:59:55 +00002370 }
2371 }
2372
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002373 if (client->hasPreferredDevice()) {
2374 // playback activity with preferred device impacts routing occurred, inform upper layers
2375 mpClientInterface->onRoutingUpdated();
2376 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002377 if (delayMs != 0) {
2378 usleep(delayMs * 1000);
2379 }
2380
jiabin220eea12024-05-17 17:55:20 +00002381 if (status == NO_ERROR &&
2382 outputDesc->mPreferredAttrInfo != nullptr &&
2383 outputDesc->isBitPerfect() &&
2384 com::android::media::audioserver::
2385 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2386 // A new client is started on bit-perfect output, update all clients internal mute.
2387 updateClientsInternalMute(outputDesc);
2388 }
2389
Eric Laurentc75307b2015-03-17 15:29:32 -07002390 return status;
2391}
2392
Eric Laurent96d1dda2022-03-14 17:14:19 +01002393bool AudioPolicyManager::isLeUnicastActive() const {
2394 if (isInCall()) {
2395 return true;
2396 }
2397 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2398}
2399
2400bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2401 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2402 return false;
2403 }
2404 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2405 ALOGV("%s active %d", __func__, active);
2406 return active;
2407}
2408
Eric Laurent97ac8712018-07-27 18:59:02 -07002409status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2410 const sp<TrackClientDescriptor>& client,
2411 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002412{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002413 // cannot start playback of STREAM_TTS if any other output is being used
2414 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002415
2416 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002417 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002418 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002419 auto clientStrategy = client->strategy();
2420 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002421 if (stream == AUDIO_STREAM_TTS) {
2422 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002423 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002424 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002425 return INVALID_OPERATION;
2426 } else {
2427 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2428 }
2429 } else {
2430 // some playback other than beacon starts
2431 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2432 }
2433
Eric Laurent77305a62016-07-25 16:39:22 -07002434 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002435 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002436 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002437
François Gaffie11d30102018-11-02 16:09:09 +01002438 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002439 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002440 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002441 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002442 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002443 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002444 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002445 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002446 } else {
2447 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002448 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002449 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2450 AUDIO_FORMAT_DEFAULT);
2451 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2452 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002453 }
2454
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002455 // requiresMuteCheck is false when we can bypass mute strategy.
2456 // It covers a common case when there is no materially active audio
2457 // and muting would result in unnecessary delay and dropped audio.
2458 const uint32_t outputLatencyMs = outputDesc->latency();
2459 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002460 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002461
Eric Laurente552edb2014-03-10 17:42:56 -07002462 // increment usage count for this stream on the requested output:
2463 // NOTE that the usage count is the same for duplicated output and hardware output which is
2464 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002465 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002466
2467 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002468 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002469 // Preferred device may be exclusive, use only if no other active clients on this output
2470 devices = DeviceVector(
2471 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2472 } else {
2473 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2474 }
François Gaffie11d30102018-11-02 16:09:09 +01002475 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002476 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002477 }
2478 }
Eric Laurente552edb2014-03-10 17:42:56 -07002479
François Gaffiec005e562018-11-06 15:04:49 +01002480 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002481 selectOutputForMusicEffects();
2482 }
2483
François Gaffie1c878552018-11-22 16:53:21 +01002484 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002485 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002486 if (devices.isEmpty()) {
2487 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002488 }
François Gaffiec005e562018-11-06 15:04:49 +01002489 bool shouldWait =
2490 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2491 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2492 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002493 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002494 const bool needToCloseBitPerfectOutput =
2495 (com::android::media::audioserver::
2496 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2497 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2498 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002499 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002500 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002501 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002502 // An output has a shared device if
2503 // - managed by the same hw module
2504 // - supports the currently selected device
2505 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002506 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002507
Eric Laurent77305a62016-07-25 16:39:22 -07002508 // force a device change if any other output is:
2509 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002510 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002511 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002512 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002513 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002514 // change the device currently selected by the other output.
2515 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002516 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002517 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002518 force = true;
2519 }
2520 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002521 // a notification so that audio focus effect can propagate, or that a mute/unmute
2522 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002523 const uint32_t latencyMs = desc->latency();
2524 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2525
2526 if (shouldWait && isActive && (waitMs < latencyMs)) {
2527 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002528 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002529
2530 // Require mute check if another output is on a shared device
2531 // and currently active to have proper drain and avoid pops.
2532 // Note restoring AudioTracks onto this output needs to invoke
2533 // a volume ramp if there is no mute.
2534 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002535
2536 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2537 outputsToReopen.push_back(desc);
2538 }
Eric Laurente552edb2014-03-10 17:42:56 -07002539 }
2540 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002541
jiabin220eea12024-05-17 17:55:20 +00002542 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002543 // If the output is open with preferred mixer attributes, but the routed device is
2544 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2545 // changed.
2546 return DEAD_OBJECT;
2547 }
jiabin220eea12024-05-17 17:55:20 +00002548 for (auto& outputToReopen : outputsToReopen) {
2549 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2550 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002551 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302552 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2553 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002554
Eric Laurente552edb2014-03-10 17:42:56 -07002555 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002556 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002557 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002558 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002559 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002560 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002561 outputDesc->useHwGain() /*force*/)) {
2562 // request AudioService to reinitialize the volume curves asynchronously
2563 ALOGE("checkAndSetVolume failed, requesting volume range init");
2564 mpClientInterface->onVolumeRangeInitRequest();
2565 };
Eric Laurente552edb2014-03-10 17:42:56 -07002566
2567 // update the outputs if starting an output with a stream that can affect notification
2568 // routing
2569 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002570
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002571 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002572 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002573 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002574 }
Eric Laurentdc462862016-07-19 12:29:53 -07002575
2576 if (waitMs > muteWaitMs) {
2577 *delayMs = waitMs - muteWaitMs;
2578 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002579
2580 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2581 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2582 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2583 // change occurs after the MixerThread starts and causes a stream volume
2584 // glitch.
2585 //
2586 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002587 }
Eric Laurentdc462862016-07-19 12:29:53 -07002588
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002589 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002590 mEngine->getForceUse(
2591 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002592 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002593 }
2594
Eric Laurent97ac8712018-07-27 18:59:02 -07002595 // Automatically enable the remote submix input when output is started on a re routing mix
2596 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002597 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2598 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002599 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2600 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2601 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002602 "remote-submix",
2603 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002604 }
2605
Eric Laurent96d1dda2022-03-14 17:14:19 +01002606 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2607
Eric Laurente552edb2014-03-10 17:42:56 -07002608 return NO_ERROR;
2609}
2610
Eric Laurent96d1dda2022-03-14 17:14:19 +01002611void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2612 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2613 bool isUnicastActive = isLeUnicastActive();
2614
2615 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002616 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002617 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2618 for (size_t i = 0; i < mOutputs.size(); i++) {
2619 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2620 if (desc != ignoredOutput && desc->isActive()
2621 && ((isUnicastActive &&
2622 !desc->devices().
2623 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2624 || (wasUnicastActive &&
2625 !desc->devices().getDevicesFromTypes(
2626 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2627 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2628 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002629 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002630 // If the device is using preferred mixer attributes, the output need to reopen
2631 // with default configuration when the new selected devices are different from
2632 // current routing devices.
2633 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2634 continue;
2635 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302636 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002637 // re-apply device specific volume if not done by setOutputDevice()
2638 if (!force) {
2639 applyStreamVolumes(desc, newDevices.types(), delayMs);
2640 }
2641 }
2642 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002643 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002644 }
2645}
2646
Eric Laurent8fc147b2018-07-22 19:13:55 -07002647status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002648{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002649 ALOGV("%s portId %d", __FUNCTION__, portId);
2650
2651 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2652 if (outputDesc == 0) {
2653 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002654 return BAD_VALUE;
2655 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002656 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002657
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002658 if (client->hasPreferredDevice(true)) {
2659 // playback activity with preferred device impacts routing occurred, inform upper layers
2660 mpClientInterface->onRoutingUpdated();
2661 }
2662
Eric Laurent97ac8712018-07-27 18:59:02 -07002663 ALOGV("stopOutput() output %d, stream %d, session %d",
2664 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002665
Eric Laurent97ac8712018-07-27 18:59:02 -07002666 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002667
Eric Laurent733ce942017-12-07 12:18:25 -08002668 if (status == NO_ERROR ) {
2669 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002670 } else {
2671 return status;
2672 }
2673
2674 if (outputDesc->devices().size() == 1) {
2675 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2676 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002677 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002678 if (info != nullptr && info->getUid() == client->uid()) {
2679 info->decreaseActiveClient();
2680 if (info->getActiveClientCount() == 0) {
2681 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002682 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002683 }
2684 }
jiabin220eea12024-05-17 17:55:20 +00002685 if (com::android::media::audioserver::
2686 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2687 !outputReopened && outputDesc->isBitPerfect()) {
2688 // Only need to update the clients' internal mute when the output is bit-perfect and it
2689 // is not reopened.
2690 updateClientsInternalMute(outputDesc);
2691 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002692 }
2693 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002694}
2695
Eric Laurent97ac8712018-07-27 18:59:02 -07002696status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2697 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002698{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002699 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002700 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002701 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002702 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002703
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002704 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2705
François Gaffie1c878552018-11-22 16:53:21 +01002706 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2707 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002708 // Automatically disable the remote submix input when output is stopped on a
2709 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002710 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002711 if (isSingleDeviceType(
2712 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002713 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002714 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002715 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2716 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002717 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002718 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002719 }
2720 }
2721 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002722 if (client->hasPreferredDevice(true) &&
2723 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002724 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002725 forceDeviceUpdate = true;
2726 }
2727
Eric Laurente552edb2014-03-10 17:42:56 -07002728 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002729 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002730
Eric Laurente552edb2014-03-10 17:42:56 -07002731 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002732 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002733 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002734 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002735
2736 // If the routing does not change, if an output is routed on a device using HwGain
2737 // (aka setAudioPortConfig) and there are still active clients following different
2738 // volume group(s), force reapply volume
2739 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2740 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2741
Eric Laurente552edb2014-03-10 17:42:56 -07002742 // delay the device switch by twice the latency because stopOutput() is executed when
2743 // the track stop() command is received and at that time the audio track buffer can
2744 // still contain data that needs to be drained. The latency only covers the audio HAL
2745 // and kernel buffers. Also the latency does not always include additional delay in the
2746 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302747 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002748 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002749
2750 // force restoring the device selection on other active outputs if it differs from the
2751 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002752 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002753 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002754 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002755 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002756 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002757 desc->isActive() &&
2758 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002759 (newDevices != desc->devices())) {
2760 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2761 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002762
jiabin220eea12024-05-17 17:55:20 +00002763 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002764 // If the device is using preferred mixer attributes, the output need to
2765 // reopen with default configuration when the new selected devices are
2766 // different from current routing devices.
2767 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2768 continue;
2769 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302770 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002771
Eric Laurent57de36c2016-09-28 16:59:11 -07002772 // re-apply device specific volume if not done by setOutputDevice()
2773 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002774 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002775 }
Eric Laurente552edb2014-03-10 17:42:56 -07002776 }
2777 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002778 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002779 // update the outputs if stopping one with a stream that can affect notification routing
2780 handleNotificationRoutingForStream(stream);
2781 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002782
2783 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2784 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002785 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002786 }
2787
François Gaffiec005e562018-11-06 15:04:49 +01002788 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002789 selectOutputForMusicEffects();
2790 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002791
2792 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2793
Eric Laurente552edb2014-03-10 17:42:56 -07002794 return NO_ERROR;
2795 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002796 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002797 return INVALID_OPERATION;
2798 }
2799}
2800
jiabinbce0c1d2020-10-05 11:20:18 -07002801bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002802{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002803 ALOGV("%s portId %d", __FUNCTION__, portId);
2804
2805 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2806 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002807 // If an output descriptor is closed due to a device routing change,
2808 // then there are race conditions with releaseOutput from tracks
2809 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2810 // destroyed shortly thereafter.
2811 //
2812 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002813 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002814 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002815 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002816
2817 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002818
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302819 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2820 if (outputDesc->isClientActive(client)) {
2821 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2822 stopOutput(portId);
2823 }
2824
Eric Laurent8fc147b2018-07-22 19:13:55 -07002825 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2826 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002827 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002828 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002829 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002830 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002831 if (--outputDesc->mDirectOpenCount == 0) {
2832 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002833 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002834 }
2835 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302836
Andy Hung39efb7a2018-09-26 15:39:28 -07002837 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002838 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2839 // The output is pending reopened to query dynamic profiles and
2840 // there is no active clients
2841 closeOutput(outputDesc->mIoHandle);
2842 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2843 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2844 if (newOutputDesc == nullptr) {
2845 ALOGE("%s failed to open output", __func__);
2846 }
2847 return true;
2848 }
2849 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002850}
2851
Eric Laurentcaf7f482014-11-25 17:50:47 -08002852status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2853 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002854 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002855 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002856 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002857 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002858 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002859 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002860 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002861 audio_port_handle_t *portId,
2862 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002863{
François Gaffiec005e562018-11-06 15:04:49 +01002864 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002865 "flags %#x attributes=%s requested device ID %d",
2866 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2867 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002868
Eric Laurentad2e7b92017-09-14 20:06:42 -07002869 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002870 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002871 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002872 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002873 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002874 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002875 sp<RecordClientDescriptor> clientDesc;
2876 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002877 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002878 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002879
2880 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2881 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2882 return INVALID_OPERATION;
2883 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002884
Francois Gaffie716e1432019-01-14 16:58:59 +01002885 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2886 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002887 }
2888
Paul McLean466dc8e2015-04-17 13:15:36 -06002889 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002890 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002891 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002892
Eric Laurentad2e7b92017-09-14 20:06:42 -07002893 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2894 // possible
2895 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2896 *input != AUDIO_IO_HANDLE_NONE) {
2897 ssize_t index = mInputs.indexOfKey(*input);
2898 if (index < 0) {
2899 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2900 status = BAD_VALUE;
2901 goto error;
2902 }
2903 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904 RecordClientVector clients = inputDesc->getClientsForSession(session);
2905 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002906 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2907 status = BAD_VALUE;
2908 goto error;
2909 }
2910 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2911 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002912 // corresponds to a new client and is only permitted from the same UID.
2913 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002914 if (clients.size() > 1) {
2915 for (const auto& client : clients) {
2916 // The client map is ordered by key values (portId) and portIds are allocated
2917 // incrementaly. So the first client in this list is the one opened by audio flinger
2918 // when the mmap stream is created and should be ignored as it does not correspond
2919 // to an actual client
2920 if (client == *clients.cbegin()) {
2921 continue;
2922 }
2923 if (uid != client->uid() && !client->isSilenced()) {
2924 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2925 uid, client->portId(), client->uid());
2926 status = INVALID_OPERATION;
2927 goto error;
2928 }
Eric Laurent331679c2018-04-16 17:03:16 -07002929 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002930 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002931 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002932 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002933
Eric Laurentfecbceb2021-02-09 14:46:43 +01002934 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002935 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002936 }
2937
2938 *input = AUDIO_IO_HANDLE_NONE;
2939 *inputType = API_INPUT_INVALID;
2940
Francois Gaffie716e1432019-01-14 16:58:59 +01002941 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002942 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002943 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002944 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002945 ALOGW("%s could not find input mix for attr %s",
2946 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002947 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002948 }
jiabinc1de2df2019-05-07 14:26:40 -07002949 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2950 String8(attr->tags + strlen("addr=")),
2951 AUDIO_FORMAT_DEFAULT);
2952 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002953 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002954 __func__, attributes.source, attributes.tags);
2955 status = BAD_VALUE;
2956 goto error;
2957 }
2958
Kevin Rocard25f9b052019-02-27 15:08:54 -08002959 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2960 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2961 } else {
2962 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2963 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002964 if (virtualDeviceId) {
2965 *virtualDeviceId = policyMix->mVirtualDeviceId;
2966 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002967 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002968 if (explicitRoutingDevice != nullptr) {
2969 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002970 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002971 // Prevent from storing invalid requested device id in clients
2972 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002973 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002974 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2975 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002976 }
François Gaffie11d30102018-11-02 16:09:09 +01002977 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002978 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002979 status = BAD_VALUE;
2980 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002981 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002982 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2983 *inputType = API_INPUT_MIX_CAPTURE;
2984 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002985 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2986 // there is an external policy, but this input is attached to a mix of recorders,
2987 // meaning it receives audio injected into the framework, so the recorder doesn't
2988 // know about it and is therefore considered "legacy"
2989 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002990
2991 if (virtualDeviceId) {
2992 *virtualDeviceId = policyMix->mVirtualDeviceId;
2993 }
François Gaffie11d30102018-11-02 16:09:09 +01002994 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002995 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002996 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002997 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002998 } else {
2999 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003000 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003001
Eric Laurent599c7582015-12-07 18:05:55 -08003002 }
3003
François Gaffiec005e562018-11-06 15:04:49 +01003004 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003005 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003006 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003007 AudioProfileVector profiles;
3008 status_t ret = getProfilesForDevices(
3009 DeviceVector(device), profiles, flags, true /*isInput*/);
3010 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003011 const auto channels = profiles[0]->getChannels();
3012 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3013 config->channel_mask = *channels.begin();
3014 }
3015 const auto sampleRates = profiles[0]->getSampleRates();
3016 if (!sampleRates.empty() &&
3017 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3018 config->sample_rate = *sampleRates.begin();
3019 }
jiabinf1c73972022-04-14 16:28:52 -07003020 config->format = profiles[0]->getFormat();
3021 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003022 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003023 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003024
Marvin Ramine5a122d2023-12-07 13:57:59 +01003025
3026 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3027 *virtualDeviceId = policyMix->mVirtualDeviceId;
3028 }
3029
Eric Laurent8f42ea12018-08-08 09:08:25 -07003030exit:
3031
François Gaffiec005e562018-11-06 15:04:49 +01003032 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3033 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003034
Francois Gaffie716e1432019-01-14 16:58:59 +01003035 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003036 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003037 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038
Mikhail Naganov2996f672019-04-18 12:29:59 -07003039 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003040 requestedDeviceId, attributes.source, flags,
3041 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003042 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003043 // Move (if found) effect for the client session to its input
3044 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003045 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003046
3047 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3048 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003049
Eric Laurent599c7582015-12-07 18:05:55 -08003050 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003051
3052error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003053 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003054}
3055
3056
François Gaffie11d30102018-11-02 16:09:09 +01003057audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003058 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003059 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003060 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003061 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003062 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003063{
3064 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003065 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003066 bool isSoundTrigger = false;
3067
François Gaffiec005e562018-11-06 15:04:49 +01003068 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003069 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3070 if (index >= 0) {
3071 input = mSoundTriggerSessions.valueFor(session);
3072 isSoundTrigger = true;
3073 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3074 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3075 } else {
3076 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003077 }
François Gaffiec005e562018-11-06 15:04:49 +01003078 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003079 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003080 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003081 }
3082
Carter Hsua3abb402021-10-26 11:11:20 +08003083 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3084 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3085 }
3086
Eric Laurentfe231122017-11-17 17:48:06 -08003087 // sampling rate and flags may be updated by getInputProfile
3088 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3089 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003090 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003091 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003092 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003093 // find a compatible input profile (not necessarily identical in parameters)
3094 sp<IOProfile> profile = getInputProfile(
3095 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3096 if (profile == nullptr) {
3097 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003098 }
jiabin2fd710d2022-05-02 23:20:22 +00003099
Glenn Kasten05ddca52016-02-11 08:17:12 -08003100 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003101 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003102 if (samplingRate == 0) {
3103 samplingRate = profileSamplingRate;
3104 }
Eric Laurente552edb2014-03-10 17:42:56 -07003105
Eric Laurent322b4d22015-04-03 15:57:54 -07003106 if (profile->getModuleHandle() == 0) {
3107 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003108 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003109 }
3110
Eric Laurentec376dc2021-04-08 20:41:22 +02003111 // Reuse an already opened input if a client with the same session ID already exists
3112 // on that input
3113 for (size_t i = 0; i < mInputs.size(); i++) {
3114 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3115 if (desc->mProfile != profile) {
3116 continue;
3117 }
3118 RecordClientVector clients = desc->clientsList();
3119 for (const auto &client : clients) {
3120 if (session == client->session()) {
3121 return desc->mIoHandle;
3122 }
3123 }
3124 }
3125
Eric Laurent3974e3b2017-12-07 17:58:43 -08003126 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003127 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003128 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003129 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003130 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003131 continue;
3132 }
3133 // if sound trigger, reuse input if used by other sound trigger on same session
3134 // else
3135 // reuse input if active client app is not in IDLE state
3136 //
3137 RecordClientVector clients = desc->clientsList();
3138 bool doClose = false;
3139 for (const auto& client : clients) {
3140 if (isSoundTrigger != client->isSoundTrigger()) {
3141 continue;
3142 }
3143 if (client->isSoundTrigger()) {
3144 if (session == client->session()) {
3145 return desc->mIoHandle;
3146 }
3147 continue;
3148 }
3149 if (client->active() && client->appState() != APP_STATE_IDLE) {
3150 return desc->mIoHandle;
3151 }
3152 doClose = true;
3153 }
3154 if (doClose) {
3155 closeInput(desc->mIoHandle);
3156 } else {
3157 i++;
3158 }
3159 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003160 }
3161
Eric Laurentfe231122017-11-17 17:48:06 -08003162 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003163
Eric Laurentfe231122017-11-17 17:48:06 -08003164 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3165 lConfig.sample_rate = profileSamplingRate;
3166 lConfig.channel_mask = profileChannelMask;
3167 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003168
François Gaffie11d30102018-11-02 16:09:09 +01003169 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003170
3171 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003172 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003173 (profileSamplingRate != lConfig.sample_rate) ||
3174 !audio_formats_match(profileFormat, lConfig.format) ||
3175 (profileChannelMask != lConfig.channel_mask)) {
3176 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003177 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003178 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003179 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003180 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003181 }
Eric Laurent599c7582015-12-07 18:05:55 -08003182 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003183 }
3184
Eric Laurentc722f302014-12-10 11:21:49 -08003185 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003186
Eric Laurent599c7582015-12-07 18:05:55 -08003187 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003188 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003189
Eric Laurent599c7582015-12-07 18:05:55 -08003190 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003191}
3192
Eric Laurent4eb58f12018-12-07 16:41:02 -08003193status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003194{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003195 ALOGV("%s portId %d", __FUNCTION__, portId);
3196
3197 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3198 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003199 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003200 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003201 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003202 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003203 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003204 if (client->active()) {
3205 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3206 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003207 }
3208
Eric Laurent8f42ea12018-08-08 09:08:25 -07003209 audio_session_t session = client->session();
3210
Eric Laurent4eb58f12018-12-07 16:41:02 -08003211 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003212
Eric Laurent4eb58f12018-12-07 16:41:02 -08003213 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003214
Eric Laurent4eb58f12018-12-07 16:41:02 -08003215 status_t status = inputDesc->start();
3216 if (status != NO_ERROR) {
3217 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003218 }
Eric Laurente552edb2014-03-10 17:42:56 -07003219
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003220 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003221 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003222 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003223
Eric Laurent8f42ea12018-08-08 09:08:25 -07003224 // indicate active capture to sound trigger service if starting capture from a mic on
3225 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003226 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003227 if (device != nullptr) {
3228 status = setInputDevice(input, device, true /* force */);
3229 } else {
3230 ALOGW("%s no new input device can be found for descriptor %d",
3231 __FUNCTION__, inputDesc->getId());
3232 status = BAD_VALUE;
3233 }
Eric Laurente552edb2014-03-10 17:42:56 -07003234
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003235 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003236 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003237 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003238 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003239 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3240 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003241 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003242 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003243
François Gaffie11d30102018-11-02 16:09:09 +01003244 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3245 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003246 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003247 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003248 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003249
Eric Laurent8f42ea12018-08-08 09:08:25 -07003250 // automatically enable the remote submix output when input is started if not
3251 // used by a policy mix of type MIX_TYPE_RECORDERS
3252 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003253 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003254 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003255 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003256 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003257 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3258 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003259 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003260 if (address != "") {
3261 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3262 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003263 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003264 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003265 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003266 } else if (status != NO_ERROR) {
3267 // Restore client activity state.
3268 inputDesc->setClientActive(client, false);
3269 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003270 }
3271
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003272 ALOGV("%s input %d source = %d status = %d exit",
3273 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003274
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003275 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003276}
3277
Eric Laurent8fc147b2018-07-22 19:13:55 -07003278status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003279{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003280 ALOGV("%s portId %d", __FUNCTION__, portId);
3281
3282 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3283 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003285 return BAD_VALUE;
3286 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003287 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003288 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003289 if (!client->active()) {
3290 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003291 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003292 }
Carter Hsue6139d52021-07-08 10:30:20 +08003293 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003294 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003295
Eric Laurent8f42ea12018-08-08 09:08:25 -07003296 inputDesc->stop();
3297 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003298 auto current_source = inputDesc->source();
3299 setInputDevice(input, getNewInputDevice(inputDesc),
3300 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003301 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003302 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003303 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003304 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003305 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3306 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003307 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003308 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003309
3310 // automatically disable the remote submix output when input is stopped if not
3311 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003312 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003313 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003314 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003315 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003316 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3317 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003318 }
3319 if (address != "") {
3320 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3321 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003322 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003323 }
3324 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003325 resetInputDevice(input);
3326
3327 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3328 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003329 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3330 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003331 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003332 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003333 }
3334 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003335 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003336 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003337}
3338
Eric Laurent8fc147b2018-07-22 19:13:55 -07003339void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003340{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003341 ALOGV("%s portId %d", __FUNCTION__, portId);
3342
3343 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3344 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003345 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003346 return;
3347 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003348 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003349 audio_io_handle_t input = inputDesc->mIoHandle;
3350
Eric Laurent8f42ea12018-08-08 09:08:25 -07003351 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003352
Andy Hung39efb7a2018-09-26 15:39:28 -07003353 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003354
3355 // If no more clients are present in this session, park effects to an orphan chain
3356 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3357 if (clientsOnSession.size() == 0) {
3358 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3359 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003360 if (inputDesc->getClientCount() > 0) {
3361 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003362 return;
3363 }
3364
Eric Laurent05b90f82014-08-27 15:32:29 -07003365 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003366 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003367 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003368}
3369
Eric Laurent8f42ea12018-08-08 09:08:25 -07003370void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003371{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003372 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003373
3374 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003375 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003376 }
3377}
3378
Eric Laurent8f42ea12018-08-08 09:08:25 -07003379void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3380{
3381 stopInput(portId);
3382 releaseInput(portId);
3383}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003384
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003385bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3386 if (input->clientsList().size() == 0
3387 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3388 return true;
3389 }
3390 for (const auto& client : input->clientsList()) {
3391 sp<DeviceDescriptor> device =
3392 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3393 client->session());
3394 if (!input->supportedDevices().contains(device)) {
3395 return true;
3396 }
3397 }
3398 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3399 return false;
3400}
3401
Eric Laurent0dd51852019-04-19 18:18:58 -07003402void AudioPolicyManager::checkCloseInputs() {
3403 // After connecting or disconnecting an input device, close input if:
3404 // - it has no client (was just opened to check profile) OR
3405 // - none of its supported devices are connected anymore OR
3406 // - one of its clients cannot be routed to one of its supported
3407 // devices anymore. Otherwise update device selection
3408 std::vector<audio_io_handle_t> inputsToClose;
3409 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003410 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003411 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003412 }
3413 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003414 for (const audio_io_handle_t handle : inputsToClose) {
3415 ALOGV("%s closing input %d", __func__, handle);
3416 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003417 }
Eric Laurentd4692962014-05-05 18:13:44 -07003418}
3419
Vlad Popa87e0e582024-05-20 18:49:20 -07003420status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3421 const char *address __unused,
3422 bool enabled,
3423 audio_stream_type_t streamToDriveAbs)
3424{
3425 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3426 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3427 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3428 toString(streamToDriveAbs).c_str());
3429 return BAD_VALUE;
3430 }
3431
3432 if (enabled) {
3433 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3434 } else {
3435 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3436 }
3437
3438 return NO_ERROR;
3439}
3440
François Gaffie251c7f02018-11-07 10:41:08 +01003441void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003442{
3443 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003444 if (indexMin < 0 || indexMax < 0) {
3445 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3446 return;
3447 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003448 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003449
3450 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003451 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3452 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003453 continue;
3454 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003455 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003456 }
Eric Laurente552edb2014-03-10 17:42:56 -07003457}
3458
Eric Laurente0720872014-03-11 09:30:41 -07003459status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003460 int index,
3461 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003462{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003463 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003464 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3465 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3466 return NO_ERROR;
3467 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303468 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3469 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003470 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003471}
3472
Eric Laurente0720872014-03-11 09:30:41 -07003473status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003474 int *index,
3475 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003476{
François Gaffiec005e562018-11-06 15:04:49 +01003477 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3478 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003479 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003480 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003481 deviceTypes = mEngine->getOutputDevicesForStream(
3482 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003483 }
jiabin9a3361e2019-10-01 09:38:30 -07003484 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003485}
3486
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003487status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003488 int index,
3489 audio_devices_t device)
3490{
3491 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003492 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3493 if (group == VOLUME_GROUP_NONE) {
3494 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003495 return BAD_VALUE;
3496 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003497 ALOGV("%s: group %d matching with %s index %d",
3498 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003499 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003500 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003501 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003502 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3503 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3504 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3505 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003506 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3507
3508 status = setVolumeCurveIndex(index, device, curves);
3509 if (status != NO_ERROR) {
3510 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3511 return status;
3512 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003513
jiabin9a3361e2019-10-01 09:38:30 -07003514 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003515 auto curCurvAttrs = curves.getAttributes();
3516 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3517 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003518 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003519 } else if (!curves.getStreamTypes().empty()) {
3520 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003521 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003522 } else {
3523 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3524 return BAD_VALUE;
3525 }
jiabin9a3361e2019-10-01 09:38:30 -07003526 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3527 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003528
François Gaffiecfe17322018-11-07 13:41:29 +01003529 // update volume on all outputs and streams matching the following:
3530 // - The requested stream (or a stream matching for volume control) is active on the output
3531 // - The device (or devices) selected by the engine for this stream includes
3532 // the requested device
3533 // - For non default requested device, currently selected device on the output is either the
3534 // requested device or one of the devices selected by the engine for this stream
3535 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3536 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003537 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003538 for (size_t i = 0; i < mOutputs.size(); i++) {
3539 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003540 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003541
jiabin9a3361e2019-10-01 09:38:30 -07003542 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3543 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003544 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003545
3546 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003547 continue;
3548 }
3549 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3550 curDevices.find(device) == curDevices.end()) {
3551 continue;
3552 }
3553 bool applyVolume = false;
3554 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3555 curSrcDevices.insert(device);
3556 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003557 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3558 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003559 } else {
3560 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3561 }
3562 if (!applyVolume) {
3563 continue; // next output
3564 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003565 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3566 // If a higher priority strategy is active, and the output is routed to a device with a
3567 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003568 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003569 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003570 // If the volume source is active with higher priority source, ensure at least Sw Muted
3571 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003572 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3573 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3574 false /*preferredDevice*/);
3575 if (activeClients.empty()) {
3576 continue;
3577 }
3578 bool isPreempted = false;
3579 bool isHigherPriority = productStrategy < strategy;
3580 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003581 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003582 ALOGV("%s: Strategy=%d (\nrequester:\n"
3583 " group %d, volumeGroup=%d attributes=%s)\n"
3584 " higher priority source active:\n"
3585 " volumeGroup=%d attributes=%s) \n"
3586 " on output %zu, bailing out", __func__, productStrategy,
3587 group, group, toString(attributes).c_str(),
3588 client->volumeSource(), toString(client->attributes()).c_str(), i);
3589 applyVolume = false;
3590 isPreempted = true;
3591 break;
3592 }
3593 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003594 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003595 applyVolume = true;
3596 }
3597 }
3598 if (isPreempted || applyVolume) {
3599 break;
3600 }
3601 }
3602 if (!applyVolume) {
3603 continue; // next output
3604 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003605 }
François Gaffieed91f582020-01-31 10:35:37 +01003606 //FIXME: workaround for truncated touch sounds
3607 // delayed volume change for system stream to be removed when the problem is
3608 // handled by system UI
3609 status_t volStatus = checkAndSetVolume(
3610 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003611 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003612 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3613 if (volStatus != NO_ERROR) {
3614 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003615 }
3616 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003617
3618 // update voice volume if the an active call route exists
3619 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3620 && (curSrcDevices.find(
3621 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3622 != curSrcDevices.end())) {
3623 bool isVoiceVolSrc;
3624 bool isBtScoVolSrc;
3625 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3626 isVoiceVolSrc, isBtScoVolSrc, __func__)
3627 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003628 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3629 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3630 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003631 }
3632 }
3633
François Gaffiecfe17322018-11-07 13:41:29 +01003634 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3635 return status;
3636}
3637
François Gaffieaaac0fd2018-11-22 17:56:39 +01003638status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003639 audio_devices_t device,
3640 IVolumeCurves &volumeCurves)
3641{
3642 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3643 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003644 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3645 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003646 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303647 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3648 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003649 return BAD_VALUE;
3650 }
3651 if (!audio_is_output_device(device)) {
3652 return BAD_VALUE;
3653 }
3654
3655 // Force max volume if stream cannot be muted
3656 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3657
François Gaffieaaac0fd2018-11-22 17:56:39 +01003658 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003659 volumeCurves.addCurrentVolumeIndex(device, index);
3660 return NO_ERROR;
3661}
3662
3663status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3664 int &index,
3665 audio_devices_t device)
3666{
3667 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3668 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003669 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003670 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003671 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003672 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003673 }
jiabin9a3361e2019-10-01 09:38:30 -07003674 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003675}
3676
3677status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3678 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003679 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003680{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003681 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003682 return BAD_VALUE;
3683 }
jiabin9a3361e2019-10-01 09:38:30 -07003684 index = curves.getVolumeIndex(deviceTypes);
3685 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003686 return NO_ERROR;
3687}
3688
3689status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3690 int &index)
3691{
3692 index = getVolumeCurves(attr).getVolumeIndexMin();
3693 return NO_ERROR;
3694}
3695
3696status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3697 int &index)
3698{
3699 index = getVolumeCurves(attr).getVolumeIndexMax();
3700 return NO_ERROR;
3701}
3702
Eric Laurent36829f92017-04-07 19:04:42 -07003703audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003704{
3705 // select one output among several suitable for global effects.
3706 // The priority is as follows:
3707 // 1: An offloaded output. If the effect ends up not being offloadable,
3708 // AudioFlinger will invalidate the track and the offloaded output
3709 // will be closed causing the effect to be moved to a PCM output.
3710 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003711 // 3: The primary output
3712 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003713
François Gaffiec005e562018-11-06 15:04:49 +01003714 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3715 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003716 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003717
Eric Laurent36829f92017-04-07 19:04:42 -07003718 if (outputs.size() == 0) {
3719 return AUDIO_IO_HANDLE_NONE;
3720 }
Eric Laurente552edb2014-03-10 17:42:56 -07003721
Eric Laurent36829f92017-04-07 19:04:42 -07003722 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3723 bool activeOnly = true;
3724
3725 while (output == AUDIO_IO_HANDLE_NONE) {
3726 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3727 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3728 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3729
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003730 for (audio_io_handle_t output : outputs) {
3731 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003732 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003733 continue;
3734 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003735 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3736 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003737 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003738 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003739 }
3740 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003741 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003742 }
3743 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003744 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003745 }
3746 }
3747 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3748 output = outputOffloaded;
3749 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3750 output = outputDeepBuffer;
3751 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3752 output = outputPrimary;
3753 } else {
3754 output = outputs[0];
3755 }
3756 activeOnly = false;
3757 }
3758
3759 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003760 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3761 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003762 mMusicEffectOutput = output;
3763 }
3764
3765 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003766 return output;
3767}
3768
Eric Laurent36829f92017-04-07 19:04:42 -07003769audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3770{
3771 return selectOutputForMusicEffects();
3772}
3773
Eric Laurente0720872014-03-11 09:30:41 -07003774status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003775 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003776 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003777 int session,
3778 int id)
3779{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003780 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003781 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003782 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003783 index = mInputs.indexOfKey(io);
3784 if (index < 0) {
3785 ALOGW("registerEffect() unknown io %d", io);
3786 return INVALID_OPERATION;
3787 }
Eric Laurente552edb2014-03-10 17:42:56 -07003788 }
3789 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003790 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3791 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3792 || strategy == PRODUCT_STRATEGY_NONE));
3793 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003794}
3795
Eric Laurentc241b0d2018-11-28 09:08:49 -08003796status_t AudioPolicyManager::unregisterEffect(int id)
3797{
3798 if (mEffects.getEffect(id) == nullptr) {
3799 return INVALID_OPERATION;
3800 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003801 if (mEffects.isEffectEnabled(id)) {
3802 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3803 setEffectEnabled(id, false);
3804 }
3805 return mEffects.unregisterEffect(id);
3806}
3807
3808status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3809{
3810 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3811 if (effect == nullptr) {
3812 return INVALID_OPERATION;
3813 }
3814
3815 status_t status = mEffects.setEffectEnabled(id, enabled);
3816 if (status == NO_ERROR) {
3817 mInputs.trackEffectEnabled(effect, enabled);
3818 }
3819 return status;
3820}
3821
Eric Laurent6c796322019-04-09 14:13:17 -07003822
3823status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3824{
3825 mEffects.moveEffects(ids, io);
3826 return NO_ERROR;
3827}
3828
Eric Laurentc75307b2015-03-17 15:29:32 -07003829bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3830{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003831 auto vs = toVolumeSource(stream, false);
3832 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003833}
3834
3835bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3836{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003837 auto vs = toVolumeSource(stream, false);
3838 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003839}
3840
Eric Laurente0720872014-03-11 09:30:41 -07003841bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003842{
3843 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003844 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003845 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003846 return true;
3847 }
3848 }
3849 return false;
3850}
3851
Eric Laurent275e8e92014-11-30 15:14:47 -08003852// Register a list of custom mixes with their attributes and format.
3853// When a mix is registered, corresponding input and output profiles are
3854// added to the remote submix hw module. The profile contains only the
3855// parameters (sampling rate, format...) specified by the mix.
3856// The corresponding input remote submix device is also connected.
3857//
3858// When a remote submix device is connected, the address is checked to select the
3859// appropriate profile and the corresponding input or output stream is opened.
3860//
3861// When capture starts, getInputForAttr() will:
3862// - 1 look for a mix matching the address passed in attribtutes tags if any
3863// - 2 if none found, getDeviceForInputSource() will:
3864// - 2.1 look for a mix matching the attributes source
3865// - 2.2 if none found, default to device selection by policy rules
3866// At this time, the corresponding output remote submix device is also connected
3867// and active playback use cases can be transferred to this mix if needed when reconnecting
3868// after AudioTracks are invalidated
3869//
3870// When playback starts, getOutputForAttr() will:
3871// - 1 look for a mix matching the address passed in attribtutes tags if any
3872// - 2 if none found, look for a mix matching the attributes usage
3873// - 3 if none found, default to device and output selection by policy rules.
3874
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003875status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003876{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003877 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3878 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003879 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003880 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003881 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003882 // examine each mix's route type
3883 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003884 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003885 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3886 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3887 ALOGE("Unsupported Policy Mix %zu of %zu: "
3888 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3889 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003890 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003891 break;
3892 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003893 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3894 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003895 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003896 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3897 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003898 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003899 rSubmixModule = mHwModules.getModuleFromName(
3900 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3901 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003902 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003903 i);
3904 res = INVALID_OPERATION;
3905 break;
3906 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003907 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003908
Eric Laurent97ac8712018-07-27 18:59:02 -07003909 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003910 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003911 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003912 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003913 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3914 } else {
3915 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3916 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003917 }
François Gaffie036e1e92015-03-19 10:16:24 +01003918
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003919 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003920 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003921 res = INVALID_OPERATION;
3922 break;
3923 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003924 audio_config_t outputConfig = mix.mFormat;
3925 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003926 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3927 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003928 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3929 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003930 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003931 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3932 audio_is_linear_pcm(outputConfig.format)
3933 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003934 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003935 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3936 audio_is_linear_pcm(inputConfig.format)
3937 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003938
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003939 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003940 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003941 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003942 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003943 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003944 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003945 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003946 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3947 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003948 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003949 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003950 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003951
3952 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3953 mix.mDeviceType, mix.mDeviceAddress,
3954 String8(), AUDIO_FORMAT_DEFAULT);
3955 if (device == nullptr) {
3956 res = INVALID_OPERATION;
3957 break;
3958 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003959
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003960 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003961 // First try to find an already opened output supporting the device
3962 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003963 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003964
Eric Laurentc529cf62020-04-17 18:19:10 -07003965 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003966 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003967 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003968 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003969 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003970 } else {
3971 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003972 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003973 }
3974 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003975 // If no output found, try to find a direct output profile supporting the device
3976 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3977 sp<HwModule> module = mHwModules[i];
3978 for (size_t j = 0;
3979 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3980 j++) {
3981 sp<IOProfile> profile = module->getOutputProfiles()[j];
3982 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3983 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3984 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003985 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003986 res = INVALID_OPERATION;
3987 } else {
3988 foundOutput = true;
3989 }
3990 }
3991 }
3992 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003993 if (res != NO_ERROR) {
3994 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003995 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003996 res = INVALID_OPERATION;
3997 break;
3998 } else if (!foundOutput) {
3999 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004000 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004001 res = INVALID_OPERATION;
4002 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004003 } else {
4004 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004005 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004006 }
Eric Laurentc722f302014-12-10 11:21:49 -08004007 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004008 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004009 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004010 if (audio_flags::audio_mix_ownership()) {
4011 // Only unregister mixes that were actually registered to not accidentally unregister
4012 // mixes that already existed previously.
4013 unregisterPolicyMixes(registeredMixes);
4014 registeredMixes.clear();
4015 } else {
4016 unregisterPolicyMixes(mixes);
4017 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004018 } else if (checkOutputs) {
4019 checkForDeviceAndOutputChanges();
4020 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004021 }
4022 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004023}
4024
4025status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4026{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004027 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004028 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004029 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004030 sp<HwModule> rSubmixModule;
4031 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004032 for (const auto& mix : mixes) {
4033 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004034
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004035 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004036 rSubmixModule = mHwModules.getModuleFromName(
4037 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4038 if (rSubmixModule == 0) {
4039 res = INVALID_OPERATION;
4040 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004041 }
4042 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004043
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004044 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004045
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004046 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004047 res = INVALID_OPERATION;
4048 continue;
4049 }
4050
Marvin Ramin0783e202024-03-05 12:45:50 +01004051 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004052 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004053 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4054 status_t currentRes =
4055 setDeviceConnectionStateInt(device,
4056 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4057 address.c_str(),
4058 "remote-submix",
4059 AUDIO_FORMAT_DEFAULT);
4060 if (!audio_flags::audio_mix_ownership()) {
4061 res = currentRes;
4062 }
4063 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004064 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004065 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004066 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004067 }
4068 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004069 }
jiabin5740f082019-08-19 15:08:30 -07004070 rSubmixModule->removeOutputProfile(address.c_str());
4071 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004072
Kevin Rocard153f92d2018-12-18 18:33:28 -08004073 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004074 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004075 res = INVALID_OPERATION;
4076 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004077 } else {
4078 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004079 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004080 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004081 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004082
4083 if (res == NO_ERROR && checkOutputs) {
4084 checkForDeviceAndOutputChanges();
4085 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004086 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004087 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004088}
4089
Marvin Raminbdefaf02023-11-01 09:10:32 +01004090status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4091 if (!audio_flags::audio_mix_test_api()) {
4092 return INVALID_OPERATION;
4093 }
4094
4095 _aidl_return.clear();
4096 _aidl_return.reserve(mPolicyMixes.size());
4097 for (const auto &policyMix: mPolicyMixes) {
4098 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4099 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4100 policyMix->mCbFlags);
4101 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004102 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004103 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004104 }
4105
Vlad Popaa5d73f32024-03-08 16:05:38 -08004106 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004107 return OK;
4108}
4109
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004110status_t AudioPolicyManager::updatePolicyMix(
4111 const AudioMix& mix,
4112 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4113 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4114 if (res == NO_ERROR) {
4115 checkForDeviceAndOutputChanges();
4116 updateCallAndOutputRouting();
4117 }
4118 return res;
4119}
4120
Mikhail Naganov100f0122018-11-29 11:22:16 -08004121void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4122{
4123 size_t i = 0;
4124 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4125 for (const auto& fmt : mManualSurroundFormats) {
4126 if (i++ != 0) dst->append(", ");
4127 std::string sfmt;
4128 FormatConverter::toString(fmt, sfmt);
4129 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4130 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4131 }
4132}
4133
Eric Laurentc529cf62020-04-17 18:19:10 -07004134// Returns true if all devices types match the predicate and are supported by one HW module
4135bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004136 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004137 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004138 const char *context,
4139 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004140 for (size_t i = 0; i < devices.size(); i++) {
4141 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004142 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004143 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004144 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004145 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004146 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004147 return false;
4148 }
4149 }
4150 return true;
4151}
4152
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004153void AudioPolicyManager::changeOutputDevicesMuteState(
4154 const AudioDeviceTypeAddrVector& devices) {
4155 ALOGVV("%s() num devices %zu", __func__, devices.size());
4156
4157 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4158 getSoftwareOutputsForDevices(devices);
4159
4160 for (size_t i = 0; i < outputs.size(); i++) {
4161 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4162 DeviceVector prevDevices = outputDesc->devices();
4163 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4164 }
4165}
4166
4167std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4168 const AudioDeviceTypeAddrVector& devices) const
4169{
4170 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4171 DeviceVector deviceDescriptors;
4172 for (size_t j = 0; j < devices.size(); j++) {
4173 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4174 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4175 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4176 ALOGE("%s: device type %#x address %s not supported or not an output device",
4177 __func__, devices[j].mType, devices[j].getAddress());
4178 continue;
4179 }
4180 deviceDescriptors.add(desc);
4181 }
4182 for (size_t i = 0; i < mOutputs.size(); i++) {
4183 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4184 continue;
4185 }
4186 outputs.push_back(mOutputs.valueAt(i));
4187 }
4188 return outputs;
4189}
4190
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004191status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004192 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004193 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004194 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4195 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004196 }
4197 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004198 if (res != NO_ERROR) {
4199 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4200 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004201 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004202
4203 checkForDeviceAndOutputChanges();
4204 updateCallAndOutputRouting();
4205
4206 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004207}
4208
4209status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4210 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004211 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4212 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004213 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004214 __FUNCTION__, uid);
4215 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004216 }
4217
Eric Laurentc529cf62020-04-17 18:19:10 -07004218 checkForDeviceAndOutputChanges();
4219 updateCallAndOutputRouting();
4220
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004221 return res;
4222}
4223
Eric Laurent2517af32020-11-25 15:31:27 +01004224
jiabin0a488932020-08-07 17:32:40 -07004225status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4226 device_role_t role,
4227 const AudioDeviceTypeAddrVector &devices) {
4228 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4229 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004230
Eric Laurentc529cf62020-04-17 18:19:10 -07004231 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004232 return BAD_VALUE;
4233 }
jiabin0a488932020-08-07 17:32:40 -07004234 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004235 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004236 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4237 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004238 return status;
4239 }
4240
4241 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004242
4243 bool forceVolumeReeval = false;
4244 // FIXME: workaround for truncated touch sounds
4245 // to be removed when the problem is handled by system UI
4246 uint32_t delayMs = 0;
4247 if (strategy == mCommunnicationStrategy) {
4248 forceVolumeReeval = true;
4249 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4250 updateInputRouting();
4251 }
4252 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004253
4254 return NO_ERROR;
4255}
4256
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004257void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4258 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004259{
4260 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004261 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004262 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004263 // Only apply special touch sound delay once
4264 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004265 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004266 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004267 for (size_t i = 0; i < mOutputs.size(); i++) {
4268 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4269 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004270 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4271 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004272 // As done in setDeviceConnectionState, we could also fix default device issue by
4273 // preventing the force re-routing in case of default dev that distinguishes on address.
4274 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004275 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004276 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004277 // If the device is using preferred mixer attributes, the output need to reopen
4278 // with default configuration when the new selected devices are different from
4279 // current routing devices.
4280 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4281 continue;
4282 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304283
4284 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4285 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004286 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004287 // Only apply special touch sound delay once
4288 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004289 }
4290 if (forceVolumeReeval && !newDevices.isEmpty()) {
4291 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4292 }
4293 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004294 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004295 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004296}
4297
Eric Laurent2517af32020-11-25 15:31:27 +01004298void AudioPolicyManager::updateInputRouting() {
4299 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304300 // Skip for hotword recording as the input device switch
4301 // is handled within sound trigger HAL
4302 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4303 continue;
4304 }
Eric Laurent2517af32020-11-25 15:31:27 +01004305 auto newDevice = getNewInputDevice(activeDesc);
4306 // Force new input selection if the new device can not be reached via current input
4307 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4308 setInputDevice(activeDesc->mIoHandle, newDevice);
4309 } else {
4310 closeInput(activeDesc->mIoHandle);
4311 }
4312 }
4313}
4314
Paul Wang5d7cdb52022-11-22 09:45:06 +00004315status_t
4316AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4317 device_role_t role,
4318 const AudioDeviceTypeAddrVector &devices) {
4319 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4320 dumpAudioDeviceTypeAddrVector(devices).c_str());
4321
Eric Laurent78fedbf2023-03-09 14:40:44 +01004322 if (!areAllDevicesSupported(
4323 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004324 return BAD_VALUE;
4325 }
4326 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4327 if (status != NO_ERROR) {
4328 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4329 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4330 return status;
4331 }
4332
4333 checkForDeviceAndOutputChanges();
4334
4335 bool forceVolumeReeval = false;
4336 // TODO(b/263479999): workaround for truncated touch sounds
4337 // to be removed when the problem is handled by system UI
4338 uint32_t delayMs = 0;
4339 if (strategy == mCommunnicationStrategy) {
4340 forceVolumeReeval = true;
4341 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4342 updateInputRouting();
4343 }
4344 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4345
4346 return NO_ERROR;
4347}
4348
4349status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4350 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004351{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004352 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004353
Paul Wang5d7cdb52022-11-22 09:45:06 +00004354 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004355 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004356 ALOGW_IF(status != NAME_NOT_FOUND,
4357 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004358 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004359 return status;
4360 }
4361
4362 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004363
4364 bool forceVolumeReeval = false;
4365 // FIXME: workaround for truncated touch sounds
4366 // to be removed when the problem is handled by system UI
4367 uint32_t delayMs = 0;
4368 if (strategy == mCommunnicationStrategy) {
4369 forceVolumeReeval = true;
4370 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4371 updateInputRouting();
4372 }
4373 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004374
4375 return NO_ERROR;
4376}
4377
jiabin0a488932020-08-07 17:32:40 -07004378status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4379 device_role_t role,
4380 AudioDeviceTypeAddrVector &devices) {
4381 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004382}
4383
Jiabin Huang3b98d322020-09-03 17:54:16 +00004384status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4385 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4386 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4387 dumpAudioDeviceTypeAddrVector(devices).c_str());
4388
Mikhail Naganov55773032020-10-01 15:08:13 -07004389 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004390 return BAD_VALUE;
4391 }
4392 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4393 ALOGW_IF(status != NO_ERROR,
4394 "Engine could not set preferred devices %s for audio source %d role %d",
4395 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4396
4397 return status;
4398}
4399
4400status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4401 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4402 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4403 dumpAudioDeviceTypeAddrVector(devices).c_str());
4404
Mikhail Naganov55773032020-10-01 15:08:13 -07004405 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004406 return BAD_VALUE;
4407 }
4408 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4409 ALOGW_IF(status != NO_ERROR,
4410 "Engine could not add preferred devices %s for audio source %d role %d",
4411 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4412
Eric Laurent2517af32020-11-25 15:31:27 +01004413 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004414 return status;
4415}
4416
4417status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4418 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4419{
4420 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4421 dumpAudioDeviceTypeAddrVector(devices).c_str());
4422
Eric Laurent78fedbf2023-03-09 14:40:44 +01004423 if (!areAllDevicesSupported(
4424 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004425 return BAD_VALUE;
4426 }
4427
4428 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4429 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004430 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004431 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004432 if (status == NO_ERROR) {
4433 updateInputRouting();
4434 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004435 return status;
4436}
4437
4438status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4439 device_role_t role) {
4440 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4441
4442 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004443 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004444 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004445 if (status == NO_ERROR) {
4446 updateInputRouting();
4447 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004448 return status;
4449}
4450
4451status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4452 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4453 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4454}
4455
Oscar Azucena90e77632019-11-27 17:12:28 -08004456status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004457 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004458 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004459 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4460 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004461 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004462 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4463 if (status != NO_ERROR) {
4464 ALOGE("%s() could not set device affinity for userId %d",
4465 __FUNCTION__, userId);
4466 return status;
4467 }
4468
4469 // reevaluate outputs for all devices
4470 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004471 changeOutputDevicesMuteState(devices);
4472 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4473 true /* skipDelays */);
4474 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004475
4476 return NO_ERROR;
4477}
4478
4479status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004480 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004481 AudioDeviceTypeAddrVector devices;
4482 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004483 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4484 if (status != NO_ERROR) {
4485 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4486 __FUNCTION__, userId);
4487 return status;
4488 }
4489
4490 // reevaluate outputs for all devices
4491 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004492 changeOutputDevicesMuteState(devices);
4493 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4494 true /* skipDelays */);
4495 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004496
4497 return NO_ERROR;
4498}
4499
Andy Hungc29d82b2018-10-05 12:23:17 -07004500void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004501{
Andy Hungc29d82b2018-10-05 12:23:17 -07004502 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004503 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004504 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004505 std::string stateLiteral;
4506 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004507 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004508 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4509 "communications", "media", "record", "dock", "system",
4510 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4511 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4512 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004513 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4514 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4515 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4516 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4517 dst->append(" (MANUAL: ");
4518 dumpManualSurroundFormats(dst);
4519 dst->append(")");
4520 }
4521 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004522 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004523 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4524 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004525 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004526 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004527
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004528 dst->append("\n");
4529 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4530 dst->append("\n");
4531 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004532 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004533 mOutputs.dump(dst);
4534 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004535 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004536 mAudioPatches.dump(dst);
4537 mPolicyMixes.dump(dst);
4538 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004539
Kevin Rocardb99cc752019-03-21 20:52:24 -07004540 dst->appendFormat(" AllowedCapturePolicies:\n");
4541 for (auto& policy : mAllowedCapturePolicies) {
4542 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4543 }
4544
jiabina84c3d32022-12-02 18:59:55 +00004545 dst->appendFormat(" Preferred mixer audio configuration:\n");
4546 for (const auto it : mPreferredMixerAttrInfos) {
4547 dst->appendFormat(" - device port id: %d\n", it.first);
4548 for (const auto preferredMixerInfoIt : it.second) {
4549 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4550 preferredMixerInfoIt.second->dump(dst);
4551 }
4552 }
4553
François Gaffiec005e562018-11-06 15:04:49 +01004554 dst->appendFormat("\nPolicy Engine dump:\n");
4555 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004556
4557 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4558 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4559 dst->appendFormat(" - device type: %s, driving stream %d\n",
4560 dumpDeviceTypes({it.first}).c_str(),
4561 mEngine->getVolumeGroupForAttributes(it.second));
4562 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004563}
4564
4565status_t AudioPolicyManager::dump(int fd)
4566{
4567 String8 result;
4568 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004569 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004570 return NO_ERROR;
4571}
4572
Kevin Rocardb99cc752019-03-21 20:52:24 -07004573status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4574{
4575 mAllowedCapturePolicies[uid] = capturePolicy;
4576 return NO_ERROR;
4577}
4578
Eric Laurente552edb2014-03-10 17:42:56 -07004579// This function checks for the parameters which can be offloaded.
4580// This can be enhanced depending on the capability of the DSP and policy
4581// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004582audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004583{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004584 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004585 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004586 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004587 offloadInfo.format,
4588 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4589 offloadInfo.has_video);
4590
jiabin2b9d5a12021-12-10 01:06:29 +00004591 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004592 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004593 }
4594
4595 // See if there is a profile to support this.
4596 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004597 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004598 offloadInfo.sample_rate,
4599 offloadInfo.format,
4600 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004601 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4602 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004603 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4604 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4605 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004606 if (profile == nullptr) {
4607 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4608 }
4609 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4610 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4611 }
4612 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004613}
4614
Michael Chana94fbb22018-04-24 14:31:19 +10004615bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4616 const audio_attributes_t& attributes) {
4617 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004618 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004619 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4620 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004621 config.sample_rate,
4622 config.format,
4623 config.channel_mask,
4624 output_flags,
4625 true /* directOnly */);
4626 ALOGV("%s() profile %sfound with name: %s, "
4627 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4628 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004629 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004630 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004631
4632 // also try the MSD module if compatible profile not found
4633 if (profile == nullptr) {
4634 profile = getMsdProfileForOutput(outputDevices,
4635 config.sample_rate,
4636 config.format,
4637 config.channel_mask,
4638 output_flags,
4639 true /* directOnly */);
4640 ALOGV("%s() MSD profile %sfound with name: %s, "
4641 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4642 __FUNCTION__, profile != 0 ? "" : "NOT ",
4643 (profile != 0 ? profile->getTagName().c_str() : "null"),
4644 config.sample_rate, config.format, config.channel_mask, output_flags);
4645 }
4646 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004647}
4648
jiabin2b9d5a12021-12-10 01:06:29 +00004649bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4650 bool durationIgnored) {
4651 if (mMasterMono) {
4652 return false; // no offloading if mono is set.
4653 }
4654
4655 // Check if offload has been disabled
4656 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4657 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4658 return false;
4659 }
4660
4661 // Check if stream type is music, then only allow offload as of now.
4662 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4663 {
4664 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4665 return false;
4666 }
4667
4668 //TODO: enable audio offloading with video when ready
4669 const bool allowOffloadWithVideo =
4670 property_get_bool("audio.offload.video", false /* default_value */);
4671 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4672 ALOGV("%s: has_video == true, returning false", __func__);
4673 return false;
4674 }
4675
4676 //If duration is less than minimum value defined in property, return false
4677 const int min_duration_secs = property_get_int32(
4678 "audio.offload.min.duration.secs", -1 /* default_value */);
4679 if (!durationIgnored) {
4680 if (min_duration_secs >= 0) {
4681 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4682 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4683 __func__, min_duration_secs);
4684 return false;
4685 }
4686 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4687 ALOGV("%s: Offload denied by duration < default min(=%u)",
4688 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4689 return false;
4690 }
4691 }
4692
4693 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4694 // creating an offloaded track and tearing it down immediately after start when audioflinger
4695 // detects there is an active non offloadable effect.
4696 // FIXME: We should check the audio session here but we do not have it in this context.
4697 // This may prevent offloading in rare situations where effects are left active by apps
4698 // in the background.
4699 if (mEffects.isNonOffloadableEffectEnabled()) {
4700 return false;
4701 }
4702
4703 return true;
4704}
4705
4706audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4707 const audio_config_t *config) {
4708 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4709 offloadInfo.format = config->format;
4710 offloadInfo.sample_rate = config->sample_rate;
4711 offloadInfo.channel_mask = config->channel_mask;
4712 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4713 offloadInfo.has_video = false;
4714 offloadInfo.is_streaming = false;
4715 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4716
4717 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4718 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4719 audio_flags_to_audio_output_flags(attr->flags, &flags);
4720 // only retain flags that will drive compressed offload or passthrough
4721 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4722 if (offloadPossible) {
4723 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4724 }
4725 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4726
Dorin Drimusfae3c642022-03-17 18:36:30 +01004727 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004728 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004729 DeviceVector outputDevices = engineOutputDevices;
4730 // the MSD module checks for different conditions and output devices
4731 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4732 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4733 continue;
4734 }
4735 outputDevices = getMsdAudioOutDevices();
4736 }
jiabin2b9d5a12021-12-10 01:06:29 +00004737 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004738 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004739 config->sample_rate, nullptr /*updatedSamplingRate*/,
4740 config->format, nullptr /*updatedFormat*/,
4741 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004742 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004743 continue;
4744 }
4745 // reject profiles not corresponding to a device currently available
4746 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4747 continue;
4748 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004749 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4750 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004751 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004752 != AUDIO_DIRECT_NOT_SUPPORTED) {
4753 // Already reports offload gapless supported. No need to report offload support.
4754 continue;
4755 }
4756 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4757 != AUDIO_OUTPUT_FLAG_NONE) {
4758 // If offload gapless is reported, no need to report offload support.
4759 directMode = (audio_direct_mode_t) ((directMode &
4760 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4761 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4762 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004763 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004764 }
4765 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004766 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004767 }
4768 }
4769 }
4770 return directMode;
4771}
4772
Dorin Drimusf2196d82022-01-03 12:11:18 +01004773status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4774 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004775 if (mEffects.isNonOffloadableEffectEnabled()) {
4776 return OK;
4777 }
jiabinf1c73972022-04-14 16:28:52 -07004778 DeviceVector devices;
4779 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004780 if (status != OK) {
4781 return status;
4782 }
4783 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4784 if (devices.empty()) {
4785 return OK; // no output devices for the attributes
4786 }
jiabinf1c73972022-04-14 16:28:52 -07004787 return getProfilesForDevices(devices, audioProfilesVector,
4788 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004789}
4790
jiabina84c3d32022-12-02 18:59:55 +00004791status_t AudioPolicyManager::getSupportedMixerAttributes(
4792 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4793 ALOGV("%s, portId=%d", __func__, portId);
4794 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4795 if (deviceDescriptor == nullptr) {
4796 ALOGE("%s the requested device is currently unavailable", __func__);
4797 return BAD_VALUE;
4798 }
jiabin96daffc2023-05-11 17:51:55 +00004799 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4800 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4801 deviceDescriptor->type());
4802 return BAD_VALUE;
4803 }
jiabina84c3d32022-12-02 18:59:55 +00004804 for (const auto& hwModule : mHwModules) {
4805 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4806 if (curProfile->supportsDevice(deviceDescriptor)) {
4807 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4808 }
4809 }
4810 }
4811 return NO_ERROR;
4812}
4813
4814status_t AudioPolicyManager::setPreferredMixerAttributes(
4815 const audio_attributes_t *attr,
4816 audio_port_handle_t portId,
4817 uid_t uid,
4818 const audio_mixer_attributes_t *mixerAttributes) {
4819 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4820 "mixerBehavior=%d}, uid=%d, portId=%u",
4821 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4822 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4823 mixerAttributes->mixer_behavior, uid, portId);
4824 if (attr->usage != AUDIO_USAGE_MEDIA) {
4825 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4826 return BAD_VALUE;
4827 }
4828 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4829 if (deviceDescriptor == nullptr) {
4830 ALOGE("%s the requested device is currently unavailable", __func__);
4831 return BAD_VALUE;
4832 }
4833 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4834 ALOGE("%s(%d), type=%d, is not a usb output device",
4835 __func__, portId, deviceDescriptor->type());
4836 return BAD_VALUE;
4837 }
4838
4839 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4840 audio_flags_to_audio_output_flags(attr->flags, &flags);
4841 flags = (audio_output_flags_t) (flags |
4842 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4843 sp<IOProfile> profile = nullptr;
4844 DeviceVector devices(deviceDescriptor);
4845 for (const auto& hwModule : mHwModules) {
4846 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4847 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004848 && curProfile->getCompatibilityScore(
4849 devices,
4850 mixerAttributes->config.sample_rate,
4851 nullptr /*updatedSamplingRate*/,
4852 mixerAttributes->config.format,
4853 nullptr /*updatedFormat*/,
4854 mixerAttributes->config.channel_mask,
4855 nullptr /*updatedChannelMask*/,
4856 flags,
4857 false /*exactMatchRequiredForInputFlags*/)
4858 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004859 profile = curProfile;
4860 break;
4861 }
4862 }
4863 }
4864 if (profile == nullptr) {
4865 ALOGE("%s, there is no compatible profile found", __func__);
4866 return BAD_VALUE;
4867 }
4868
4869 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4870 sp<PreferredMixerAttributesInfo>::make(
4871 uid, portId, profile, flags, *mixerAttributes);
4872 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4873 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4874
4875 // If 1) there is any client from the preferred mixer configuration owner that is currently
4876 // active and matches the strategy and 2) current output is on the preferred device and the
4877 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4878 // configuration.
4879 std::vector<audio_io_handle_t> outputsToReopen;
4880 for (size_t i = 0; i < mOutputs.size(); i++) {
4881 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004882 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4883 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004884 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004885 } else {
4886 for (const auto &client: output->getActiveClients()) {
4887 if (client->uid() == uid && client->strategy() == strategy) {
4888 client->setIsInvalid();
4889 outputsToReopen.push_back(output->mIoHandle);
4890 }
jiabina84c3d32022-12-02 18:59:55 +00004891 }
4892 }
4893 }
4894 }
4895 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4896 config.sample_rate = mixerAttributes->config.sample_rate;
4897 config.channel_mask = mixerAttributes->config.channel_mask;
4898 config.format = mixerAttributes->config.format;
4899 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004900 sp<SwAudioOutputDescriptor> desc =
4901 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4902 if (desc == nullptr) {
4903 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4904 continue;
4905 }
jiabin220eea12024-05-17 17:55:20 +00004906 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004907 }
4908
4909 return NO_ERROR;
4910}
4911
4912sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004913 audio_port_handle_t devicePortId,
4914 product_strategy_t strategy,
4915 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004916 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4917 if (it == mPreferredMixerAttrInfos.end()) {
4918 return nullptr;
4919 }
jiabind9a58d32023-06-01 17:57:30 +00004920 if (activeBitPerfectPreferred) {
4921 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004922 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004923 return info;
4924 }
4925 }
jiabina84c3d32022-12-02 18:59:55 +00004926 }
jiabind9a58d32023-06-01 17:57:30 +00004927 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4928 return strategyMatchedMixerAttrInfoIt == it->second.end()
4929 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004930}
4931
4932status_t AudioPolicyManager::getPreferredMixerAttributes(
4933 const audio_attributes_t *attr,
4934 audio_port_handle_t portId,
4935 audio_mixer_attributes_t* mixerAttributes) {
4936 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4937 portId, mEngine->getProductStrategyForAttributes(*attr));
4938 if (info == nullptr) {
4939 return NAME_NOT_FOUND;
4940 }
4941 *mixerAttributes = info->getMixerAttributes();
4942 return NO_ERROR;
4943}
4944
4945status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4946 audio_port_handle_t portId,
4947 uid_t uid) {
4948 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4949 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4950 if (preferredMixerAttrInfo == nullptr) {
4951 return NAME_NOT_FOUND;
4952 }
4953 if (preferredMixerAttrInfo->getUid() != uid) {
4954 ALOGE("%s, requested uid=%d, owned uid=%d",
4955 __func__, uid, preferredMixerAttrInfo->getUid());
4956 return PERMISSION_DENIED;
4957 }
4958 mPreferredMixerAttrInfos[portId].erase(strategy);
4959 if (mPreferredMixerAttrInfos[portId].empty()) {
4960 mPreferredMixerAttrInfos.erase(portId);
4961 }
4962
4963 // Reconfig existing output
4964 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4965 for (size_t i = 0; i < mOutputs.size(); i++) {
4966 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4967 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4968 }
4969 }
4970 for (const auto output : potentialOutputsToReopen) {
4971 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4972 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4973 preferredMixerAttrInfo->getFlags())) {
4974 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4975 }
4976 }
4977 return NO_ERROR;
4978}
4979
Eric Laurent6a94d692014-05-20 11:18:06 -07004980status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4981 audio_port_type_t type,
4982 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004983 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 unsigned int *generation)
4985{
jiabin19cdba52020-11-24 11:28:58 -08004986 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4987 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 return BAD_VALUE;
4989 }
4990 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004991 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 *num_ports = 0;
4993 }
4994
4995 size_t portsWritten = 0;
4996 size_t portsMax = *num_ports;
4997 *num_ports = 0;
4998 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004999 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5000 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005001 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005002 for (const auto& dev : mAvailableOutputDevices) {
5003 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005004 continue;
5005 }
5006 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005007 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005008 }
5009 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 }
5012 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005013 for (const auto& dev : mAvailableInputDevices) {
5014 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005015 continue;
5016 }
5017 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005018 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005019 }
5020 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005022 }
5023 }
5024 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5025 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5026 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5027 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5028 }
5029 *num_ports += mInputs.size();
5030 }
5031 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005032 size_t numOutputs = 0;
5033 for (size_t i = 0; i < mOutputs.size(); i++) {
5034 if (!mOutputs[i]->isDuplicated()) {
5035 numOutputs++;
5036 if (portsWritten < portsMax) {
5037 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5038 }
5039 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 }
Eric Laurent84c70242014-06-23 08:46:27 -07005041 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 }
5043 }
jiabina84c3d32022-12-02 18:59:55 +00005044
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005046 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005047 return NO_ERROR;
5048}
5049
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005050status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5051 std::vector<media::AudioPortFw>* _aidl_return) {
5052 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5053 audio_port_v7 port;
5054 dev->toAudioPort(&port);
5055 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5056 _aidl_return->push_back(std::move(aidlPort));
5057 return OK;
5058 };
5059
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005060 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005061 for (const auto& dev : module->getDeclaredDevices()) {
5062 if (role == media::AudioPortRole::NONE ||
5063 ((role == media::AudioPortRole::SOURCE)
5064 == audio_is_input_device(dev->type()))) {
5065 RETURN_STATUS_IF_ERROR(pushPort(dev));
5066 }
5067 }
5068 }
5069 return OK;
5070}
5071
jiabin19cdba52020-11-24 11:28:58 -08005072status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005073{
Eric Laurent99fcae42018-05-17 16:59:18 -07005074 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5075 return BAD_VALUE;
5076 }
5077 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5078 if (dev != 0) {
5079 dev->toAudioPort(port);
5080 return NO_ERROR;
5081 }
5082 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5083 if (dev != 0) {
5084 dev->toAudioPort(port);
5085 return NO_ERROR;
5086 }
5087 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5088 if (out != 0) {
5089 out->toAudioPort(port);
5090 return NO_ERROR;
5091 }
5092 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5093 if (in != 0) {
5094 in->toAudioPort(port);
5095 return NO_ERROR;
5096 }
5097 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005098}
5099
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005100status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5101 audio_patch_handle_t *handle,
5102 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005103{
François Gaffieafd4cea2019-11-18 15:50:22 +01005104 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005105 if (handle == NULL || patch == NULL) {
5106 return BAD_VALUE;
5107 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005108 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005109 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005110 return BAD_VALUE;
5111 }
5112 // only one source per audio patch supported for now
5113 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005114 return INVALID_OPERATION;
5115 }
Eric Laurent874c42872014-08-08 15:13:39 -07005116 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005117 return INVALID_OPERATION;
5118 }
Eric Laurent874c42872014-08-08 15:13:39 -07005119 for (size_t i = 0; i < patch->num_sinks; i++) {
5120 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5121 return INVALID_OPERATION;
5122 }
5123 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005124
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005125 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5126 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5127 if (srcDevice == nullptr || sinkDevice == nullptr) {
5128 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5129 return BAD_VALUE;
5130 }
5131 ALOGV("%s between source %s and sink %s", __func__,
5132 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5133 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5134 // Default attributes, default volume priority, not to infer with non raw audio patches.
5135 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5136 const struct audio_port_config *source = &patch->sources[0];
5137 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005138 new SourceClientDescriptor(
5139 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5140 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005141 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005142 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005143
5144 status_t status =
5145 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5146
5147 if (status != NO_ERROR) {
5148 return INVALID_OPERATION;
5149 }
5150 mAudioSources.add(portId, sourceDesc);
5151 return NO_ERROR;
5152}
5153
5154status_t AudioPolicyManager::connectAudioSourceToSink(
5155 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5156 const struct audio_patch *patch,
5157 audio_patch_handle_t &handle,
5158 uid_t uid, uint32_t delayMs)
5159{
5160 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5161 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5162 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5163 return INVALID_OPERATION;
5164 }
5165 sourceDesc->connect(handle, sinkDevice);
5166 if (isMsdPatch(handle)) {
5167 return NO_ERROR;
5168 }
5169 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5170 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5171 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5172 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5173 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5174 goto FailurePatchAdded;
5175 }
5176 status = swOutput->start();
5177 if (status != NO_ERROR) {
5178 goto FailureSourceAdded;
5179 }
5180 swOutput->addClient(sourceDesc);
5181 status = startSource(swOutput, sourceDesc, &delayMs);
5182 if (status != NO_ERROR) {
5183 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5184 goto FailureSourceActive;
5185 }
5186 if (delayMs != 0) {
5187 usleep(delayMs * 1000);
5188 }
5189 return NO_ERROR;
5190
5191FailureSourceActive:
5192 swOutput->stop();
5193 releaseOutput(sourceDesc->portId());
5194FailureSourceAdded:
5195 sourceDesc->setSwOutput(nullptr);
5196FailurePatchAdded:
5197 releaseAudioPatchInternal(handle);
5198 return INVALID_OPERATION;
5199}
5200
5201status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5202 audio_patch_handle_t *handle,
5203 uid_t uid, uint32_t delayMs,
5204 const sp<SourceClientDescriptor>& sourceDesc)
5205{
5206 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 sp<AudioPatch> patchDesc;
5208 ssize_t index = mAudioPatches.indexOfKey(*handle);
5209
François Gaffieafd4cea2019-11-18 15:50:22 +01005210 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5211 patch->sources[0].role,
5212 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005213#if LOG_NDEBUG == 0
5214 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005215 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5216 patch->sinks[i].role,
5217 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005218 }
5219#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005220
5221 if (index >= 0) {
5222 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005223 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5224 __func__, mUidCached, patchDesc->getUid(), uid);
5225 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 return INVALID_OPERATION;
5227 }
5228 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005229 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005230 }
5231
5232 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005233 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005234 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005235 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 return BAD_VALUE;
5237 }
Eric Laurent84c70242014-06-23 08:46:27 -07005238 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5239 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005240 if (patchDesc != 0) {
5241 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005242 ALOGV("%s source id differs for patch current id %d new id %d",
5243 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005244 return BAD_VALUE;
5245 }
5246 }
Eric Laurent874c42872014-08-08 15:13:39 -07005247 DeviceVector devices;
5248 for (size_t i = 0; i < patch->num_sinks; i++) {
5249 // Only support mix to devices connection
5250 // TODO add support for mix to mix connection
5251 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005252 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005253 return INVALID_OPERATION;
5254 }
5255 sp<DeviceDescriptor> devDesc =
5256 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5257 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005258 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005259 return BAD_VALUE;
5260 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005261
jiabin66acc432024-02-06 00:57:36 +00005262 if (outputDesc->mProfile->getCompatibilityScore(
5263 DeviceVector(devDesc),
5264 patch->sources[0].sample_rate,
5265 nullptr, // updatedSamplingRate
5266 patch->sources[0].format,
5267 nullptr, // updatedFormat
5268 patch->sources[0].channel_mask,
5269 nullptr, // updatedChannelMask
5270 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005271 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005272 return INVALID_OPERATION;
5273 }
5274 devices.add(devDesc);
5275 }
5276 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 return INVALID_OPERATION;
5278 }
Eric Laurent874c42872014-08-08 15:13:39 -07005279
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005281 ALOGV("%s setting device %s on output %d",
5282 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305283 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 index = mAudioPatches.indexOfKey(*handle);
5285 if (index >= 0) {
5286 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005287 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 }
5289 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005290 patchDesc->setUid(uid);
5291 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005293 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 return INVALID_OPERATION;
5295 }
5296 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5297 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5298 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005299 // only one sink supported when connecting an input device to a mix
5300 if (patch->num_sinks > 1) {
5301 return INVALID_OPERATION;
5302 }
François Gaffie53615e22015-03-19 09:24:12 +01005303 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005304 if (inputDesc == NULL) {
5305 return BAD_VALUE;
5306 }
5307 if (patchDesc != 0) {
5308 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5309 return BAD_VALUE;
5310 }
5311 }
François Gaffie11d30102018-11-02 16:09:09 +01005312 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005313 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005314 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 return BAD_VALUE;
5316 }
5317
jiabin66acc432024-02-06 00:57:36 +00005318 if (inputDesc->mProfile->getCompatibilityScore(
5319 DeviceVector(device),
5320 patch->sinks[0].sample_rate,
5321 nullptr, /*updatedSampleRate*/
5322 patch->sinks[0].format,
5323 nullptr, /*updatedFormat*/
5324 patch->sinks[0].channel_mask,
5325 nullptr, /*updatedChannelMask*/
5326 // FIXME for the parameter type,
5327 // and the NONE
5328 (audio_output_flags_t)
5329 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005330 return INVALID_OPERATION;
5331 }
5332 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005333 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005334 device->toString().c_str(), inputDesc->mIoHandle);
5335 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005336 index = mAudioPatches.indexOfKey(*handle);
5337 if (index >= 0) {
5338 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005339 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005340 }
5341 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005342 patchDesc->setUid(uid);
5343 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005344 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005345 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 return INVALID_OPERATION;
5347 }
5348 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5349 // device to device connection
5350 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005351 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005352 return BAD_VALUE;
5353 }
5354 }
François Gaffie11d30102018-11-02 16:09:09 +01005355 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005356 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005357 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005358 return BAD_VALUE;
5359 }
Eric Laurent874c42872014-08-08 15:13:39 -07005360
Eric Laurent6a94d692014-05-20 11:18:06 -07005361 //update source and sink with our own data as the data passed in the patch may
5362 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005363 PatchBuilder patchBuilder;
5364 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005365
5366 // if first sink is to MSD, establish single MSD patch
5367 if (getMsdAudioOutDevices().contains(
5368 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5369 ALOGV("%s patching to MSD", __FUNCTION__);
5370 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5371 goto installPatch;
5372 }
5373
François Gaffieafd4cea2019-11-18 15:50:22 +01005374 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5375 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005376
Eric Laurent874c42872014-08-08 15:13:39 -07005377 for (size_t i = 0; i < patch->num_sinks; i++) {
5378 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005379 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005380 return INVALID_OPERATION;
5381 }
François Gaffie11d30102018-11-02 16:09:09 +01005382 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005383 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005384 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005385 return BAD_VALUE;
5386 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005387 audio_port_config sinkPortConfig = {};
5388 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5389 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005390
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005391 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5392 // volume management purpose (tracking activity)
5393 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5394 // in config XML to reach the sink so that is can be declared as available.
5395 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005396 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005397 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005398 // take care of dynamic routing for SwOutput selection,
5399 audio_attributes_t attributes = sourceDesc->attributes();
5400 audio_stream_type_t stream = sourceDesc->stream();
5401 audio_attributes_t resultAttr;
5402 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5403 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005404 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5405 config.channel_mask =
5406 (audio_channel_mask_get_representation(sourceMask)
5407 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5408 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005409 config.format = sourceDesc->config().format;
5410 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5411 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5412 bool isRequestedDeviceForExclusiveUse = false;
5413 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005414 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005415 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005416 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5417 &stream, sourceDesc->uid(), &config, &flags,
5418 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005419 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005420 if (output == AUDIO_IO_HANDLE_NONE) {
5421 ALOGV("%s no output for device %s",
5422 __FUNCTION__, sinkDevice->toString().c_str());
5423 return INVALID_OPERATION;
5424 }
5425 outputDesc = mOutputs.valueFor(output);
5426 if (outputDesc->isDuplicated()) {
5427 ALOGE("%s output is duplicated", __func__);
5428 return INVALID_OPERATION;
5429 }
François Gaffie7e39df22022-04-26 12:48:49 +02005430 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5431 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005432 } else {
5433 // Same for "raw patches" aka created from createAudioPatch API
5434 SortedVector<audio_io_handle_t> outputs =
5435 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5436 // if the sink device is reachable via an opened output stream, request to
5437 // go via this output stream by adding a second source to the patch
5438 // description
5439 output = selectOutput(outputs);
5440 if (output == AUDIO_IO_HANDLE_NONE) {
5441 ALOGE("%s no output available for internal patch sink", __func__);
5442 return INVALID_OPERATION;
5443 }
5444 outputDesc = mOutputs.valueFor(output);
5445 if (outputDesc->isDuplicated()) {
5446 ALOGV("%s output for device %s is duplicated",
5447 __func__, sinkDevice->toString().c_str());
5448 return INVALID_OPERATION;
5449 }
François Gaffie7e39df22022-04-26 12:48:49 +02005450 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005451 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005452 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005453 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005454 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005455 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005456 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5457 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005458 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5459 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005460 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005461 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005462 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005463 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005464 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005465 return INVALID_OPERATION;
5466 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005467 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005468 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005469 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005470 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005471 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005472 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005473 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005474 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5475 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005476 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005477 }
Eric Laurent83b88082014-06-20 18:31:16 -07005478 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005479 }
5480 // TODO: check from routing capabilities in config file and other conflicting patches
5481
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005482installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005483 status_t status = installPatch(
5484 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005485 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005486 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005487 return INVALID_OPERATION;
5488 }
5489 } else {
5490 return BAD_VALUE;
5491 }
5492 } else {
5493 return BAD_VALUE;
5494 }
5495 return NO_ERROR;
5496}
5497
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005498status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005499{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005500 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005501 ssize_t index = mAudioPatches.indexOfKey(handle);
5502
5503 if (index < 0) {
5504 return BAD_VALUE;
5505 }
5506 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005507 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5508 __func__, mUidCached, patchDesc->getUid(), uid);
5509 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 return INVALID_OPERATION;
5511 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005512 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5513 for (size_t i = 0; i < mAudioSources.size(); i++) {
5514 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5515 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5516 portId = sourceDesc->portId();
5517 break;
5518 }
5519 }
5520 return portId != AUDIO_PORT_HANDLE_NONE ?
5521 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005522}
Eric Laurent6a94d692014-05-20 11:18:06 -07005523
François Gaffieafd4cea2019-11-18 15:50:22 +01005524status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005525 uint32_t delayMs,
5526 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005527{
5528 ALOGV("%s patch %d", __func__, handle);
5529 if (mAudioPatches.indexOfKey(handle) < 0) {
5530 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5531 return BAD_VALUE;
5532 }
5533 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005534 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005535 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005536 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005537 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005538 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005539 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005540 return BAD_VALUE;
5541 }
5542
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305543 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005544 getNewOutputDevices(outputDesc, true /*fromCache*/),
5545 true,
5546 0,
5547 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005548 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5549 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005550 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005551 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005552 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005553 return BAD_VALUE;
5554 }
5555 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005556 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005557 true,
5558 NULL);
5559 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005560 status_t status =
5561 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5562 ALOGV("%s patch panel returned %d patchHandle %d",
5563 __func__, status, patchDesc->getAfHandle());
5564 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005565 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005566 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005567 // SW or HW Bridge
5568 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5569 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005570 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005571 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5572 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5573 outputDesc = sourceDesc->swOutput().promote();
5574 }
5575 if (outputDesc == nullptr) {
5576 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5577 // releaseOutput has already called closeOutput in case of direct output
5578 return NO_ERROR;
5579 }
François Gaffie7e39df22022-04-26 12:48:49 +02005580 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005581 // While using a HwBridge, force reconsidering device only if not reusing an existing
5582 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005583 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005584 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5585 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5586 // Reconsider device only for cases:
5587 // 1 / Active Output
5588 // 2 / Inactive Output previously hosting HwBridge
5589 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5590 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5591 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305592 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005593 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5594 outputDesc->devices(),
5595 force,
5596 0,
5597 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005598 } else {
5599 return BAD_VALUE;
5600 }
5601 } else {
5602 return BAD_VALUE;
5603 }
5604 return NO_ERROR;
5605}
5606
5607status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5608 struct audio_patch *patches,
5609 unsigned int *generation)
5610{
François Gaffie53615e22015-03-19 09:24:12 +01005611 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005612 return BAD_VALUE;
5613 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005614 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005615 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005616}
5617
Eric Laurente1715a42014-05-20 11:30:42 -07005618status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005619{
Eric Laurente1715a42014-05-20 11:30:42 -07005620 ALOGV("setAudioPortConfig()");
5621
5622 if (config == NULL) {
5623 return BAD_VALUE;
5624 }
5625 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5626 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005627 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5628 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005629 }
5630
Eric Laurenta121f902014-06-03 13:32:54 -07005631 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005632 if (config->type == AUDIO_PORT_TYPE_MIX) {
5633 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005634 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005635 if (outputDesc == NULL) {
5636 return BAD_VALUE;
5637 }
Eric Laurent84c70242014-06-23 08:46:27 -07005638 ALOG_ASSERT(!outputDesc->isDuplicated(),
5639 "setAudioPortConfig() called on duplicated output %d",
5640 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005641 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005642 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005643 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005644 if (inputDesc == NULL) {
5645 return BAD_VALUE;
5646 }
Eric Laurenta121f902014-06-03 13:32:54 -07005647 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005648 } else {
5649 return BAD_VALUE;
5650 }
5651 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5652 sp<DeviceDescriptor> deviceDesc;
5653 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5654 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5655 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5656 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5657 } else {
5658 return BAD_VALUE;
5659 }
5660 if (deviceDesc == NULL) {
5661 return BAD_VALUE;
5662 }
Eric Laurenta121f902014-06-03 13:32:54 -07005663 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005664 } else {
5665 return BAD_VALUE;
5666 }
5667
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005668 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005669 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5670 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005671 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005672 audioPortConfig->toAudioPortConfig(&newConfig, config);
5673 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005674 }
Eric Laurenta121f902014-06-03 13:32:54 -07005675 if (status != NO_ERROR) {
5676 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005677 }
Eric Laurente1715a42014-05-20 11:30:42 -07005678
5679 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005680}
5681
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005682void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5683{
Eric Laurentd60560a2015-04-10 11:31:20 -07005684 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005685 clearAudioPatches(uid);
5686 clearSessionRoutes(uid);
5687}
5688
Eric Laurent6a94d692014-05-20 11:18:06 -07005689void AudioPolicyManager::clearAudioPatches(uid_t uid)
5690{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005691 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005692 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005693 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005694 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005695 }
5696 }
5697}
5698
François Gaffiec005e562018-11-06 15:04:49 +01005699void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005700{
François Gaffiec005e562018-11-06 15:04:49 +01005701 // Take the first attributes following the product strategy as it is used to retrieve the routed
5702 // device. All attributes wihin a strategy follows the same "routing strategy"
5703 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5704 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005705 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005706 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005707 for (size_t j = 0; j < mOutputs.size(); j++) {
5708 if (mOutputs.keyAt(j) == ouptutToSkip) {
5709 continue;
5710 }
5711 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005712 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005713 continue;
5714 }
5715 // If the default device for this strategy is on another output mix,
5716 // invalidate all tracks in this strategy to force re connection.
5717 // Otherwise select new device on the output mix.
5718 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005719 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005720 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005721 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005722 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005723 // If the device is using preferred mixer attributes, the output need to reopen
5724 // with default configuration when the new selected devices are different from
5725 // current routing devices.
5726 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5727 continue;
5728 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305729 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005730 }
5731 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005732 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005733}
5734
5735void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5736{
5737 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005738 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005739 for (size_t i = 0; i < mOutputs.size(); i++) {
5740 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005741 for (const auto& client : outputDesc->getClientIterable()) {
5742 if (client->hasPreferredDevice() && client->uid() == uid) {
5743 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005744 auto clientStrategy = client->strategy();
5745 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5746 end(affectedStrategies)) {
5747 continue;
5748 }
5749 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005750 }
5751 }
5752 }
5753 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005754 for (const auto& strategy : affectedStrategies) {
5755 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005756 }
5757
5758 // remove input routes associated with this uid
5759 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005760 for (size_t i = 0; i < mInputs.size(); i++) {
5761 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005762 for (const auto& client : inputDesc->getClientIterable()) {
5763 if (client->hasPreferredDevice() && client->uid() == uid) {
5764 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5765 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005766 }
5767 }
5768 }
5769 // reroute inputs if necessary
5770 SortedVector<audio_io_handle_t> inputsToClose;
5771 for (size_t i = 0; i < mInputs.size(); i++) {
5772 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005773 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005774 inputsToClose.add(inputDesc->mIoHandle);
5775 }
5776 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005777 for (const auto& input : inputsToClose) {
5778 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005779 }
5780}
5781
Eric Laurentd60560a2015-04-10 11:31:20 -07005782void AudioPolicyManager::clearAudioSources(uid_t uid)
5783{
5784 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005785 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5786 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005787 stopAudioSource(mAudioSources.keyAt(i));
5788 }
5789 }
5790}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005791
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005792status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5793 audio_io_handle_t *ioHandle,
5794 audio_devices_t *device)
5795{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005796 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5797 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005798 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005799 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5800 if (deviceDesc == nullptr) {
5801 return INVALID_OPERATION;
5802 }
5803 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005804
François Gaffiedf372692015-03-19 10:43:27 +01005805 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005806}
5807
Eric Laurentd60560a2015-04-10 11:31:20 -07005808status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005809 const audio_attributes_t *attributes,
5810 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005811 uid_t uid) {
5812 return startAudioSourceInternal(source, attributes, portId, uid,
David Li48b6a832024-07-01 13:14:10 +00005813 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurent963dbcc2024-06-20 12:34:15 +00005814}
5815
5816status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5817 const audio_attributes_t *attributes,
5818 audio_port_handle_t *portId,
David Li48b6a832024-07-01 13:14:10 +00005819 uid_t uid, bool internal, bool isCallRx,
5820 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005821{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005822 ALOGV("%s", __FUNCTION__);
5823 *portId = AUDIO_PORT_HANDLE_NONE;
5824
5825 if (source == NULL || attributes == NULL || portId == NULL) {
5826 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5827 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005828 return BAD_VALUE;
5829 }
5830
Eric Laurentd60560a2015-04-10 11:31:20 -07005831 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5832 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005833 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5834 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005835 return INVALID_OPERATION;
5836 }
5837
François Gaffie11d30102018-11-02 16:09:09 +01005838 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005839 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005840 String8(source->ext.device.address),
5841 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005842 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005843 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005844 return BAD_VALUE;
5845 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005846
jiabin4ef93452019-09-10 14:29:54 -07005847 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005848
François Gaffieaaac0fd2018-11-22 17:56:39 +01005849 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005850 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005851 mEngine->getStreamTypeForAttributes(*attributes),
5852 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005853 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005854
David Li48b6a832024-07-01 13:14:10 +00005855 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005856 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005857 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005858 }
5859 return status;
5860}
5861
David Li48b6a832024-07-01 13:14:10 +00005862status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5863 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005864{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005865 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005866
5867 // make sure we only have one patch per source.
5868 disconnectAudioSource(sourceDesc);
5869
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005870 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005871 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5872 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5873 sourceDesc->srcDevice()->type(),
5874 String8(sourceDesc->srcDevice()->address().c_str()),
5875 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005876 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005877 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005878 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005879 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005880 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5881 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5882 return INVALID_OPERATION;
5883 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005884 PatchBuilder patchBuilder;
5885 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5886 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005887
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005888 return connectAudioSourceToSink(
David Li48b6a832024-07-01 13:14:10 +00005889 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005890}
5891
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005892status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005893{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005894 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5895 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005896 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005897 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005898 return BAD_VALUE;
5899 }
5900 status_t status = disconnectAudioSource(sourceDesc);
5901
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005902 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005903 return status;
5904}
5905
Andy Hung2ddee192015-12-18 17:34:44 -08005906status_t AudioPolicyManager::setMasterMono(bool mono)
5907{
5908 if (mMasterMono == mono) {
5909 return NO_ERROR;
5910 }
5911 mMasterMono = mono;
5912 // if enabling mono we close all offloaded devices, which will invalidate the
5913 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5914 // for recreating the new AudioTrack as non-offloaded PCM.
5915 //
5916 // If disabling mono, we leave all tracks as is: we don't know which clients
5917 // and tracks are able to be recreated as offloaded. The next "song" should
5918 // play back offloaded.
5919 if (mMasterMono) {
5920 Vector<audio_io_handle_t> offloaded;
5921 for (size_t i = 0; i < mOutputs.size(); ++i) {
5922 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5923 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5924 offloaded.push(desc->mIoHandle);
5925 }
5926 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005927 for (const auto& handle : offloaded) {
5928 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005929 }
5930 }
5931 // update master mono for all remaining outputs
5932 for (size_t i = 0; i < mOutputs.size(); ++i) {
5933 updateMono(mOutputs.keyAt(i));
5934 }
5935 return NO_ERROR;
5936}
5937
5938status_t AudioPolicyManager::getMasterMono(bool *mono)
5939{
5940 *mono = mMasterMono;
5941 return NO_ERROR;
5942}
5943
Eric Laurentac9cef52017-06-09 15:46:26 -07005944float AudioPolicyManager::getStreamVolumeDB(
5945 audio_stream_type_t stream, int index, audio_devices_t device)
5946{
jiabin9a3361e2019-10-01 09:38:30 -07005947 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005948}
5949
jiabin81772902018-04-02 17:52:27 -07005950status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5951 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005952 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005953{
Kriti Dang6537def2021-03-02 13:46:59 +01005954 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5955 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005956 return BAD_VALUE;
5957 }
Kriti Dang6537def2021-03-02 13:46:59 +01005958 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5959 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005960
5961 size_t formatsWritten = 0;
5962 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005963
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005964 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005965 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5966 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005967 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005968 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005969 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005970 bool formatEnabled = true;
5971 switch (forceUse) {
5972 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005973 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005974 break;
5975 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5976 formatEnabled = false;
5977 break;
5978 default: // AUTO or ALWAYS => true
5979 break;
jiabin81772902018-04-02 17:52:27 -07005980 }
5981 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5982 }
jiabin81772902018-04-02 17:52:27 -07005983 }
5984 return NO_ERROR;
5985}
5986
Kriti Dang6537def2021-03-02 13:46:59 +01005987status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5988 audio_format_t *surroundFormats) {
5989 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5990 return BAD_VALUE;
5991 }
5992 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5993 __func__, *numSurroundFormats, surroundFormats);
5994
5995 size_t formatsWritten = 0;
5996 size_t formatsMax = *numSurroundFormats;
5997 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5998
5999 // Return formats from all device profiles that have already been resolved by
6000 // checkOutputsForDevice().
6001 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6002 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6003 audio_devices_t deviceType = device->type();
6004 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6005 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006006 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6007 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006008 continue;
6009 }
6010 // Formats reported by sink devices
6011 std::unordered_set<audio_format_t> formatset;
6012 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6013 formatset.insert(it->second.begin(), it->second.end());
6014 }
6015
6016 // Formats hard-coded in the in policy configuration file (if any).
6017 FormatVector encodedFormats = device->encodedFormats();
6018 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6019 // Filter the formats which are supported by the vendor hardware.
6020 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006021 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006022 formats.insert(*it);
6023 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006024 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006025 if (pair.second.count(*it) != 0) {
6026 formats.insert(pair.first);
6027 break;
6028 }
6029 }
6030 }
6031 }
6032 }
6033 *numSurroundFormats = formats.size();
6034 for (const auto& format: formats) {
6035 if (formatsWritten < formatsMax) {
6036 surroundFormats[formatsWritten++] = format;
6037 }
6038 }
6039 return NO_ERROR;
6040}
6041
jiabin81772902018-04-02 17:52:27 -07006042status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6043{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006044 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006045 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6046 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006047 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006048 return BAD_VALUE;
6049 }
6050
Mikhail Naganov100f0122018-11-29 11:22:16 -08006051 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6052 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006053 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006054 return INVALID_OPERATION;
6055 }
6056
Mikhail Naganov100f0122018-11-29 11:22:16 -08006057 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006058 return NO_ERROR;
6059 }
6060
Mikhail Naganov100f0122018-11-29 11:22:16 -08006061 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006062 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006063 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006064 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006065 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006066 }
6067 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006068 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006069 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006070 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006071 }
6072 }
6073
6074 sp<SwAudioOutputDescriptor> outputDesc;
6075 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006076 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6077 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006078 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6079 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006080 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006081 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006082 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006083 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6084 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006085 name.c_str(),
6086 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006087 if (status != NO_ERROR) {
6088 continue;
6089 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006090 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006091 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6092 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006093 name.c_str(),
6094 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006095 profileUpdated |= (status == NO_ERROR);
6096 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006097 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006098 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006099 AUDIO_DEVICE_IN_HDMI);
6100 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6101 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006102 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006103 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006104 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6105 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6106 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006107 name.c_str(),
6108 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006109 if (status != NO_ERROR) {
6110 continue;
6111 }
6112 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6113 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6114 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006115 name.c_str(),
6116 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006117 profileUpdated |= (status == NO_ERROR);
6118 }
6119
jiabin81772902018-04-02 17:52:27 -07006120 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006121 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006122 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006123 }
6124
6125 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6126}
6127
Eric Laurent5ada82e2019-08-29 17:53:54 -07006128void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006129{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006130 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006131 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006132 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006133 }
6134}
6135
jiabin6012f912018-11-02 17:06:30 -07006136bool AudioPolicyManager::isHapticPlaybackSupported()
6137{
6138 for (const auto& hwModule : mHwModules) {
6139 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6140 for (const auto &outProfile : outputProfiles) {
6141 struct audio_port audioPort;
6142 outProfile->toAudioPort(&audioPort);
6143 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6144 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6145 return true;
6146 }
6147 }
6148 }
6149 }
6150 return false;
6151}
6152
Carter Hsu325a8eb2022-01-19 19:56:51 +08006153bool AudioPolicyManager::isUltrasoundSupported()
6154{
6155 bool hasUltrasoundOutput = false;
6156 bool hasUltrasoundInput = false;
6157 for (const auto& hwModule : mHwModules) {
6158 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6159 if (!hasUltrasoundOutput) {
6160 for (const auto &outProfile : outputProfiles) {
6161 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6162 hasUltrasoundOutput = true;
6163 break;
6164 }
6165 }
6166 }
6167
6168 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6169 if (!hasUltrasoundInput) {
6170 for (const auto &inputProfile : inputProfiles) {
6171 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6172 hasUltrasoundInput = true;
6173 break;
6174 }
6175 }
6176 }
6177
6178 if (hasUltrasoundOutput && hasUltrasoundInput)
6179 return true;
6180 }
6181 return false;
6182}
6183
Atneya Nair698f5ef2022-12-15 16:15:09 -08006184bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6185{
6186 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6187 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6188 for (const auto& hwModule : mHwModules) {
6189 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6190 for (const auto &inputProfile : inputProfiles) {
6191 if ((inputProfile->getFlags() & mask) == mask) {
6192 return true;
6193 }
6194 }
6195 }
6196 return false;
6197}
6198
Eric Laurent8340e672019-11-06 11:01:08 -08006199bool AudioPolicyManager::isCallScreenModeSupported()
6200{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006201 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006202}
6203
6204
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006205status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006206{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006207 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006208 if (!sourceDesc->isConnected()) {
6209 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6210 return NO_ERROR;
6211 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006212 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6213 if (swOutput != 0) {
6214 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006215 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006216 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006217 }
jiabinbce0c1d2020-10-05 11:20:18 -07006218 if (releaseOutput(sourceDesc->portId())) {
6219 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6220 // no need to release audio patch here but just return NO_ERROR.
6221 return NO_ERROR;
6222 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006223 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006224 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006225 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006226 // close Hwoutput and remove from mHwOutputs
6227 } else {
6228 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6229 }
6230 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006231 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006232 sourceDesc->disconnect();
6233 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006234}
6235
François Gaffiec005e562018-11-06 15:04:49 +01006236sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6237 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006238{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006239 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006240 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006241 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006242 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006243 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6244 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006245 source = sourceDesc;
6246 break;
6247 }
6248 }
6249 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006250}
6251
Eric Laurentb4f42a92022-01-17 17:37:31 +01006252bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006253 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006254 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006255{
6256 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6257 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006258 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006259 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006260 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6261 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6262 return false;
6263 }
6264 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6265 return false;
6266 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006267 }
6268
Eric Laurentd332bc82023-08-04 11:45:23 +02006269 // The caller can have the audio config criteria ignored by either passing a null ptr or
6270 // the AUDIO_CONFIG_INITIALIZER value.
6271 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006272 // some positional channel masks and PCM format and for stereo if low latency performance
6273 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006274
6275 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006276 static const bool stereo_spatialization_enabled =
6277 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006278 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006279 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006280 ? audio_channel_mask_contains_stereo(config->channel_mask)
6281 : audio_is_channel_mask_spatialized(config->channel_mask);
6282 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006283 return false;
6284 }
6285 if (!audio_is_linear_pcm(config->format)) {
6286 return false;
6287 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006288 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6289 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6290 return false;
6291 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006292 }
6293
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006294 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006295 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006296 if (profile == nullptr) {
6297 return false;
6298 }
6299
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006300 return true;
6301}
6302
Shunkai Yao57b93392024-04-26 04:12:21 +00006303// The Spatializer output is compatible with Haptic use cases if:
6304// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6305// with client if client haptic channel bits were set, or
6306// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6307// including the haptic bits or creating the HapticGenerator effect for same session.
6308bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6309 const audio_config_t* config, audio_session_t sessionId) const {
6310 const auto clientHapticChannel =
6311 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6312 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6313 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6314
6315 if (threadOutputHapticChannel) {
6316 // check format and sampleRate match if client haptic channel mask exist
6317 if (clientHapticChannel) {
6318 return mSpatializerOutput->getFormat() == config->format &&
6319 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6320 }
6321 return true;
6322 } else {
6323 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6324 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6325 // HapticGenerator effect for this session) are not supported.
6326 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006327 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006328 }
6329}
6330
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006331void AudioPolicyManager::checkVirtualizerClientRoutes() {
6332 std::set<audio_stream_type_t> streamsToInvalidate;
6333 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006334 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6335 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006336 audio_attributes_t attr = client->attributes();
6337 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6338 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6339 audio_config_base_t clientConfig = client->config();
6340 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006341 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006342 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006343 streamsToInvalidate.insert(client->stream());
6344 }
6345 }
6346 }
6347
jiabinc44b3462022-12-08 12:52:31 -08006348 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006349}
6350
Eric Laurente191d1b2022-04-15 11:59:25 +02006351
6352bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6353 const sp<SwAudioOutputDescriptor>& outputDesc) {
6354 if (outputDesc->isDuplicated()) {
6355 return false;
6356 }
6357 DeviceVector devices = outputDesc->supportedDevices();
6358 for (size_t i = 0; i < mOutputs.size(); i++) {
6359 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6360 if (desc == outputDesc || desc->isDuplicated()) {
6361 continue;
6362 }
6363 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6364 if (!sharedDevices.isEmpty()
6365 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6366 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6367 return false;
6368 }
6369 }
6370 return true;
6371}
6372
6373
Eric Laurentfa0f6742021-08-17 18:39:44 +02006374status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006375 const audio_attributes_t *attr,
6376 audio_io_handle_t *output) {
6377 *output = AUDIO_IO_HANDLE_NONE;
6378
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006379 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6380 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6381 audio_config_t *configPtr = nullptr;
6382 audio_config_t config;
6383 if (mixerConfig != nullptr) {
6384 config = audio_config_initializer(mixerConfig);
6385 configPtr = &config;
6386 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006387 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006388 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006389 return BAD_VALUE;
6390 }
6391
6392 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006393 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006394 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006395 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006396 return BAD_VALUE;
6397 }
6398
Eric Laurente191d1b2022-04-15 11:59:25 +02006399 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006400 for (size_t i = 0; i < mOutputs.size(); i++) {
6401 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006402 if (!desc->isDuplicated()
6403 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6404 spatializerOutputs.push_back(desc);
6405 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006406 }
6407 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006408 mSpatializerOutput.clear();
6409 bool outputsChanged = false;
6410 for (const auto& desc : spatializerOutputs) {
6411 if (desc->mProfile == profile
6412 && (configPtr == nullptr
6413 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6414 mSpatializerOutput = desc;
6415 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6416 } else {
6417 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6418 " and devices %s", __func__, desc->mIoHandle,
6419 configPtr != nullptr ? configPtr->channel_mask : 0,
6420 devices.toString().c_str());
6421 closeOutput(desc->mIoHandle);
6422 outputsChanged = true;
6423 }
Eric Laurent39095982021-08-24 18:29:27 +02006424 }
6425
Eric Laurente191d1b2022-04-15 11:59:25 +02006426 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006427 sp<SwAudioOutputDescriptor> desc =
6428 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006429 if (desc != nullptr) {
6430 mSpatializerOutput = desc;
6431 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006432 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006433 }
6434
6435 checkVirtualizerClientRoutes();
6436
Eric Laurente191d1b2022-04-15 11:59:25 +02006437 if (outputsChanged) {
6438 mPreviousOutputs = mOutputs;
6439 mpClientInterface->onAudioPortListUpdate();
6440 }
6441
6442 if (mSpatializerOutput == nullptr) {
6443 ALOGV("%s could not open spatializer output with requested config", __func__);
6444 return BAD_VALUE;
6445 }
Eric Laurent39095982021-08-24 18:29:27 +02006446 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006447 ALOGV("%s returning new spatializer output %d", __func__, *output);
6448 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006449}
6450
Eric Laurentfa0f6742021-08-17 18:39:44 +02006451status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6452 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006453 return INVALID_OPERATION;
6454 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006455 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006456 return BAD_VALUE;
6457 }
Eric Laurent39095982021-08-24 18:29:27 +02006458
Eric Laurente191d1b2022-04-15 11:59:25 +02006459 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6460 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6461 closeOutput(mSpatializerOutput->mIoHandle);
6462 //from now on mSpatializerOutput is null
6463 checkVirtualizerClientRoutes();
6464 }
Eric Laurent39095982021-08-24 18:29:27 +02006465
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006466 return NO_ERROR;
6467}
6468
Eric Laurente552edb2014-03-10 17:42:56 -07006469// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006470// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006471// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006472uint32_t AudioPolicyManager::nextAudioPortGeneration()
6473{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006474 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006475}
6476
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006477AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006478 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006479 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006480 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006481 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006482 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006483 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006484 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006485 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006486 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006487 mAudioPortGeneration(1),
6488 mBeaconMuteRefCount(0),
6489 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006490 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006491 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006492 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006493 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006494{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006495}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006496
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006497status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006498 if (mEngine == nullptr) {
6499 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006500 }
6501 mEngine->setObserver(this);
6502 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006503 if (status != NO_ERROR) {
6504 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6505 return status;
6506 }
François Gaffie2110e042015-03-24 08:41:51 +01006507
jiabin29230182023-04-04 21:02:36 +00006508 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6509 // at the end of this function.
6510 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006511 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6512 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6513
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006514 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006515 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006516 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006517
Eric Laurent3a4311c2014-03-17 12:00:47 -07006518 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006519 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6520 defaultOutputDevice == nullptr ||
6521 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6522 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6523 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006524 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006525 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006526 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006527
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006528 // Silence ALOGV statements
6529 property_set("log.tag." LOG_TAG, "D");
6530
Eric Laurente552edb2014-03-10 17:42:56 -07006531 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006532 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006533}
6534
Eric Laurente0720872014-03-11 09:30:41 -07006535AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006536{
Eric Laurente552edb2014-03-10 17:42:56 -07006537 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006538 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006539 }
6540 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006541 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006542 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006543 mAvailableOutputDevices.clear();
6544 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006545 mOutputs.clear();
6546 mInputs.clear();
6547 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006548 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006549 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006550}
6551
Eric Laurente0720872014-03-11 09:30:41 -07006552status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006553{
Eric Laurent87ffa392015-05-22 10:32:38 -07006554 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006555}
6556
Eric Laurente552edb2014-03-10 17:42:56 -07006557// ---
6558
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006559void AudioPolicyManager::onNewAudioModulesAvailable()
6560{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006561 DeviceVector newDevices;
6562 onNewAudioModulesAvailableInt(&newDevices);
6563 if (!newDevices.empty()) {
6564 nextAudioPortGeneration();
6565 mpClientInterface->onAudioPortListUpdate();
6566 }
6567}
6568
6569void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6570{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006571 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006572 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6573 continue;
6574 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006575 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006576 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6577 handle != AUDIO_MODULE_HANDLE_NONE) {
6578 hwModule->setHandle(handle);
6579 } else {
6580 ALOGW("could not load HW module %s", hwModule->getName());
6581 continue;
6582 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006583 }
6584 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006585 // open all output streams needed to access attached devices.
6586 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006587 // This also validates mAvailableOutputDevices list
6588 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6589 if (!outProfile->canOpenNewIo()) {
6590 ALOGE("Invalid Output profile max open count %u for profile %s",
6591 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6592 continue;
6593 }
6594 if (!outProfile->hasSupportedDevices()) {
6595 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6596 continue;
6597 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006598 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6599 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006600 mTtsOutputAvailable = true;
6601 }
6602
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006603 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006604 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006605 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006606 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6607 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006608 } else {
6609 // choose first device present in profile's SupportedDevices also part of
6610 // mAvailableOutputDevices.
6611 if (availProfileDevices.isEmpty()) {
6612 continue;
6613 }
6614 supportedDevice = availProfileDevices.itemAt(0);
6615 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006616 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006617 continue;
6618 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306619
6620 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6621 && availProfileDevices.areAllDevicesAttached()) {
6622 ALOGV("%s skip opening output for mmap profile %s", __func__,
6623 outProfile->getTagName().c_str());
6624 continue;
6625 }
6626
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006627 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6628 mpClientInterface);
6629 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006630 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006631 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006632 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6633 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006634 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006635 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006636 if (status != NO_ERROR) {
6637 ALOGW("Cannot open output stream for devices %s on hw module %s",
6638 supportedDevice->toString().c_str(), hwModule->getName());
6639 continue;
6640 }
6641 for (const auto &device : availProfileDevices) {
6642 // give a valid ID to an attached device once confirmed it is reachable
6643 if (!device->isAttached()) {
6644 device->attach(hwModule);
6645 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006646 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006647 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006648 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6649 }
6650 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006651 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006652 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6653 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006654 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006655 }
Eric Laurent39095982021-08-24 18:29:27 +02006656 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006657 outputDesc->close();
6658 } else {
6659 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306660 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006661 DeviceVector(supportedDevice),
6662 true,
6663 0,
6664 NULL);
6665 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006666 }
6667 // open input streams needed to access attached devices to validate
6668 // mAvailableInputDevices list
6669 for (const auto& inProfile : hwModule->getInputProfiles()) {
6670 if (!inProfile->canOpenNewIo()) {
6671 ALOGE("Invalid Input profile max open count %u for profile %s",
6672 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6673 continue;
6674 }
6675 if (!inProfile->hasSupportedDevices()) {
6676 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6677 continue;
6678 }
6679 // chose first device present in profile's SupportedDevices also part of
6680 // available input devices
6681 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006682 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006683 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006684 ALOGV("%s: Input device list is empty! for profile %s",
6685 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006686 continue;
6687 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306688
6689 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6690 && availProfileDevices.areAllDevicesAttached()) {
6691 ALOGV("%s skip opening input for mmap profile %s", __func__,
6692 inProfile->getTagName().c_str());
6693 continue;
6694 }
6695
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006696 sp<AudioInputDescriptor> inputDesc =
6697 new AudioInputDescriptor(inProfile, mpClientInterface);
6698
6699 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6700 status_t status = inputDesc->open(nullptr,
6701 availProfileDevices.itemAt(0),
6702 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006703 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006704 &input);
6705 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306706 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6707 __func__, availProfileDevices.toString().c_str(),
6708 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006709 continue;
6710 }
6711 for (const auto &device : availProfileDevices) {
6712 // give a valid ID to an attached device once confirmed it is reachable
6713 if (!device->isAttached()) {
6714 device->attach(hwModule);
6715 device->importAudioPortAndPickAudioProfile(inProfile, true);
6716 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006717 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006718 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6719 }
6720 }
6721 inputDesc->close();
6722 }
6723 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006724
6725 // Check if spatializer outputs can be closed until used.
6726 // mOutputs vector never contains duplicated outputs at this point.
6727 std::vector<audio_io_handle_t> outputsClosed;
6728 for (size_t i = 0; i < mOutputs.size(); i++) {
6729 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6730 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6731 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6732 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006733 nextAudioPortGeneration();
6734 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6735 if (index >= 0) {
6736 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6737 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6738 patchDesc->getAfHandle(), 0);
6739 mAudioPatches.removeItemsAt(index);
6740 mpClientInterface->onAudioPatchListUpdate();
6741 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006742 desc->close();
6743 }
6744 }
6745 for (auto output : outputsClosed) {
6746 removeOutput(output);
6747 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006748}
6749
Eric Laurent98e38192018-02-15 18:31:53 -08006750void AudioPolicyManager::addOutput(audio_io_handle_t output,
6751 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006752{
Eric Laurent1c333e22014-05-20 10:48:17 -07006753 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006754 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006755 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006756 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006757 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006758}
6759
François Gaffie53615e22015-03-19 09:24:12 +01006760void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6761{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006762 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6763 ALOGV("%s: removing primary output", __func__);
6764 mPrimaryOutput = nullptr;
6765 }
François Gaffie53615e22015-03-19 09:24:12 +01006766 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006767 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006768}
6769
Eric Laurent98e38192018-02-15 18:31:53 -08006770void AudioPolicyManager::addInput(audio_io_handle_t input,
6771 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006772{
Eric Laurent1c333e22014-05-20 10:48:17 -07006773 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006774 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006775}
Eric Laurente552edb2014-03-10 17:42:56 -07006776
François Gaffie11d30102018-11-02 16:09:09 +01006777status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006778 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006779 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006780{
François Gaffie11d30102018-11-02 16:09:09 +01006781 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006782 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006783 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006784
François Gaffie11d30102018-11-02 16:09:09 +01006785 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006786 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006787 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006788 }
Eric Laurente552edb2014-03-10 17:42:56 -07006789
Eric Laurent3b73df72014-03-11 09:06:29 -07006790 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006791 // first call getAudioPort to get the supported attributes from the HAL
6792 struct audio_port_v7 port = {};
6793 device->toAudioPort(&port);
6794 status_t status = mpClientInterface->getAudioPort(&port);
6795 if (status == NO_ERROR) {
6796 device->importAudioPort(port);
6797 }
6798
6799 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006800 for (size_t i = 0; i < mOutputs.size(); i++) {
6801 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006802 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006803 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006804 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6805 mOutputs.keyAt(i), device->toString().c_str());
6806 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006807 }
6808 }
6809 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006810 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006811 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006812 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6813 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006814 if (profile->supportsDevice(device)) {
6815 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306816 ALOGV("%s(): adding profile %s from module %s",
6817 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006818 }
6819 }
6820 }
6821
Eric Laurent7b279bb2015-12-14 10:18:23 -08006822 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006823
Eric Laurente552edb2014-03-10 17:42:56 -07006824 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006825 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006826 return BAD_VALUE;
6827 }
6828
6829 // open outputs for matching profiles if needed. Direct outputs are also opened to
6830 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6831 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006832 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006833
6834 // nothing to do if one output is already opened for this profile
6835 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006836 for (j = 0; j < outputs.size(); j++) {
6837 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006838 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006839 // matching profile: save the sample rates, format and channel masks supported
6840 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006841 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006842 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006843 }
Eric Laurente552edb2014-03-10 17:42:56 -07006844 break;
6845 }
6846 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006847 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006848 continue;
6849 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306850 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6851 ALOGV("%s skip opening output for mmap profile %s",
6852 __func__, profile->getTagName().c_str());
6853 continue;
6854 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006855 if (!profile->canOpenNewIo()) {
6856 ALOGW("Max Output number %u already opened for this profile %s",
6857 profile->maxOpenCount, profile->getTagName().c_str());
6858 continue;
6859 }
6860
Eric Laurent83efe1c2017-07-09 16:51:08 -07006861 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006862 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006863 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6864 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006865 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006866 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006867 profiles.removeAt(profile_index);
6868 profile_index--;
6869 } else {
6870 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006871 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006872 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006873 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6874 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006875 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006876 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006877
François Gaffie11d30102018-11-02 16:09:09 +01006878 if (device_distinguishes_on_address(deviceType)) {
6879 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6880 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306881 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6882 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006883 }
Eric Laurente552edb2014-03-10 17:42:56 -07006884 ALOGV("checkOutputsForDevice(): adding output %d", output);
6885 }
6886 }
6887
6888 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006889 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006890 return BAD_VALUE;
6891 }
Eric Laurentd4692962014-05-05 18:13:44 -07006892 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006893 // check if one opened output is not needed any more after disconnecting one device
6894 for (size_t i = 0; i < mOutputs.size(); i++) {
6895 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006896 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006897 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006898 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006899 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006900 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006901 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006902 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6903 mOutputs.keyAt(i));
6904 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006905 }
Eric Laurente552edb2014-03-10 17:42:56 -07006906 }
6907 }
Eric Laurentd4692962014-05-05 18:13:44 -07006908 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006909 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006910 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6911 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006912 if (!profile->supportsDevice(device)) {
6913 continue;
6914 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306915 ALOGV("%s(): clearing direct output profile %s on module %s",
6916 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006917 profile->clearAudioProfiles();
6918 if (!profile->hasDynamicAudioProfile()) {
6919 continue;
6920 }
6921 // When a device is disconnected, if there is an IOProfile that contains dynamic
6922 // profiles and supports the disconnected device, call getAudioPort to repopulate
6923 // the capabilities of the devices that is supported by the IOProfile.
6924 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6925 if (supportedDevice == device ||
6926 !mAvailableOutputDevices.contains(supportedDevice)) {
6927 continue;
6928 }
6929 struct audio_port_v7 port;
6930 supportedDevice->toAudioPort(&port);
6931 status_t status = mpClientInterface->getAudioPort(&port);
6932 if (status == NO_ERROR) {
6933 supportedDevice->importAudioPort(port);
6934 }
Eric Laurente552edb2014-03-10 17:42:56 -07006935 }
6936 }
6937 }
6938 }
6939 return NO_ERROR;
6940}
6941
François Gaffie11d30102018-11-02 16:09:09 +01006942status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006943 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006944{
François Gaffie11d30102018-11-02 16:09:09 +01006945 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006946 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006947 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006948 }
6949
Eric Laurentd4692962014-05-05 18:13:44 -07006950 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006951 sp<AudioInputDescriptor> desc;
6952
jiabinbf5f4262023-04-12 21:48:34 +00006953 // first call getAudioPort to get the supported attributes from the HAL
6954 struct audio_port_v7 port = {};
6955 device->toAudioPort(&port);
6956 status_t status = mpClientInterface->getAudioPort(&port);
6957 if (status == NO_ERROR) {
6958 device->importAudioPort(port);
6959 }
6960
Eric Laurent0dd51852019-04-19 18:18:58 -07006961 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006962 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006963 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006964 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006965 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006966 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006967 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006968
François Gaffie11d30102018-11-02 16:09:09 +01006969 if (profile->supportsDevice(device)) {
6970 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306971 ALOGV("%s : adding profile %s from module %s", __func__,
6972 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006973 }
6974 }
6975 }
6976
Eric Laurent0dd51852019-04-19 18:18:58 -07006977 if (profiles.isEmpty()) {
6978 ALOGW("%s: No input profile available for device %s",
6979 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006980 return BAD_VALUE;
6981 }
6982
6983 // open inputs for matching profiles if needed. Direct inputs are also opened to
6984 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6985 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6986
Eric Laurent1c333e22014-05-20 10:48:17 -07006987 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006988
Eric Laurentd4692962014-05-05 18:13:44 -07006989 // nothing to do if one input is already opened for this profile
6990 size_t input_index;
6991 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6992 desc = mInputs.valueAt(input_index);
6993 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006994 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006995 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006996 }
Eric Laurentd4692962014-05-05 18:13:44 -07006997 break;
6998 }
6999 }
7000 if (input_index != mInputs.size()) {
7001 continue;
7002 }
7003
Jaideep Sharma44824a22024-06-18 16:32:34 +05307004 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7005 ALOGV("%s skip opening input for mmap profile %s",
7006 __func__, profile->getTagName().c_str());
7007 continue;
7008 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007009 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307010 ALOGW("%s Max Input number %u already opened for this profile %s",
7011 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007012 continue;
7013 }
7014
Eric Laurentfe231122017-11-17 17:48:06 -08007015 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007016 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307017 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00007018 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7019 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007020
Eric Laurentcf2c0212014-07-25 16:20:43 -07007021 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007022 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007023 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007024 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007025 mpClientInterface->setParameters(input, String8(param));
7026 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007027 }
jiabin12537fc2023-10-12 17:56:08 +00007028 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007029 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307030 ALOGW("%s direct input missing param for profile %s", __func__,
7031 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007032 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007033 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007034 }
7035
Eric Laurent0dd51852019-04-19 18:18:58 -07007036 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007037 addInput(input, desc);
7038 }
7039 } // endif input != 0
7040
Eric Laurentcf2c0212014-07-25 16:20:43 -07007041 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307042 ALOGW("%s could not open input for device %s on profile %s", __func__,
7043 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007044 profiles.removeAt(profile_index);
7045 profile_index--;
7046 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007047 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007048 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007049 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307050 ALOGV("%s: adding input %d for profile %s", __func__,
7051 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007052
7053 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307054 ALOGV("%s: closing input %d for profile %s", __func__,
7055 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007056 closeInput(input);
7057 }
Eric Laurentd4692962014-05-05 18:13:44 -07007058 }
7059 } // end scan profiles
7060
7061 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007062 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007063 return BAD_VALUE;
7064 }
7065 } else {
7066 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007067 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007068 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007069 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007070 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007071 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007072 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007073 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307074 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7075 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007076 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007077 }
7078 }
7079 }
7080 } // end disconnect
7081
7082 return NO_ERROR;
7083}
7084
7085
Eric Laurente0720872014-03-11 09:30:41 -07007086void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007087{
7088 ALOGV("closeOutput(%d)", output);
7089
François Gaffie1c878552018-11-22 16:53:21 +01007090 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7091 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007092 ALOGW("closeOutput() unknown output %d", output);
7093 return;
7094 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007095 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007096 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007097
Eric Laurente552edb2014-03-10 17:42:56 -07007098 // look for duplicated outputs connected to the output being removed.
7099 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007100 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7101 if (dupOutput->isDuplicated() &&
7102 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7103 sp<SwAudioOutputDescriptor> remainingOutput =
7104 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007105 // As all active tracks on duplicated output will be deleted,
7106 // and as they were also referenced on the other output, the reference
7107 // count for their stream type must be adjusted accordingly on
7108 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007109 const bool wasActive = remainingOutput->isActive();
7110 // Note: no-op on the closing output where all clients has already been set inactive
7111 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007112 // stop() will be a no op if the output is still active but is needed in case all
7113 // active streams refcounts where cleared above
7114 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007115 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007116 }
Eric Laurente552edb2014-03-10 17:42:56 -07007117 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7118 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7119
7120 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007121 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007122 }
7123 }
7124
Eric Laurent05b90f82014-08-27 15:32:29 -07007125 nextAudioPortGeneration();
7126
François Gaffie1c878552018-11-22 16:53:21 +01007127 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007128 if (index >= 0) {
7129 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007130 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7131 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007132 mAudioPatches.removeItemsAt(index);
7133 mpClientInterface->onAudioPatchListUpdate();
7134 }
7135
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007136 if (closingOutputWasActive) {
7137 closingOutput->stop();
7138 }
François Gaffie1c878552018-11-22 16:53:21 +01007139 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007140 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007141 for (const auto device : closingOutput->devices()) {
7142 device->setPreferredConfig(nullptr);
7143 }
7144 }
Eric Laurente552edb2014-03-10 17:42:56 -07007145
François Gaffie53615e22015-03-19 09:24:12 +01007146 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007147 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007148 if (closingOutput == mSpatializerOutput) {
7149 mSpatializerOutput.clear();
7150 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007151
7152 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7153 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007154 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007155 bool directOutputOpen = false;
7156 for (size_t i = 0; i < mOutputs.size(); i++) {
7157 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7158 directOutputOpen = true;
7159 break;
7160 }
7161 }
7162 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007163 ALOGV("no direct outputs open, reset MSD patches");
7164 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7165 // how output devices for patching are resolved. Avoid by caching and reusing the
7166 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7167 // devices to patch to. This may be complicated by the fact that devices may become
7168 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007169 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007170 }
7171 }
jiabin220eea12024-05-17 17:55:20 +00007172
7173 if (closingOutput->mPreferredAttrInfo != nullptr) {
7174 closingOutput->mPreferredAttrInfo->resetActiveClient();
7175 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007176}
7177
7178void AudioPolicyManager::closeInput(audio_io_handle_t input)
7179{
7180 ALOGV("closeInput(%d)", input);
7181
7182 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7183 if (inputDesc == NULL) {
7184 ALOGW("closeInput() unknown input %d", input);
7185 return;
7186 }
7187
Eric Laurent6a94d692014-05-20 11:18:06 -07007188 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007189
François Gaffie11d30102018-11-02 16:09:09 +01007190 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007191 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007192 if (index >= 0) {
7193 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007194 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7195 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007196 mAudioPatches.removeItemsAt(index);
7197 mpClientInterface->onAudioPatchListUpdate();
7198 }
7199
François Gaffie6ebbce02023-07-19 13:27:53 +02007200 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007201 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007202 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007203
François Gaffie11d30102018-11-02 16:09:09 +01007204 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7205 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007206 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007207 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007208 }
Eric Laurente552edb2014-03-10 17:42:56 -07007209}
7210
François Gaffie11d30102018-11-02 16:09:09 +01007211SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7212 const DeviceVector &devices,
7213 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007214{
7215 SortedVector<audio_io_handle_t> outputs;
7216
François Gaffie11d30102018-11-02 16:09:09 +01007217 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007218 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007219 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007220 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007221 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007222 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007223 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007224 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007225 outputs.add(openOutputs.keyAt(i));
7226 }
7227 }
7228 return outputs;
7229}
7230
Mikhail Naganov37977152018-07-11 15:54:44 -07007231void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7232{
7233 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7234 // output is suspended before any tracks are moved to it
7235 checkA2dpSuspend();
7236 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007237 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007238 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007239 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007240 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007241 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7242 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7243 // configuration changes will ultimately be rerouted correctly. We can still avoid
7244 // unnecessary rerouting by caching and reusing the arguments to
7245 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7246 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007247 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007248 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007249 // an event that changed routing likely occurred, inform upper layers
7250 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007251}
7252
François Gaffiec005e562018-11-06 15:04:49 +01007253bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7254 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007255{
François Gaffiec005e562018-11-06 15:04:49 +01007256 return mEngine->getProductStrategyForAttributes(lAttr) ==
7257 mEngine->getProductStrategyForAttributes(rAttr);
7258}
7259
Francois Gaffieff1eb522020-05-06 18:37:04 +02007260void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7261{
7262 for (size_t i = 0; i < mAudioSources.size(); i++) {
7263 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7264 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007265 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007266 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007267 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007268 }
7269 }
7270}
7271
7272void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7273{
7274 for (size_t i = 0; i < mAudioSources.size(); i++) {
7275 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7276 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7277 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7278 disconnectAudioSource(sourceDesc);
7279 }
7280 }
7281}
7282
François Gaffiec005e562018-11-06 15:04:49 +01007283void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7284{
7285 auto psId = mEngine->getProductStrategyForAttributes(attr);
7286
7287 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7288 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007289
François Gaffie11d30102018-11-02 16:09:09 +01007290 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7291 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007292
Eric Laurentc209fe42020-06-05 18:11:23 -07007293 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007294 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007295 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007296 // take into account dynamic audio policies related changes: if a client is now associated
7297 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007298 // invalidate clients on outputs that do not support all the newly selected devices for the
7299 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007300 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007301 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007302 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007303 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007304 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007305
Eric Laurentc209fe42020-06-05 18:11:23 -07007306 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7307 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7308 continue;
7309 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007310 if (!desc->supportsAllDevices(newDevices)) {
7311 invalidatedOutputs.push_back(desc);
7312 break;
7313 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007314 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007315 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007316 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7317 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7318 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007319 if (status == OK) {
7320 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7321 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7322 maxLatency = desc->latency();
7323 }
7324 invalidatedOutputs.push_back(desc);
7325 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007326 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007327 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007328 }
7329 }
7330
Eric Laurent56ed8842022-11-15 16:04:41 +01007331 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007332 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7333 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007334 for (audio_io_handle_t srcOut : srcOutputs) {
7335 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007336 if (desc == nullptr) continue;
7337
7338 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007339 maxLatency = desc->latency();
7340 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007341
Eric Laurent56ed8842022-11-15 16:04:41 +01007342 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007343 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007344 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007345 // a client on a non direct outputs has necessarily a linear PCM format
7346 // so we can call selectOutput() safely
7347 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7348 client->flags(),
7349 client->config().format,
7350 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007351 client->config().sample_rate,
7352 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007353 if (newOutput != srcOut) {
7354 invalidate = true;
7355 break;
7356 }
7357 } else {
7358 sp<IOProfile> profile = getProfileForOutput(newDevices,
7359 client->config().sample_rate,
7360 client->config().format,
7361 client->config().channel_mask,
7362 client->flags(),
7363 true /* directOnly */);
7364 if (profile != desc->mProfile) {
7365 invalidate = true;
7366 break;
7367 }
7368 }
7369 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007370 // mute strategy while moving tracks from one output to another
7371 if (invalidate) {
7372 invalidatedOutputs.push_back(desc);
7373 if (desc->isStrategyActive(psId)) {
7374 setStrategyMute(psId, true, desc);
7375 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7376 newDevices.types());
7377 }
Eric Laurente552edb2014-03-10 17:42:56 -07007378 }
François Gaffiec005e562018-11-06 15:04:49 +01007379 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007380 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007381 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007382 }
Eric Laurente552edb2014-03-10 17:42:56 -07007383 }
7384
Eric Laurent56ed8842022-11-15 16:04:41 +01007385 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7386 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7387 std::to_string(srcOutputs[0]).c_str(),
7388 std::to_string(dstOutputs[0]).c_str());
7389
François Gaffiec005e562018-11-06 15:04:49 +01007390 // Move effects associated to this stream from previous output to new output
7391 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007392 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007393 }
François Gaffiec005e562018-11-06 15:04:49 +01007394 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007395 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007396 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007397 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007398 desc->setTracksInvalidatedStatusByStrategy(psId);
7399 }
Eric Laurente552edb2014-03-10 17:42:56 -07007400 }
7401 }
7402}
7403
Eric Laurente0720872014-03-11 09:30:41 -07007404void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007405{
François Gaffiec005e562018-11-06 15:04:49 +01007406 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7407 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7408 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007409 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007410 }
Eric Laurente552edb2014-03-10 17:42:56 -07007411}
7412
Kevin Rocard153f92d2018-12-18 18:33:28 -08007413void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007414 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007415 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007416 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007417 for (size_t i = 0; i < mOutputs.size(); i++) {
7418 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7419 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007420 sp<AudioPolicyMix> primaryMix;
7421 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007422 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007423 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7424 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7425 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007426 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7427 for (auto &secondaryMix : secondaryMixes) {
7428 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7429 if (outputDesc != nullptr &&
7430 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7431 secondaryDescs.push_back(outputDesc);
7432 }
7433 }
7434
jiabinc44b3462022-12-08 12:52:31 -08007435 if (status != OK &&
7436 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7437 // When it failed to query secondary output, only invalidate the client that is not
7438 // MMAP. The reason is that MMAP stream will not support secondary output.
7439 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007440 } else if (!std::equal(
7441 client->getSecondaryOutputs().begin(),
7442 client->getSecondaryOutputs().end(),
7443 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungced57302024-08-14 11:37:57 -07007444 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7445 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007446 // If the format is not PCM, the tracks should be invalidated to get correct
7447 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007448 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007449 } else {
7450 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7451 std::vector<audio_io_handle_t> secondaryOutputIds;
7452 for (const auto &secondaryDesc: secondaryDescs) {
7453 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7454 weakSecondaryDescs.push_back(secondaryDesc);
7455 }
7456 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7457 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007458 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007459 }
7460 }
7461 }
jiabin10a03f12021-05-07 23:46:28 +00007462 if (!trackSecondaryOutputs.empty()) {
7463 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7464 }
jiabinc44b3462022-12-08 12:52:31 -08007465 if (!clientsToInvalidate.empty()) {
7466 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7467 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007468 }
7469}
7470
Eric Laurent2517af32020-11-25 15:31:27 +01007471bool AudioPolicyManager::isScoRequestedForComm() const {
7472 AudioDeviceTypeAddrVector devices;
7473 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7474 for (const auto &device : devices) {
7475 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7476 return true;
7477 }
7478 }
7479 return false;
7480}
7481
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007482bool AudioPolicyManager::isHearingAidUsedForComm() const {
7483 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7484 true /*fromCache*/);
7485 for (const auto &device : devices) {
7486 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7487 return true;
7488 }
7489 }
7490 return false;
7491}
7492
7493
Eric Laurente0720872014-03-11 09:30:41 -07007494void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007495{
François Gaffie53615e22015-03-19 09:24:12 +01007496 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007497 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007498 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007499 return;
7500 }
7501
Eric Laurent3a4311c2014-03-17 12:00:47 -07007502 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007503 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7504 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007505 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007506
7507 // if suspended, restore A2DP output if:
7508 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007509 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007510 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007511 //
Eric Laurentf732e072016-08-03 19:30:28 -07007512 // if not suspended, suspend A2DP output if:
7513 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007514 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007515 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007516 //
7517 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007518 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007519 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007520 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007521 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007522
7523 mpClientInterface->restoreOutput(a2dpOutput);
7524 mA2dpSuspended = false;
7525 }
7526 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007527 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007528 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007529 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007530 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007531
7532 mpClientInterface->suspendOutput(a2dpOutput);
7533 mA2dpSuspended = true;
7534 }
7535 }
7536}
7537
François Gaffie11d30102018-11-02 16:09:09 +01007538DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7539 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007540{
François Gaffiedb1755b2023-09-01 11:50:35 +02007541 if (outputDesc == nullptr) {
7542 return DeviceVector{};
7543 }
François Gaffie11d30102018-11-02 16:09:09 +01007544
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007545 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007546 if (index >= 0) {
7547 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007548 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007549 ALOGV("%s device %s forced by patch %d", __func__,
7550 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7551 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007552 }
7553 }
7554
Dean Wheatley514b4312020-06-17 21:45:00 +10007555 // Do not retrieve engine device for outputs through MSD
7556 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7557 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7558 return outputDesc->devices();
7559 }
7560
Eric Laurent97ac8712018-07-27 18:59:02 -07007561 // Honor explicit routing requests only if no client using default routing is active on this
7562 // input: a specific app can not force routing for other apps by setting a preferred device.
7563 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007564 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007565 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007566 if (device != nullptr) {
7567 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007568 }
7569
François Gaffiea807ef92018-11-05 10:44:33 +01007570 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7571 // of setForceUse / Default Bus device here
7572 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7573 if (device != nullptr) {
7574 return DeviceVector(device);
7575 }
7576
François Gaffiedb1755b2023-09-01 11:50:35 +02007577 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007578 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7579 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307580 auto hasStreamActive = [&](auto stream) {
7581 return hasStream(streams, stream) && isStreamActive(stream, 0);
7582 };
Eric Laurent484e9272018-06-07 17:29:23 -07007583
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307584 auto doGetOutputDevicesForVoice = [&]() {
7585 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007586 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307587 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007588 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7589 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307590 };
7591
7592 // With low-latency playing on speaker, music on WFD, when the first low-latency
7593 // output is stopped, getNewOutputDevices checks for a product strategy
7594 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007595 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307596 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7597 // stream is associated to the output descriptor.
7598 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7599 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7600 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7601 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007602 // Retrieval of devices for voice DL is done on primary output profile, cannot
7603 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007604 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007605 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7606 break;
7607 }
Eric Laurente552edb2014-03-10 17:42:56 -07007608 }
François Gaffiec005e562018-11-06 15:04:49 +01007609 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007610 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007611}
7612
François Gaffie11d30102018-11-02 16:09:09 +01007613sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7614 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007615{
François Gaffie11d30102018-11-02 16:09:09 +01007616 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007617
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007618 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007619 if (index >= 0) {
7620 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007621 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007622 ALOGV("getNewInputDevice() device %s forced by patch %d",
7623 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7624 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007625 }
7626 }
7627
Eric Laurent97ac8712018-07-27 18:59:02 -07007628 // Honor explicit routing requests only if no client using default routing is active on this
7629 // input: a specific app can not force routing for other apps by setting a preferred device.
7630 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007631 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7632 if (device != nullptr) {
7633 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007634 }
7635
Eric Laurentdc95a252018-04-12 12:46:56 -07007636 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007637 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007638 audio_attributes_t attributes;
7639 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007640 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007641 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7642 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007643 attributes = topClient->attributes();
7644 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007645 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007646 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007647 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7648 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007649 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007650 }
7651
Francois Gaffie716e1432019-01-14 16:58:59 +01007652 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7653 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007654 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007655 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007656 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007657 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007658
Eric Laurente552edb2014-03-10 17:42:56 -07007659 return device;
7660}
7661
Eric Laurent794fde22016-03-11 09:50:45 -08007662bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7663 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007664 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007665}
7666
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007667status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007668 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007669 if (devices == nullptr) {
7670 return BAD_VALUE;
7671 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007672
Andy Hung6d23c0f2022-02-16 09:37:15 -08007673 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007674 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7675 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007676 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007677 for (const auto& device : curDevices) {
7678 devices->push_back(device->getDeviceTypeAddr());
7679 }
7680 return NO_ERROR;
7681}
7682
Eric Laurente0720872014-03-11 09:30:41 -07007683void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007684 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007685 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007686 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007687 updateDevicesAndOutputs();
7688 break;
7689 default:
7690 break;
7691 }
7692}
7693
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007694uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007695
7696 // skip beacon mute management if a dedicated TTS output is available
7697 if (mTtsOutputAvailable) {
7698 return 0;
7699 }
7700
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007701 switch(event) {
7702 case STARTING_OUTPUT:
7703 mBeaconMuteRefCount++;
7704 break;
7705 case STOPPING_OUTPUT:
7706 if (mBeaconMuteRefCount > 0) {
7707 mBeaconMuteRefCount--;
7708 }
7709 break;
7710 case STARTING_BEACON:
7711 mBeaconPlayingRefCount++;
7712 break;
7713 case STOPPING_BEACON:
7714 if (mBeaconPlayingRefCount > 0) {
7715 mBeaconPlayingRefCount--;
7716 }
7717 break;
7718 }
7719
7720 if (mBeaconMuteRefCount > 0) {
7721 // any playback causes beacon to be muted
7722 return setBeaconMute(true);
7723 } else {
7724 // no other playback: unmute when beacon starts playing, mute when it stops
7725 return setBeaconMute(mBeaconPlayingRefCount == 0);
7726 }
7727}
7728
7729uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7730 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7731 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7732 // keep track of muted state to avoid repeating mute/unmute operations
7733 if (mBeaconMuted != mute) {
7734 // mute/unmute AUDIO_STREAM_TTS on all outputs
7735 ALOGV("\t muting %d", mute);
7736 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007737 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7738 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7739 ALOGV("\t no tts volume source available");
7740 return 0;
7741 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007742 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007743 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007744 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007745 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007746 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007747 maxLatency = latency;
7748 }
7749 }
7750 mBeaconMuted = mute;
7751 return maxLatency;
7752 }
7753 return 0;
7754}
7755
Eric Laurente0720872014-03-11 09:30:41 -07007756void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007757{
François Gaffiec005e562018-11-06 15:04:49 +01007758 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007759 mPreviousOutputs = mOutputs;
7760}
7761
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007762uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007763 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007764 uint32_t delayMs)
7765{
7766 // mute/unmute strategies using an incompatible device combination
7767 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7768 // if unmuting, unmute only after the specified delay
7769 if (outputDesc->isDuplicated()) {
7770 return 0;
7771 }
7772
7773 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007774 DeviceVector devices = outputDesc->devices();
7775 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007776
François Gaffiec005e562018-11-06 15:04:49 +01007777 auto productStrategies = mEngine->getOrderedProductStrategies();
7778 for (const auto &productStrategy : productStrategies) {
7779 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7780 DeviceVector curDevices =
7781 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7782 curDevices = curDevices.filter(outputDesc->supportedDevices());
7783 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007784 bool doMute = false;
7785
François Gaffiec005e562018-11-06 15:04:49 +01007786 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007787 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007788 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7789 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007790 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007791 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007792 }
Eric Laurent99401132014-05-07 19:48:15 -07007793 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007794 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007795 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007796 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007797 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007798 continue;
7799 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307800 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007801 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7802 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7803 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007804 if (mute) {
7805 // FIXME: should not need to double latency if volume could be applied
7806 // immediately by the audioflinger mixer. We must account for the delay
7807 // between now and the next time the audioflinger thread for this output
7808 // will process a buffer (which corresponds to one buffer size,
7809 // usually 1/2 or 1/4 of the latency).
7810 if (muteWaitMs < desc->latency() * 2) {
7811 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007812 }
7813 }
7814 }
7815 }
7816 }
7817 }
7818
Eric Laurent99401132014-05-07 19:48:15 -07007819 // temporary mute output if device selection changes to avoid volume bursts due to
7820 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007821 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007822 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007823
Eric Laurentdc462862016-07-19 12:29:53 -07007824 if (muteWaitMs < tempMuteWaitMs) {
7825 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007826 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007827
7828 // If recommended duration is defined, replace temporary mute duration to avoid
7829 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7830 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7831 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7832 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7833 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7834
François Gaffieaaac0fd2018-11-22 17:56:39 +01007835 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7836 // make sure that we do not start the temporary mute period too early in case of
7837 // delayed device change
7838 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7839 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007840 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007841 }
7842 }
7843
Eric Laurente552edb2014-03-10 17:42:56 -07007844 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7845 if (muteWaitMs > delayMs) {
7846 muteWaitMs -= delayMs;
7847 usleep(muteWaitMs * 1000);
7848 return muteWaitMs;
7849 }
7850 return 0;
7851}
7852
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307853uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7854 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007855 const DeviceVector &devices,
7856 bool force,
7857 int delayMs,
7858 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007859 bool requiresMuteCheck, bool requiresVolumeCheck,
7860 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007861{
jiabin3ff8d7d2022-12-13 06:27:44 +00007862 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307863 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7864 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7865 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007866 uint32_t muteWaitMs;
7867
7868 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307869 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007870 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307871 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007872 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007873 return muteWaitMs;
7874 }
Eric Laurente552edb2014-03-10 17:42:56 -07007875
7876 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007877 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007878 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007879 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007880
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307881 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7882 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007883
7884 if (!filteredDevices.isEmpty()) {
7885 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007886 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007887
7888 // if the outputs are not materially active, there is no need to mute.
7889 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007890 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007891 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307892 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7893 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007894 muteWaitMs = 0;
7895 }
Eric Laurente552edb2014-03-10 17:42:56 -07007896
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007897 bool outputRouted = outputDesc->isRouted();
7898
Eric Laurent79ea9582020-06-11 18:49:24 -07007899 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7900 // output profile or if new device is not supported AND previous device(s) is(are) still
7901 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007902 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307903 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7904 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007905 // restore previous device after evaluating strategy mute state
7906 outputDesc->setDevices(prevDevices);
7907 return muteWaitMs;
7908 }
7909
Eric Laurente552edb2014-03-10 17:42:56 -07007910 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007911 // the requested device is AUDIO_DEVICE_NONE
7912 // OR the requested device is the same as current device
7913 // AND force is not specified
7914 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007915 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007916 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307917 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7918 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7919 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007920 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307921 ALOGV("%s %s setting same device on routed output, force apply volumes",
7922 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007923 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7924 }
Eric Laurente552edb2014-03-10 17:42:56 -07007925 return muteWaitMs;
7926 }
7927
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307928 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7929 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007930
Eric Laurente552edb2014-03-10 17:42:56 -07007931 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007932 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007933 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007934 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007935 PatchBuilder patchBuilder;
7936 patchBuilder.addSource(outputDesc);
7937 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7938 for (const auto &filteredDevice : filteredDevices) {
7939 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007940 }
7941
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007942 // Add half reported latency to delayMs when muteWaitMs is null in order
7943 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007944 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7945 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7946 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007947 }
Eric Laurente552edb2014-03-10 17:42:56 -07007948
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007949 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7950 if (!skipMuteDelay) {
7951 // update stream volumes according to new device
7952 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7953 }
Eric Laurente552edb2014-03-10 17:42:56 -07007954
7955 return muteWaitMs;
7956}
7957
Eric Laurentc75307b2015-03-17 15:29:32 -07007958status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007959 int delayMs,
7960 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007961{
Eric Laurent6a94d692014-05-20 11:18:06 -07007962 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007963 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7964 return INVALID_OPERATION;
7965 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007966 if (patchHandle) {
7967 index = mAudioPatches.indexOfKey(*patchHandle);
7968 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007969 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007970 }
7971 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007972 return INVALID_OPERATION;
7973 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007974 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007975 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007976 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007977 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007978 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007979 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007980 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007981 return status;
7982}
7983
7984status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007985 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007986 bool force,
7987 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007988{
7989 status_t status = NO_ERROR;
7990
Eric Laurent1f2f2232014-06-02 12:01:23 -07007991 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007992 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7993 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007994
François Gaffie11d30102018-11-02 16:09:09 +01007995 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007996 PatchBuilder patchBuilder;
7997 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007998 // AUDIO_SOURCE_HOTWORD is for internal use only:
7999 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008000 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8001 auto result = usecase;
8002 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8003 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8004 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008005 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008006 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008007 if (audio_is_remote_submix_device(device->type())) {
8008 // remote submix HAL does not support audio conversion, need source device
8009 // audio config to match the sink input descriptor audio config, otherwise AIDL
8010 // HAL patching will fail
8011 audio_port_config srcDevicePortConfig = {};
8012 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8013 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8014 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8015 srcDevicePortConfig.format = inputDesc->getFormat();
8016 patchBuilder.addSource(srcDevicePortConfig);
8017 } else {
8018 patchBuilder.addSource(device);
8019 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008020 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008021 }
8022 }
8023 return status;
8024}
8025
Eric Laurent6a94d692014-05-20 11:18:06 -07008026status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8027 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008028{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008029 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008030 ssize_t index;
8031 if (patchHandle) {
8032 index = mAudioPatches.indexOfKey(*patchHandle);
8033 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008034 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008035 }
8036 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008037 return INVALID_OPERATION;
8038 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008039 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008040 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008041 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008042 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008043 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008044 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008045 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008046 return status;
8047}
8048
François Gaffie11d30102018-11-02 16:09:09 +01008049sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008050 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008051 audio_format_t& format,
8052 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008053 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008054{
8055 // Choose an input profile based on the requested capture parameters: select the first available
8056 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008057 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008058
Atneya Nair0f0a8032022-12-12 16:20:12 -08008059 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8060 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8061 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8062
8063 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008064
jiabin2fd710d2022-05-02 23:20:22 +00008065 for (;;) {
8066 sp<IOProfile> firstInexact = nullptr;
8067 uint32_t updatedSamplingRate = 0;
8068 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8069 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8070 for (const auto& hwModule : mHwModules) {
8071 for (const auto& profile : hwModule->getInputProfiles()) {
8072 // profile->log();
8073 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008074 if (profile->getCompatibilityScore(
8075 DeviceVector(device),
8076 samplingRate,
8077 &updatedSamplingRate,
8078 format,
8079 &updatedFormat,
8080 channelMask,
8081 &updatedChannelMask,
8082 // FIXME ugly cast
8083 (audio_output_flags_t) flags,
8084 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8085 samplingRate = updatedSamplingRate;
8086 format = updatedFormat;
8087 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008088 return profile;
8089 }
jiabin66acc432024-02-06 00:57:36 +00008090 if (firstInexact == nullptr
8091 && profile->getCompatibilityScore(
8092 DeviceVector(device),
8093 samplingRate,
8094 &updatedSamplingRate,
8095 format,
8096 &updatedFormat,
8097 channelMask,
8098 &updatedChannelMask,
8099 // FIXME ugly cast
8100 (audio_output_flags_t) flags,
8101 false /*exactMatchRequiredForInputFlags*/)
8102 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008103 firstInexact = profile;
8104 }
8105 }
8106 }
8107
8108 if (firstInexact != nullptr) {
8109 samplingRate = updatedSamplingRate;
8110 format = updatedFormat;
8111 channelMask = updatedChannelMask;
8112 return firstInexact;
8113 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8114 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8115 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8116 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8117 flags = AUDIO_INPUT_FLAG_NONE;
8118 } else { // fail
8119 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8120 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8121 samplingRate, format, channelMask, oriFlags);
8122 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008123 }
8124 }
jiabin2fd710d2022-05-02 23:20:22 +00008125
8126 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008127}
8128
Vlad Popa87e0e582024-05-20 18:49:20 -07008129float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8130 VolumeSource volumeSource,
8131 int index,
8132 const DeviceTypeSet &deviceTypes)
8133{
8134 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8135 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8136 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8137
8138 if (com_android_media_audio_abs_volume_index_fix()) {
8139 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8140 mAbsoluteVolumeDrivingStreams.end()) {
8141 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8142 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8143 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8144 ALOGD("%s: no group matching with %s", __FUNCTION__,
8145 toString(attributesToDriveAbs).c_str());
8146 return volumeDb;
8147 }
8148
8149 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8150 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8151 if (vsToDriveAbs == volumeSource) {
8152 // attenuation is applied by the abs volume controller
8153 return volumeDbMax;
8154 } else {
8155 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8156 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8157 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8158 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8159 curvesAbs.getVolumeIndexMax());
8160 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8161 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8162 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8163 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8164 return newVolumeDb;
8165 }
8166 }
8167 return volumeDb;
8168 } else {
8169 return volumeDb;
8170 }
8171}
8172
François Gaffieaaac0fd2018-11-22 17:56:39 +01008173float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8174 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008175 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008176 const DeviceTypeSet& deviceTypes,
8177 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008178{
Vlad Popa87e0e582024-05-20 18:49:20 -07008179 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008180 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8181 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8182
8183 if (!computeInternalInteraction) {
8184 return volumeDb;
8185 }
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008186
8187 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8188 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8189 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8190 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008191 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8192 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8193 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8194 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8195 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008196 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008197 mOutputs.isActive(ringVolumeSrc, 0)) {
8198 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008199 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8200 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008201 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008202 }
8203
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008204 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008205 if ((volumeSource != callVolumeSrc && (isInCall() ||
8206 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008207 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008208 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8209 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008210 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8211 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8212 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008213 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008214 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008215 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008216 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008217 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8218 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008219 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008220 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8221 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8222 // programmatically muted.
8223 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8224 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8225 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008226 bool exemptFromCapping =
8227 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8228 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008229 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8230 volumeSource, volumeDb);
8231 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008232 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8233 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8234 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008235 }
8236 }
Eric Laurente552edb2014-03-10 17:42:56 -07008237 // if a headset is connected, apply the following rules to ring tones and notifications
8238 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008239 // - always attenuate notifications volume by 6dB
8240 // - attenuate ring tones volume by 6dB unless music is not playing and
8241 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008242 // - if music is playing, always limit the volume to current music volume,
8243 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008244 if (!Intersection(deviceTypes,
8245 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8246 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008247 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8248 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008249 ((volumeSource == alarmVolumeSrc ||
8250 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008251 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8252 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8253 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008254 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8255 curves.canBeMuted()) {
8256
Eric Laurente552edb2014-03-10 17:42:56 -07008257 // when the phone is ringing we must consider that music could have been paused just before
8258 // by the music application and behave as if music was active if the last music track was
8259 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008260 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8261 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008262 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008263 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008264 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8265 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008266 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008267 float musicVolDb = computeVolume(musicCurves,
8268 musicVolumeSrc,
8269 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008270 musicDevice,
8271 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008272 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8273 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8274 if (volumeDb > minVolDb) {
8275 volumeDb = minVolDb;
8276 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008277 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008278 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8279 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008280 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8281 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8282 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8283 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008284 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008285 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008286 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8287 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008288 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8289 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008290 }
8291 }
jiabin9a3361e2019-10-01 09:38:30 -07008292 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008293 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008294 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008295 }
8296 }
8297
François Gaffie43c73442018-11-08 08:21:55 +01008298 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008299}
8300
Eric Laurent3839bc02018-07-10 18:33:34 -07008301int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008302 VolumeSource fromVolumeSource,
8303 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008304{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008305 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008306 return srcIndex;
8307 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008308 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8309 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008310 float minSrc = (float)srcCurves.getVolumeIndexMin();
8311 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8312 float minDst = (float)dstCurves.getVolumeIndexMin();
8313 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008314
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008315 // preserve mute request or correct range
8316 if (srcIndex < minSrc) {
8317 if (srcIndex == 0) {
8318 return 0;
8319 }
8320 srcIndex = minSrc;
8321 } else if (srcIndex > maxSrc) {
8322 srcIndex = maxSrc;
8323 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008324 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8325}
8326
François Gaffieaaac0fd2018-11-22 17:56:39 +01008327status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8328 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008329 int index,
8330 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008331 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008332 int delayMs,
8333 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008334{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008335 // APM is single threaded, and single instance.
8336 static std::set<IVolumeCurves*> invalidCurvesReported;
8337
François Gaffieaaac0fd2018-11-22 17:56:39 +01008338 // do not change actual attributes volume if the attributes is muted
8339 if (outputDesc->isMuted(volumeSource)) {
8340 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8341 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008342 return NO_ERROR;
8343 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008344
Eric Laurent5baf07c2024-01-11 16:57:27 +00008345 bool isVoiceVolSrc;
8346 bool isBtScoVolSrc;
8347 if (!isVolumeConsistentForCalls(
8348 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008349 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008350 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008351 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008352 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008353
jiabin9a3361e2019-10-01 09:38:30 -07008354 if (deviceTypes.empty()) {
8355 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008356 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008357 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008358 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008359 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008360
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008361 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008362 if (!invalidCurvesReported.count(&curves)) {
8363 invalidCurvesReported.insert(&curves);
8364 String8 dump;
8365 curves.dump(&dump);
8366 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8367 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008368 return BAD_VALUE;
8369 }
8370
jiabin9a3361e2019-10-01 09:38:30 -07008371 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8372 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008373 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008374 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008375 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8376 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008377 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008378 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008379 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008380 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8381 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008382
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008383 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008384 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8385 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8386 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008387 }
Eric Laurente552edb2014-03-10 17:42:56 -07008388 return NO_ERROR;
8389}
8390
Eric Laurent5baf07c2024-01-11 16:57:27 +00008391void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008392 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008393 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008394 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008395 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008396 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008397 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8398 } else {
8399 voiceVolume = index == 0 ? 0.0 : 1.0;
8400 }
8401 if (voiceVolume != mLastVoiceVolume) {
8402 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8403 mLastVoiceVolume = voiceVolume;
8404 }
8405}
8406
8407bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8408 const DeviceTypeSet& deviceTypes,
8409 bool& isVoiceVolSrc,
8410 bool& isBtScoVolSrc,
8411 const char* caller) {
8412 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8413 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8414 const bool isScoRequested = isScoRequestedForComm();
8415 const bool isHAUsed = isHearingAidUsedForComm();
8416
8417 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8418 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8419
8420 if ((callVolSrc != btScoVolSrc) &&
8421 ((isVoiceVolSrc && isScoRequested) ||
8422 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8423 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8424 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8425 volumeSource, isScoRequested ? " " : " not ");
8426 return false;
8427 }
8428 return true;
8429}
8430
Eric Laurentc75307b2015-03-17 15:29:32 -07008431void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008432 const DeviceTypeSet& deviceTypes,
8433 int delayMs,
8434 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008435{
jiabincd510522020-01-22 09:40:55 -08008436 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008437 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8438 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8439 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008440 curves.getVolumeIndex(deviceTypes),
8441 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008442 }
8443}
8444
François Gaffiec005e562018-11-06 15:04:49 +01008445void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8446 bool on,
8447 const sp<AudioOutputDescriptor>& outputDesc,
8448 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008449 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008450{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008451 std::vector<VolumeSource> sourcesToMute;
8452 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8453 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8454 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008455 VolumeSource source = toVolumeSource(attributes, false);
8456 if ((source != VOLUME_SOURCE_NONE) &&
8457 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8458 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008459 sourcesToMute.push_back(source);
8460 }
Eric Laurente552edb2014-03-10 17:42:56 -07008461 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008462 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008463 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008464 }
8465
Eric Laurente552edb2014-03-10 17:42:56 -07008466}
8467
François Gaffieaaac0fd2018-11-22 17:56:39 +01008468void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8469 bool on,
8470 const sp<AudioOutputDescriptor>& outputDesc,
8471 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008472 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008473{
jiabin9a3361e2019-10-01 09:38:30 -07008474 if (deviceTypes.empty()) {
8475 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008476 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008477 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008478 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008479 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008480 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008481 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008482 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8483 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008484 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008485 }
8486 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008487 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8488 // ignored
8489 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008490 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008491 if (!outputDesc->isMuted(volumeSource)) {
8492 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008493 return;
8494 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008495 if (outputDesc->decMuteCount(volumeSource) == 0) {
8496 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008497 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008498 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008499 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008500 delayMs);
8501 }
8502 }
8503}
8504
François Gaffie53615e22015-03-19 09:24:12 +01008505bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8506{
François Gaffiec005e562018-11-06 15:04:49 +01008507 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008508 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8509 return true;
8510 }
8511
8512 // has known usage?
8513 switch (paa->usage) {
8514 case AUDIO_USAGE_UNKNOWN:
8515 case AUDIO_USAGE_MEDIA:
8516 case AUDIO_USAGE_VOICE_COMMUNICATION:
8517 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8518 case AUDIO_USAGE_ALARM:
8519 case AUDIO_USAGE_NOTIFICATION:
8520 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8521 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8522 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8523 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8524 case AUDIO_USAGE_NOTIFICATION_EVENT:
8525 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8526 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8527 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8528 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008529 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008530 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008531 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008532 case AUDIO_USAGE_EMERGENCY:
8533 case AUDIO_USAGE_SAFETY:
8534 case AUDIO_USAGE_VEHICLE_STATUS:
8535 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008536 break;
8537 default:
8538 return false;
8539 }
8540 return true;
8541}
8542
François Gaffie2110e042015-03-24 08:41:51 +01008543audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8544{
8545 return mEngine->getForceUse(usage);
8546}
8547
Eric Laurent96d1dda2022-03-14 17:14:19 +01008548bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008549 return isStateInCall(mEngine->getPhoneState());
8550}
8551
Eric Laurent96d1dda2022-03-14 17:14:19 +01008552bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008553 return is_state_in_call(state);
8554}
8555
Eric Laurentf9cccec2022-11-16 19:12:00 +01008556bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008557 audio_mode_t mode = mEngine->getPhoneState();
8558 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008559 || (mode == AUDIO_MODE_CALL_SCREEN)
8560 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008561}
8562
Eric Laurentf9cccec2022-11-16 19:12:00 +01008563bool AudioPolicyManager::isInCallOrScreening() const {
8564 audio_mode_t mode = mEngine->getPhoneState();
8565 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8566}
8567
Eric Laurentd60560a2015-04-10 11:31:20 -07008568void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8569{
8570 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008571 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008572 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008573 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008574 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008575 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008576 }
8577 }
8578
8579 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8580 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8581 bool release = false;
8582 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8583 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8584 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8585 source->ext.device.type == deviceDesc->type()) {
8586 release = true;
8587 }
8588 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008589 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008590 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8591 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8592 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008593 sink->ext.device.type == deviceDesc->type() &&
8594 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8595 || strncmp(sink->ext.device.address, address,
8596 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008597 release = true;
8598 }
8599 }
8600 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008601 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8602 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008603 }
8604 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008605
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008606 mInputs.clearSessionRoutesForDevice(deviceDesc);
8607
Francois Gaffie716e1432019-01-14 16:58:59 +01008608 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008609}
8610
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008611void AudioPolicyManager::modifySurroundFormats(
8612 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008613 std::unordered_set<audio_format_t> enforcedSurround(
8614 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008615 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008616 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008617 allSurround.insert(pair.first);
8618 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8619 }
Phil Burk09bc4612016-02-24 15:58:15 -08008620
8621 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8622 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008623 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008624 // This is the resulting set of formats depending on the surround mode:
8625 // 'all surround' = allSurround
8626 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8627 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8628 // 'manual surround' = mManualSurroundFormats
8629 // AUTO: formats v 'enforced surround'
8630 // ALWAYS: formats v 'all surround' v 'enforced surround'
8631 // NEVER: formats ^ 'non-surround'
8632 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008633
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008634 std::unordered_set<audio_format_t> formatSet;
8635 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8636 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008637 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008638 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008639 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008640 formatSet.insert(*formatIter);
8641 }
8642 }
8643 } else {
8644 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8645 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008646 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008647
jiabin81772902018-04-02 17:52:27 -07008648 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008649 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008650 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8651 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8652 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008653 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008654 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8655 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8656 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008657 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008658 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008659 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008660 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008661 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008662 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008663}
8664
jiabin06e4bab2019-07-29 10:13:34 -07008665void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8666 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008667 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8668 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8669
8670 // If NEVER, then remove support for channelMasks > stereo.
8671 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008672 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8673 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008674 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008675 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008676 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008677 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008678 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008679 }
8680 }
jiabin81772902018-04-02 17:52:27 -07008681 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8682 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8683 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008684 bool supports5dot1 = false;
8685 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008686 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008687 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8688 supports5dot1 = true;
8689 break;
8690 }
8691 }
8692 // If not then add 5.1 support.
8693 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008694 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008695 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008696 }
Phil Burk09bc4612016-02-24 15:58:15 -08008697 }
8698}
8699
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008700void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008701 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008702 const sp<IOProfile>& profile) {
8703 if (!profile->hasDynamicAudioProfile()) {
8704 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008705 }
François Gaffie112b0af2015-11-19 16:13:25 +01008706
jiabin12537fc2023-10-12 17:56:08 +00008707 audio_port_v7 devicePort;
8708 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008709
jiabin12537fc2023-10-12 17:56:08 +00008710 audio_port_v7 mixPort;
8711 profile->toAudioPort(&mixPort);
8712 mixPort.ext.mix.handle = ioHandle;
8713
8714 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8715 if (status != NO_ERROR) {
8716 ALOGE("%s failed to query the attributes of the mix port", __func__);
8717 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008718 }
jiabin12537fc2023-10-12 17:56:08 +00008719
8720 std::set<audio_format_t> supportedFormats;
8721 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8722 supportedFormats.insert(mixPort.audio_profiles[i].format);
8723 }
8724 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8725 mReportedFormatsMap[devDesc] = formats;
8726
8727 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008728 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8729 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008730 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8731 modifySurroundFormats(devDesc, &formats);
8732 size_t modifiedNumProfiles = 0;
8733 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8734 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8735 formats.end()) {
8736 // Skip the format that is not present after modifying surround formats.
8737 continue;
8738 }
8739 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8740 sizeof(struct audio_profile));
8741 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8742 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8743 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8744 modifySurroundChannelMasks(&channels);
8745 std::copy(channels.begin(), channels.end(),
8746 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8747 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8748 }
8749 mixPort.num_audio_profiles = modifiedNumProfiles;
8750 }
8751 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008752}
Eric Laurentd60560a2015-04-10 11:31:20 -07008753
Mikhail Naganovdc769682018-05-04 15:34:08 -07008754status_t AudioPolicyManager::installPatch(const char *caller,
8755 audio_patch_handle_t *patchHandle,
8756 AudioIODescriptorInterface *ioDescriptor,
8757 const struct audio_patch *patch,
8758 int delayMs)
8759{
8760 ssize_t index = mAudioPatches.indexOfKey(
8761 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8762 *patchHandle : ioDescriptor->getPatchHandle());
8763 sp<AudioPatch> patchDesc;
8764 status_t status = installPatch(
8765 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8766 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008767 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008768 }
8769 return status;
8770}
8771
8772status_t AudioPolicyManager::installPatch(const char *caller,
8773 ssize_t index,
8774 audio_patch_handle_t *patchHandle,
8775 const struct audio_patch *patch,
8776 int delayMs,
8777 uid_t uid,
8778 sp<AudioPatch> *patchDescPtr)
8779{
8780 sp<AudioPatch> patchDesc;
8781 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8782 if (index >= 0) {
8783 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008784 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008785 }
8786
8787 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8788 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8789 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8790 if (status == NO_ERROR) {
8791 if (index < 0) {
8792 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008793 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008794 } else {
8795 patchDesc->mPatch = *patch;
8796 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008797 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008798 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008799 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008800 }
8801 nextAudioPortGeneration();
8802 mpClientInterface->onAudioPatchListUpdate();
8803 }
8804 if (patchDescPtr) *patchDescPtr = patchDesc;
8805 return status;
8806}
8807
jiabinbce0c1d2020-10-05 11:20:18 -07008808bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8809{
8810 const TrackClientVector activeClients = output->getActiveClients();
8811 if (activeClients.empty()) {
8812 return true;
8813 }
8814 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8815 if (index < 0) {
8816 ALOGE("%s, no audio patch found while there are active clients on output %d",
8817 __func__, output->getId());
8818 return false;
8819 }
8820 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8821 DeviceVector routedDevices;
8822 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8823 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8824 patchDesc->mPatch.sinks[i].id);
8825 if (device == nullptr) {
8826 ALOGE("%s, no audio device found with id(%d)",
8827 __func__, patchDesc->mPatch.sinks[i].id);
8828 return false;
8829 }
8830 routedDevices.add(device);
8831 }
8832 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008833 if (client->isInvalid()) {
8834 // No need to take care about invalidated clients.
8835 continue;
8836 }
jiabinbce0c1d2020-10-05 11:20:18 -07008837 sp<DeviceDescriptor> preferredDevice =
8838 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8839 if (mEngine->getOutputDevicesForAttributes(
8840 client->attributes(), preferredDevice, false) == routedDevices) {
8841 return false;
8842 }
8843 }
8844 return true;
8845}
8846
8847sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008848 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008849 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8850 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008851{
8852 for (const auto& device : devices) {
8853 // TODO: This should be checking if the profile supports the device combo.
8854 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008855 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8856 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008857 return nullptr;
8858 }
8859 }
8860 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8861 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008862 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008863 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11008864 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008865 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008866 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008867 return nullptr;
8868 }
jiabin14b50cc2023-12-13 19:01:52 +00008869 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8870 auto portConfig = desc->getConfig();
8871 for (const auto& device : devices) {
8872 device->setPreferredConfig(&portConfig);
8873 }
8874 }
jiabinbce0c1d2020-10-05 11:20:18 -07008875
8876 // Here is where the out_set_parameters() for card & device gets called
8877 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8878 const audio_devices_t deviceType = device->type();
8879 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008880 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008881 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8882 mpClientInterface->setParameters(output, String8(param));
8883 free(param);
8884 }
jiabin12537fc2023-10-12 17:56:08 +00008885 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008886 if (!profile->hasValidAudioProfile()) {
8887 ALOGW("%s() missing param", __func__);
8888 desc->close();
8889 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008890 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8891 // Reopen the output with the best audio profile picked by APM when the profile supports
8892 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008893 desc->close();
8894 output = AUDIO_IO_HANDLE_NONE;
8895 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8896 profile->pickAudioProfile(
8897 config.sample_rate, config.channel_mask, config.format);
8898 config.offload_info.sample_rate = config.sample_rate;
8899 config.offload_info.channel_mask = config.channel_mask;
8900 config.offload_info.format = config.format;
8901
Dean Wheatleydfb67b82024-01-23 09:36:29 +11008902 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008903 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008904 if (status != NO_ERROR) {
8905 return nullptr;
8906 }
8907 }
8908
8909 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07008910 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
8911 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
8912 hwModule->getHalVersionMajor() >= 3) {
8913 setOutputDevices(__func__, desc, devices, true, 0, NULL);
8914 }
baek.kim -61c20122022-07-27 10:05:32 +00008915 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8916 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8917
jiabinbce0c1d2020-10-05 11:20:18 -07008918 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8919 sp<AudioPolicyMix> policyMix;
8920 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8921 policyMix->setOutput(desc);
8922 desc->mPolicyMix = policyMix;
8923 } else {
8924 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008925 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008926 }
8927
baek.kim -61c20122022-07-27 10:05:32 +00008928 } else if (hasPrimaryOutput() && speaker != nullptr
8929 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008930 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8931 // no duplicated output for:
8932 // - direct outputs
8933 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008934 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008935 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8936
8937 //TODO: configure audio effect output stage here
8938
8939 // open a duplicating output thread for the new output and the primary output
8940 sp<SwAudioOutputDescriptor> dupOutputDesc =
8941 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8942 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8943 if (status == NO_ERROR) {
8944 // add duplicated output descriptor
8945 addOutput(duplicatedOutput, dupOutputDesc);
8946 } else {
8947 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8948 mPrimaryOutput->mIoHandle, output);
8949 desc->close();
8950 removeOutput(output);
8951 nextAudioPortGeneration();
8952 return nullptr;
8953 }
8954 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008955 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8956 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8957 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008958 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008959 }
jiabinbce0c1d2020-10-05 11:20:18 -07008960 return desc;
8961}
8962
jiabinf1c73972022-04-14 16:28:52 -07008963status_t AudioPolicyManager::getDevicesForAttributes(
8964 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8965 // Devices are determined in the following precedence:
8966 //
8967 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8968 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8969 //
8970 // If no such dynamic policy then
8971 // 2) Devices containing an active client using setPreferredDevice
8972 // with same strategy as the attributes.
8973 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8974 //
8975 // If no corresponding active client with setPreferredDevice then
8976 // 3) Devices associated with the strategy determined by the attributes
8977 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8978 //
8979 // See related getOutputForAttrInt().
8980
8981 // check dynamic policies but only for primary descriptors (secondary not used for audible
8982 // audio routing, only used for duplication for playback capture)
8983 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008984 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008985 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008986 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8987 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8988 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008989 if (status != OK) {
8990 return status;
8991 }
8992
8993 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8994 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8995 // as they are unaffected by device/stream volume
8996 // (per SwAudioOutputDescriptor::isFixedVolume()).
8997 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8998 ) {
8999 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9000 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9001 devices.add(deviceDesc);
9002 } else {
9003 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9004 // which selects setPreferredDevice if active. This means forVolume call
9005 // will take an active setPreferredDevice, if such exists.
9006
9007 devices = mEngine->getOutputDevicesForAttributes(
9008 attr, nullptr /* preferredDevice */, false /* fromCache */);
9009 }
9010
9011 if (forVolume) {
9012 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9013 // for single volume control in AudioService (such relationship should exist if
9014 // SPEAKER_SAFE is present).
9015 //
9016 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9017 DeviceVector speakerSafeDevices =
9018 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9019 if (!speakerSafeDevices.isEmpty()) {
9020 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9021 devices.remove(speakerSafeDevices);
9022 }
9023 }
9024
9025 return NO_ERROR;
9026}
9027
9028status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9029 AudioProfileVector& audioProfiles,
9030 uint32_t flags,
9031 bool isInput) {
9032 for (const auto& hwModule : mHwModules) {
9033 // the MSD module checks for different conditions
9034 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9035 continue;
9036 }
9037 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9038 : hwModule->getOutputProfiles();
9039 for (const auto& profile : ioProfiles) {
9040 if (!profile->areAllDevicesSupported(devices) ||
9041 !profile->isCompatibleProfileForFlags(
9042 flags, false /*exactMatchRequiredForInputFlags*/)) {
9043 continue;
9044 }
9045 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9046 }
9047 }
9048
9049 if (!isInput) {
9050 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9051 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9052 if (msdModule != nullptr) {
9053 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9054 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9055 for (const auto &profile: msdModule->getOutputProfiles()) {
9056 if (!profile->asAudioPort()->isDirectOutput()) {
9057 continue;
9058 }
9059 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9060 }
9061 } else {
9062 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9063 }
9064 }
9065 }
9066
9067 return NO_ERROR;
9068}
9069
jiabin3ff8d7d2022-12-13 06:27:44 +00009070sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9071 const audio_config_t *config,
9072 audio_output_flags_t flags,
9073 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009074 closeOutput(outputDesc->mIoHandle);
9075 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9076 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9077 if (preferredOutput == nullptr) {
9078 ALOGE("%s failed to reopen output device=%d, caller=%s",
9079 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009080 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009081 return preferredOutput;
9082}
9083
9084void AudioPolicyManager::reopenOutputsWithDevices(
9085 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9086 for (const auto& [output, devices] : outputsToReopen) {
9087 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9088 closeOutput(output);
9089 openOutputWithProfileAndDevice(desc->mProfile, devices);
9090 }
jiabina84c3d32022-12-02 18:59:55 +00009091}
9092
jiabinc44b3462022-12-08 12:52:31 -08009093PortHandleVector AudioPolicyManager::getClientsForStream(
9094 audio_stream_type_t streamType) const {
9095 PortHandleVector clients;
9096 for (size_t i = 0; i < mOutputs.size(); ++i) {
9097 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9098 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9099 }
9100 return clients;
9101}
9102
9103void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9104 PortHandleVector clients;
9105 for (auto stream : streams) {
9106 PortHandleVector clientsForStream = getClientsForStream(stream);
9107 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9108 }
9109 mpClientInterface->invalidateTracks(clients);
9110}
9111
jiabin220eea12024-05-17 17:55:20 +00009112void AudioPolicyManager::updateClientsInternalMute(
9113 const sp<android::SwAudioOutputDescriptor> &desc) {
9114 if (!desc->isBitPerfect() ||
9115 !com::android::media::audioserver::
9116 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9117 // This is only used for bit perfect output now.
9118 return;
9119 }
9120 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9121 bool bitPerfectClientInternalMute = false;
9122 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9123 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9124 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9125 bitPerfectClient = client;
9126 continue;
9127 }
9128 bool muted = false;
9129 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9130 // System sound is muted.
9131 muted = true;
9132 } else {
9133 bitPerfectClientInternalMute = true;
9134 }
9135 if (client->setInternalMute(muted)) {
9136 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9137 if (!result.ok()) {
9138 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9139 continue;
9140 }
9141 media::TrackInternalMuteInfo info;
9142 info.portId = result.value();
9143 info.muted = client->getInternalMute();
9144 clientsInternalMute.push_back(std::move(info));
9145 }
9146 }
9147 if (bitPerfectClient != nullptr &&
9148 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9149 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9150 if (result.ok()) {
9151 media::TrackInternalMuteInfo info;
9152 info.portId = result.value();
9153 info.muted = bitPerfectClient->getInternalMute();
9154 clientsInternalMute.push_back(std::move(info));
9155 } else {
9156 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9157 __func__, bitPerfectClient->portId());
9158 }
9159 }
9160 if (!clientsInternalMute.empty()) {
9161 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9162 status != NO_ERROR) {
9163 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9164 }
9165 }
9166}
9167
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009168} // namespace android