blob: 74e77e81f976a97bf27b3830fa9a1518ca192904 [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 &&
jiabin6d66b372024-11-25 20:04:29 +00001495 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE &&
1496 outputDesc->mIoHandle != *output) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001497 secondaryOutputs->push_back(outputDesc->mIoHandle);
1498 weakSecondaryOutputDescs.push_back(outputDesc);
1499 }
1500 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001501 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001502
Eric Laurent8fc147b2018-07-22 19:13:55 -07001503 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001504 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001505 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001506 };
jiabin4ef93452019-09-10 14:29:54 -07001507 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001508
Eric Laurentc209fe42020-06-05 18:11:23 -07001509 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001510 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001511 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001512 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001513 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001514 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001515 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001516 std::move(weakSecondaryOutputDescs),
1517 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001518 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001519
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001520 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1521 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001522
Eric Laurente83b55d2014-11-14 10:06:21 -08001523 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001524}
1525
Eric Laurentc529cf62020-04-17 18:19:10 -07001526status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1527 audio_session_t session,
1528 const audio_config_t *config,
1529 audio_output_flags_t flags,
1530 const DeviceVector &devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001531 audio_io_handle_t *output,
1532 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001533
1534 *output = AUDIO_IO_HANDLE_NONE;
1535
1536 // skip direct output selection if the request can obviously be attached to a mixed output
1537 // and not explicitly requested
1538 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1539 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1540 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1541 return NAME_NOT_FOUND;
1542 }
1543
Mikhail Naganov285c1732024-09-05 17:26:50 -07001544 // Reject flag combinations that do not make sense. Note that the requested flags might not
1545 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1546 // combine the requested flags with its own flags, yielding an unsupported combination.
1547 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1548 return NAME_NOT_FOUND;
1549 }
1550
Eric Laurentc529cf62020-04-17 18:19:10 -07001551 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1552 // This prevents creating an offloaded track and tearing it down immediately after start
1553 // when audioflinger detects there is an active non offloadable effect.
1554 // FIXME: We should check the audio session here but we do not have it in this context.
1555 // This may prevent offloading in rare situations where effects are left active by apps
1556 // in the background.
1557 sp<IOProfile> profile;
1558 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1559 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1560 profile = getProfileForOutput(
1561 devices, config->sample_rate, config->format, config->channel_mask,
1562 flags, true /* directOnly */);
1563 }
1564
1565 if (profile == nullptr) {
1566 return NAME_NOT_FOUND;
1567 }
1568
1569 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1570 for (size_t i = 0; i < mOutputs.size(); i++) {
1571 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1572 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1573 // reuse direct output if currently open by the same client
1574 // and configured with same parameters
1575 if ((config->sample_rate == desc->getSamplingRate()) &&
1576 (config->format == desc->getFormat()) &&
1577 (config->channel_mask == desc->getChannelMask()) &&
1578 (session == desc->mDirectClientSession)) {
1579 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301580 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001581 mOutputs.keyAt(i), session);
1582 *output = mOutputs.keyAt(i);
1583 return NO_ERROR;
1584 }
1585 }
1586 }
1587
1588 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001589 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301590 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1591 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001592 return NAME_NOT_FOUND;
1593 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1594 // MMAP gracefully handles lack of an exclusive track resource by mixing
1595 // above the audio framework. For AAudio to know that the limit is reached,
1596 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301597 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1598 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001599 return NAME_NOT_FOUND;
1600 } else {
1601 // Close outputs on this profile, if available, to free resources for this request
1602 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1603 const auto desc = mOutputs.valueAt(i);
1604 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301605 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1606 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001607 closeOutput(desc->mIoHandle);
1608 }
1609 }
1610 }
1611 }
1612
1613 // Unable to close streams to find free resources for this request
1614 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301615 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1616 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001617 return NAME_NOT_FOUND;
1618 }
1619
Atneya Nairb16666a2023-12-11 20:18:33 -08001620 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001621
Michael Chan6fb34492020-12-08 15:44:49 +11001622 // An MSD patch may be using the only output stream that can service this request. Release
1623 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001624 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001625
Eric Laurentf1f22e72021-07-13 14:04:14 +02001626 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001627 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001628 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001629
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001630 // only accept an output with the requested parameters, unless the format can be IEC61937
1631 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1632 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1633 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1634 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001635 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001636 (!ignoreRequestedParametersCheck &&
1637 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1638 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1639 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001640 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1641 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1642 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1643 config->channel_mask, outputDesc->getChannelMask());
1644 if (*output != AUDIO_IO_HANDLE_NONE) {
1645 outputDesc->close();
1646 }
1647 // fall back to mixer output if possible when the direct output could not be open
1648 if (audio_is_linear_pcm(config->format) &&
1649 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1650 return NAME_NOT_FOUND;
1651 }
1652 *output = AUDIO_IO_HANDLE_NONE;
1653 return BAD_VALUE;
1654 }
1655 outputDesc->mDirectOpenCount = 1;
1656 outputDesc->mDirectClientSession = session;
1657
1658 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001659 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1660 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1661 hwModule->getHalVersionMajor() >= 3) {
1662 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1663 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001664 mPreviousOutputs = mOutputs;
1665 ALOGV("%s returns new direct output %d", __func__, *output);
1666 mpClientInterface->onAudioPortListUpdate();
1667 return NO_ERROR;
1668}
1669
François Gaffie11d30102018-11-02 16:09:09 +01001670audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1671 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001672 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001673 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001674 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001675 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001676 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001677 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001678 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001679{
Andy Hungc88b0642018-04-27 15:42:35 -07001680 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001681
jiabine375d412019-02-26 12:54:53 -08001682 // Discard haptic channel mask when forcing muting haptic channels.
1683 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001684 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1685 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001686
Eric Laurente552edb2014-03-10 17:42:56 -07001687 // open a direct output if required by specified parameters
1688 //force direct flag if offload flag is set: offloading implies a direct output stream
1689 // and all common behaviors are driven by checking only the direct flag
1690 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001691 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1692 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001693 }
Nadav Bar766fb022018-01-07 12:18:03 +02001694 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1695 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001696 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001697
1698 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1699
Eric Laurente83b55d2014-11-14 10:06:21 -08001700 // only allow deep buffering for music stream type
1701 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001702 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001703 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov285c1732024-09-05 17:26:50 -07001704 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001705 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001706 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001707 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001708 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001709 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001710 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001711 audio_is_linear_pcm(config->format) &&
1712 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001713 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001714 AUDIO_OUTPUT_FLAG_DIRECT);
1715 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001716 }
Eric Laurente552edb2014-03-10 17:42:56 -07001717
Carter Hsua3abb402021-10-26 11:11:20 +08001718 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1719 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1720 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1721 }
1722
Eric Laurentf9230d52024-01-26 18:49:09 +01001723 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001724 // was specified and offload or direct playback is not explicitly requested, and there is no
1725 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001726 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001727 if (mSpatializerOutput != nullptr &&
1728 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1729 prefMixerConfigInfo == nullptr &&
1730 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1731 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001732 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001733 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001734 }
1735
Eric Laurentc529cf62020-04-17 18:19:10 -07001736 audio_config_t directConfig = *config;
1737 directConfig.channel_mask = channelMask;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001738
1739 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1740 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001741 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001742 return output;
1743 }
1744
Eric Laurent14cbfca2016-03-17 09:42:16 -07001745 // A request for HW A/V sync cannot fallback to a mixed output because time
1746 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001747 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001748 return AUDIO_IO_HANDLE_NONE;
1749 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001750 // A request for Tuner cannot fallback to a mixed output
1751 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1752 return AUDIO_IO_HANDLE_NONE;
1753 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001754
Eric Laurente552edb2014-03-10 17:42:56 -07001755 // ignoring channel mask due to downmix capability in mixer
1756
1757 // open a non direct output
1758
1759 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001760 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001761 // get which output is suitable for the specified stream. The actual
1762 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001763 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001764 if (prefMixerConfigInfo != nullptr) {
1765 for (audio_io_handle_t outputHandle : outputs) {
1766 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1767 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1768 output = outputHandle;
1769 break;
1770 }
1771 }
1772 if (output == AUDIO_IO_HANDLE_NONE) {
1773 // No output open with the preferred profile. Open a new one.
1774 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1775 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1776 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1777 config.format = prefMixerConfigInfo->getConfigBase().format;
1778 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1779 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1780 &config, prefMixerConfigInfo->getFlags());
1781 if (preferredOutput == nullptr) {
1782 ALOGE("%s failed to open output with preferred mixer config", __func__);
1783 } else {
1784 output = preferredOutput->mIoHandle;
1785 }
1786 }
1787 } else {
1788 // at this stage we should ignore the DIRECT flag as no direct output could be
1789 // found earlier
1790 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001791 if (com::android::media::audioserver::
1792 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1793 // If the preferred mixer attributes is null, do not select the bit-perfect output
1794 // unless the bit-perfect output is the only output.
1795 // The bit-perfect output can exist while the passed in preferred mixer attributes
1796 // info is null when it is a high priority client. The high priority clients are
1797 // ringtone or alarm, which is not a bit-perfect use case.
1798 size_t i = 0;
1799 while (i < outputs.size() && outputs.size() > 1) {
1800 auto desc = mOutputs.valueFor(outputs[i]);
1801 // The output descriptor must not be null here.
1802 if (desc->isBitPerfect()) {
1803 outputs.removeItemsAt(i);
1804 } else {
1805 i += 1;
1806 }
1807 }
1808 }
jiabina84c3d32022-12-02 18:59:55 +00001809 output = selectOutput(
1810 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1811 }
Eric Laurente552edb2014-03-10 17:42:56 -07001812 }
François Gaffie11d30102018-11-02 16:09:09 +01001813 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001814 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001815 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001816
Eric Laurente552edb2014-03-10 17:42:56 -07001817 return output;
1818}
1819
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001820sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001821 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1822 mAvailableInputDevices);
1823 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1824}
1825
1826DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1827 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1828 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001829}
1830
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001831const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001833 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1834 if (msdModule != 0) {
1835 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1836 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1837 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1838 const struct audio_port_config *source = &patch->mPatch.sources[j];
1839 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1840 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001841 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001842 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001843 }
1844 }
1845 }
1846 return msdPatches;
1847}
1848
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001849bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1850 ssize_t index = mAudioPatches.indexOfKey(handle);
1851 if (index < 0) {
1852 return false;
1853 }
1854 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1855 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1856 if (msdModule == nullptr) {
1857 return false;
1858 }
1859 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1860 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1861 return true;
1862 }
1863 index = getMsdOutputPatches().indexOfKey(handle);
1864 if (index < 0) {
1865 return false;
1866 }
1867 return true;
1868}
1869
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001870status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1871 const InputProfileCollection &inputProfiles,
1872 const OutputProfileCollection &outputProfiles,
1873 const sp<DeviceDescriptor> &sourceDevice,
1874 const sp<DeviceDescriptor> &sinkDevice,
1875 AudioProfileVector& sourceProfiles,
1876 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001878 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001879 return NO_INIT;
1880 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001883 return NO_INIT;
1884 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1887 inProfile->supportsDevice(sourceDevice)) {
1888 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 }
1890 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001891 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001892 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001893 outProfile->supportsDevice(sinkDevice)) {
1894 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001895 }
1896 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001897 return NO_ERROR;
1898}
1899
1900status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1901 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1902 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1903{
Dean Wheatley16809da2022-12-09 14:55:46 +11001904 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1905 static const std::vector<audio_format_t> formatsOrder = {{
1906 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001907 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1908 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001909 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1910 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1911 // preferred).
1912 std::vector<audio_channel_mask_t> masks = {{
1913 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1914 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1915 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1916 // insert index masks (higher counts most preferred) as preferred over position masks
1917 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1918 masks.insert(
1919 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1920 }
1921 return masks;
1922 }();
1923
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001924 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001925 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1926 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001927 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001928 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1929 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001930 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001931 }
1932 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1933 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1934 sinkConfig->format = bestSinkConfig.format;
1935 // For encoded streams force direct flag to prevent downstream mixing.
1936 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1937 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001938 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1939 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001940 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001941 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1942 // raw and IEC61937 framed streams.
1943 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1944 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1945 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001946 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1947 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001948 sourceConfig->channel_mask =
1949 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1950 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1951 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952 sourceConfig->format = bestSinkConfig.format;
1953 // Copy input stream directly without any processing (e.g. resampling).
1954 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1955 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1956 if (hwAvSync) {
1957 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1958 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1959 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1960 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1961 }
1962 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1963 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1964 sinkConfig->config_mask |= config_mask;
1965 sourceConfig->config_mask |= config_mask;
1966 return NO_ERROR;
1967}
1968
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001969PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1970 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001971{
1972 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001973 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1974 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1975 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1976 if (deviceModule == nullptr) {
1977 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1978 return patchBuilder;
1979 }
1980 const InputProfileCollection inputProfiles = msdIsSource ?
1981 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1982 const OutputProfileCollection outputProfiles = msdIsSource ?
1983 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1984
1985 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1986 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1987 device : getMsdAudioOutDevices().itemAt(0);
1988 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1989
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001990 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1991 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001992 AudioProfileVector sourceProfiles;
1993 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001994 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1995 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001996 for (auto hwAvSync : { true, false }) {
1997 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1998 sourceProfiles, sinkProfiles) != NO_ERROR) {
1999 continue;
2000 }
2001 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2002 &sinkConfig) == NO_ERROR) {
2003 // Found a matching config. Re-create PatchBuilder with this config.
2004 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2005 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002006 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002007 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002008 " supporting PCM format conversion.", __func__);
2009 return patchBuilder;
2010}
2011
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002012status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002013 DeviceVector devices;
2014 if (outputDevices != nullptr && outputDevices->size() > 0) {
2015 devices.add(*outputDevices);
2016 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002017 // Use media strategy for unspecified output device. This should only
2018 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2019 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002020 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002021 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002022 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002023 }
Michael Chan6fb34492020-12-08 15:44:49 +11002024 std::vector<PatchBuilder> patchesToCreate;
2025 for (auto i = 0u; i < devices.size(); ++i) {
2026 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002027 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002028 }
2029 // Retain only the MSD patches associated with outputDevices request.
2030 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002031 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002032 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2033 auto retainedPatch = false;
2034 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2035 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2036 patchesToRemove.removeItemsAt(i);
2037 retainedPatch = true;
2038 break;
2039 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002040 }
Michael Chan6fb34492020-12-08 15:44:49 +11002041 if (retainedPatch) {
2042 it = patchesToCreate.erase(it);
2043 continue;
2044 }
2045 ++it;
2046 }
2047 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2048 return NO_ERROR;
2049 }
2050 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2051 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002052 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002053 }
Michael Chan6fb34492020-12-08 15:44:49 +11002054 status_t status = NO_ERROR;
2055 for (const auto &p : patchesToCreate) {
2056 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2057 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2058 char message[256];
2059 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2060 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2061 currStatus == NO_ERROR ? "Success" : "Error",
2062 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2063 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2064 if (currStatus == NO_ERROR) {
2065 ALOGD("%s", message);
2066 } else {
2067 ALOGE("%s", message);
2068 if (status == NO_ERROR) {
2069 status = currStatus;
2070 }
2071 }
2072 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002073 return status;
2074}
2075
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002076void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2077 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002078 for (size_t i = 0; i < msdPatches.size(); i++) {
2079 const auto& patch = msdPatches[i];
2080 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2081 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2082 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2083 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2084 releaseAudioPatch(patch->getHandle(), mUidCached);
2085 break;
2086 }
2087 }
2088 }
2089}
2090
Dorin Drimus94d94412022-02-02 09:05:02 +01002091bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002092 DeviceVector devicesToCheck =
2093 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002094 AudioPatchCollection msdPatches = getMsdOutputPatches();
2095 for (size_t i = 0; i < msdPatches.size(); i++) {
2096 const auto& patch = msdPatches[i];
2097 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2098 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2099 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2100 const auto& foundDevice = devicesToCheck.getDevice(
2101 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2102 if (foundDevice != nullptr) {
2103 devicesToCheck.remove(foundDevice);
2104 if (devicesToCheck.isEmpty()) {
2105 return true;
2106 }
2107 }
2108 }
2109 }
2110 }
2111 return false;
2112}
2113
Eric Laurente0720872014-03-11 09:30:41 -07002114audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002115 audio_output_flags_t flags,
2116 audio_format_t format,
2117 audio_channel_mask_t channelMask,
2118 uint32_t samplingRate,
2119 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002120{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002121 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2122 "%s called with format %#x", __func__, format);
2123
jiabinebb6af42020-06-09 17:31:17 -07002124 // Return the output that haptic-generating attached to when 1) session id is specified,
2125 // 2) haptic-generating effect exists for given session id and 3) the output that
2126 // haptic-generating effect attached to is in given outputs.
2127 if (sessionId != AUDIO_SESSION_NONE) {
2128 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2129 sessionId, FX_IID_HAPTICGENERATOR);
2130 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2131 return hapticGeneratingOutput;
2132 }
2133 }
2134
Eric Laurent16c66dd2019-05-01 17:54:10 -07002135 // Flags disqualifying an output: the match must happen before calling selectOutput()
2136 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2137 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2138
2139 // Flags expressing a functional request: must be honored in priority over
2140 // other criteria
2141 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2142 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002143 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2144 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002145 // Flags expressing a performance request: have lower priority than serving
2146 // requested sampling rate or channel mask
2147 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2148 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2149 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2150
2151 const audio_output_flags_t functionalFlags =
2152 (audio_output_flags_t)(flags & kFunctionalFlags);
2153 const audio_output_flags_t performanceFlags =
2154 (audio_output_flags_t)(flags & kPerformanceFlags);
2155
2156 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2157
Eric Laurente552edb2014-03-10 17:42:56 -07002158 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002159 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002160 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002161 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002162 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002163 // with tiebreak preferring the minimum number of extra functional flags
2164 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002165 // 3: the output supporting the exact channel mask
2166 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002167 // 5: the output with the highest sampling rate if the requested sample rate is
2168 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002169 // 6: the output with the highest number of requested performance flags
2170 // 7: the output with the bit depth the closest to the requested one
2171 // 8: the primary output
2172 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002173
Eric Laurent16c66dd2019-05-01 17:54:10 -07002174 // matching criteria values in priority order for best matching output so far
2175 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002176
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002177 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002178 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2179 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2180 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002181
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002182 for (audio_io_handle_t output : outputs) {
2183 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002184 // matching criteria values in priority order for current output
2185 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002186
Eric Laurent16c66dd2019-05-01 17:54:10 -07002187 if (outputDesc->isDuplicated()) {
2188 continue;
2189 }
2190 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2191 continue;
2192 }
Eric Laurent8838a382014-09-08 16:44:28 -07002193
Eric Laurent16c66dd2019-05-01 17:54:10 -07002194 // If haptic channel is specified, use the haptic output if present.
2195 // When using haptic output, same audio format and sample rate are required.
2196 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002197 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002198 // skip if haptic channel specified but output does not support it, or output support haptic
2199 // but there is no haptic channel requested AND no orphan haptic effect exist
2200 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2201 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002202 continue;
2203 }
Shunkai Yao808da212024-04-05 22:50:56 +00002204 // In the case of audio-coupled-haptic playback, there is no format conversion and
2205 // resampling in the framework, same format/channel/sampleRate for client and the output
2206 // thread is required. In the case of HapticGenerator effect, do not require format
2207 // matching.
2208 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2209 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002210 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002211 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002212 }
2213
2214 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002215 const int matchingFunctionalFlags =
2216 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2217 const int totalFunctionalFlags =
2218 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2219 // Prefer matching functional flags, but subtract unnecessary functional flags.
2220 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002221
2222 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002223 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2224 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002225 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2226 channelCount <= outputChannelCount) {
2227 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002228 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2229 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002230 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002231 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002232 currentMatchCriteria[3] = outputChannelCount;
2233 }
2234
2235 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002236 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002237 int diff; // avoid unsigned integer overflow.
2238 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2239
2240 // prefer the closest output sampling rate greater than or equal to target
2241 // if none exists, prefer the closest output sampling rate less than target.
2242 //
2243 // criteria is offset to make non-negative.
2244 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002245 }
2246
2247 // performance flags match
2248 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2249
2250 // format match
2251 if (format != AUDIO_FORMAT_INVALID) {
2252 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002253 PolicyAudioPort::kFormatDistanceMax -
2254 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002255 }
2256
2257 // primary output match
2258 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2259
2260 // compare match criteria by priority then value
2261 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2262 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2263 bestMatchCriteria = currentMatchCriteria;
2264 bestOutput = output;
2265
2266 std::stringstream result;
2267 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2268 std::ostream_iterator<int>(result, " "));
2269 ALOGV("%s new bestOutput %d criteria %s",
2270 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002271 }
2272 }
2273
Eric Laurent16c66dd2019-05-01 17:54:10 -07002274 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002275}
2276
Eric Laurent8fc147b2018-07-22 19:13:55 -07002277status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002278{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002279 ALOGV("%s portId %d", __FUNCTION__, portId);
2280
2281 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2282 if (outputDesc == 0) {
2283 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002284 return BAD_VALUE;
2285 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002286 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002287
Eric Laurent8fc147b2018-07-22 19:13:55 -07002288 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002289 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002290
jiabin220eea12024-05-17 17:55:20 +00002291 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2292 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2293 && outputDesc->isBitPerfect()) {
2294 // Usually, APM selects bit-perfect output for high priority use cases only when
2295 // bit-perfect output is the only output that can be routed to the selected device.
2296 // However, here is no need to play high priority use cases such as ringtone and alarm
2297 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2298 // can attach to new output.
2299 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2300 __func__, client->stream());
2301 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2302 return DEAD_OBJECT;
2303 }
2304
Eric Laurent733ce942017-12-07 12:18:25 -08002305 status_t status = outputDesc->start();
2306 if (status != NO_ERROR) {
2307 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002308 }
2309
Eric Laurent97ac8712018-07-27 18:59:02 -07002310 uint32_t delayMs;
2311 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002312
2313 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002314 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002315 if (status == DEAD_OBJECT) {
2316 sp<SwAudioOutputDescriptor> desc =
2317 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2318 if (desc == nullptr) {
2319 // This is not common, it may indicate something wrong with the HAL.
2320 ALOGE("%s unable to open output with default config", __func__);
2321 return status;
2322 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002323 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002324 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002325 }
jiabina84c3d32022-12-02 18:59:55 +00002326
2327 // If the client is the first one active on preferred mixer parameters, reopen the output
2328 // if the current mixer parameters doesn't match the preferred one.
2329 if (outputDesc->devices().size() == 1) {
2330 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2331 outputDesc->devices()[0]->getId(), client->strategy());
2332 if (info != nullptr && info->getUid() == client->uid()) {
2333 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2334 info->getConfigBase(), info->getFlags())) {
2335 stopSource(outputDesc, client);
2336 outputDesc->stop();
2337 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2338 config.channel_mask = info->getConfigBase().channel_mask;
2339 config.sample_rate = info->getConfigBase().sample_rate;
2340 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002341 sp<SwAudioOutputDescriptor> desc =
2342 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2343 if (desc == nullptr) {
2344 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002345 }
jiabin220eea12024-05-17 17:55:20 +00002346 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002347 // Intentionally return error to let the client side resending request for
2348 // creating and starting.
2349 return DEAD_OBJECT;
2350 }
2351 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002352 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002353 // If it is first bit-perfect client, reroute all clients that will be routed to
2354 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2355 PortHandleVector clientsToInvalidate;
2356 for (size_t i = 0; i < mOutputs.size(); i++) {
2357 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002358 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002359 continue;
2360 }
2361 for (const auto& c : mOutputs[i]->getClientIterable()) {
2362 clientsToInvalidate.push_back(c->portId());
2363 }
2364 }
2365 if (!clientsToInvalidate.empty()) {
2366 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2367 __func__);
2368 mpClientInterface->invalidateTracks(clientsToInvalidate);
2369 }
2370 }
jiabina84c3d32022-12-02 18:59:55 +00002371 }
2372 }
2373
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002374 if (client->hasPreferredDevice()) {
2375 // playback activity with preferred device impacts routing occurred, inform upper layers
2376 mpClientInterface->onRoutingUpdated();
2377 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002378 if (delayMs != 0) {
2379 usleep(delayMs * 1000);
2380 }
2381
jiabin220eea12024-05-17 17:55:20 +00002382 if (status == NO_ERROR &&
2383 outputDesc->mPreferredAttrInfo != nullptr &&
2384 outputDesc->isBitPerfect() &&
2385 com::android::media::audioserver::
2386 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2387 // A new client is started on bit-perfect output, update all clients internal mute.
2388 updateClientsInternalMute(outputDesc);
2389 }
2390
Eric Laurentc75307b2015-03-17 15:29:32 -07002391 return status;
2392}
2393
Eric Laurent96d1dda2022-03-14 17:14:19 +01002394bool AudioPolicyManager::isLeUnicastActive() const {
2395 if (isInCall()) {
2396 return true;
2397 }
2398 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2399}
2400
2401bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2402 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2403 return false;
2404 }
2405 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2406 ALOGV("%s active %d", __func__, active);
2407 return active;
2408}
2409
Eric Laurent97ac8712018-07-27 18:59:02 -07002410status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2411 const sp<TrackClientDescriptor>& client,
2412 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002413{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002414 // cannot start playback of STREAM_TTS if any other output is being used
2415 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002416
2417 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002418 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002419 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002420 auto clientStrategy = client->strategy();
2421 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002422 if (stream == AUDIO_STREAM_TTS) {
2423 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002424 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002425 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002426 return INVALID_OPERATION;
2427 } else {
2428 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2429 }
2430 } else {
2431 // some playback other than beacon starts
2432 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2433 }
2434
Eric Laurent77305a62016-07-25 16:39:22 -07002435 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002436 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002437 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002438
François Gaffie11d30102018-11-02 16:09:09 +01002439 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002440 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002441 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002442 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002443 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002444 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002445 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002446 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002447 } else {
2448 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002449 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002450 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2451 AUDIO_FORMAT_DEFAULT);
2452 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2453 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002454 }
2455
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002456 // requiresMuteCheck is false when we can bypass mute strategy.
2457 // It covers a common case when there is no materially active audio
2458 // and muting would result in unnecessary delay and dropped audio.
2459 const uint32_t outputLatencyMs = outputDesc->latency();
2460 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002461 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002462
Eric Laurente552edb2014-03-10 17:42:56 -07002463 // increment usage count for this stream on the requested output:
2464 // NOTE that the usage count is the same for duplicated output and hardware output which is
2465 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002466 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002467
2468 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002469 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002470 // Preferred device may be exclusive, use only if no other active clients on this output
2471 devices = DeviceVector(
2472 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2473 } else {
2474 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2475 }
François Gaffie11d30102018-11-02 16:09:09 +01002476 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002477 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002478 }
2479 }
Eric Laurente552edb2014-03-10 17:42:56 -07002480
François Gaffiec005e562018-11-06 15:04:49 +01002481 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002482 selectOutputForMusicEffects();
2483 }
2484
François Gaffie1c878552018-11-22 16:53:21 +01002485 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002486 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002487 if (devices.isEmpty()) {
2488 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002489 }
François Gaffiec005e562018-11-06 15:04:49 +01002490 bool shouldWait =
2491 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2492 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2493 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002494 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002495 const bool needToCloseBitPerfectOutput =
2496 (com::android::media::audioserver::
2497 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2498 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2499 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002500 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002501 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002502 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002503 // An output has a shared device if
2504 // - managed by the same hw module
2505 // - supports the currently selected device
2506 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002507 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002508
Eric Laurent77305a62016-07-25 16:39:22 -07002509 // force a device change if any other output is:
2510 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002511 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002512 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002513 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002514 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002515 // change the device currently selected by the other output.
2516 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002517 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002518 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002519 force = true;
2520 }
2521 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002522 // a notification so that audio focus effect can propagate, or that a mute/unmute
2523 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002524 const uint32_t latencyMs = desc->latency();
2525 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2526
2527 if (shouldWait && isActive && (waitMs < latencyMs)) {
2528 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002529 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002530
2531 // Require mute check if another output is on a shared device
2532 // and currently active to have proper drain and avoid pops.
2533 // Note restoring AudioTracks onto this output needs to invoke
2534 // a volume ramp if there is no mute.
2535 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002536
2537 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2538 outputsToReopen.push_back(desc);
2539 }
Eric Laurente552edb2014-03-10 17:42:56 -07002540 }
2541 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002542
jiabin220eea12024-05-17 17:55:20 +00002543 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002544 // If the output is open with preferred mixer attributes, but the routed device is
2545 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2546 // changed.
2547 return DEAD_OBJECT;
2548 }
jiabin220eea12024-05-17 17:55:20 +00002549 for (auto& outputToReopen : outputsToReopen) {
2550 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2551 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002552 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302553 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2554 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002555
Eric Laurente552edb2014-03-10 17:42:56 -07002556 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002557 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002558 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002559 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002560 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002561 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002562 outputDesc->useHwGain() /*force*/)) {
2563 // request AudioService to reinitialize the volume curves asynchronously
2564 ALOGE("checkAndSetVolume failed, requesting volume range init");
2565 mpClientInterface->onVolumeRangeInitRequest();
2566 };
Eric Laurente552edb2014-03-10 17:42:56 -07002567
2568 // update the outputs if starting an output with a stream that can affect notification
2569 // routing
2570 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002571
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002572 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002573 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002574 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002575 }
Eric Laurentdc462862016-07-19 12:29:53 -07002576
2577 if (waitMs > muteWaitMs) {
2578 *delayMs = waitMs - muteWaitMs;
2579 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002580
2581 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2582 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2583 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2584 // change occurs after the MixerThread starts and causes a stream volume
2585 // glitch.
2586 //
2587 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002588 }
Eric Laurentdc462862016-07-19 12:29:53 -07002589
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002590 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002591 mEngine->getForceUse(
2592 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002593 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002594 }
2595
Eric Laurent97ac8712018-07-27 18:59:02 -07002596 // Automatically enable the remote submix input when output is started on a re routing mix
2597 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002598 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2599 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002600 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2601 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2602 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002603 "remote-submix",
2604 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002605 }
2606
Eric Laurent96d1dda2022-03-14 17:14:19 +01002607 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2608
Eric Laurente552edb2014-03-10 17:42:56 -07002609 return NO_ERROR;
2610}
2611
Eric Laurent96d1dda2022-03-14 17:14:19 +01002612void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2613 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2614 bool isUnicastActive = isLeUnicastActive();
2615
2616 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002617 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002618 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2619 for (size_t i = 0; i < mOutputs.size(); i++) {
2620 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2621 if (desc != ignoredOutput && desc->isActive()
2622 && ((isUnicastActive &&
2623 !desc->devices().
2624 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2625 || (wasUnicastActive &&
2626 !desc->devices().getDevicesFromTypes(
2627 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2628 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2629 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002630 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002631 // If the device is using preferred mixer attributes, the output need to reopen
2632 // with default configuration when the new selected devices are different from
2633 // current routing devices.
2634 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2635 continue;
2636 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302637 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002638 // re-apply device specific volume if not done by setOutputDevice()
2639 if (!force) {
2640 applyStreamVolumes(desc, newDevices.types(), delayMs);
2641 }
2642 }
2643 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002644 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002645 }
2646}
2647
Eric Laurent8fc147b2018-07-22 19:13:55 -07002648status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002649{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002650 ALOGV("%s portId %d", __FUNCTION__, portId);
2651
2652 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2653 if (outputDesc == 0) {
2654 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002655 return BAD_VALUE;
2656 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002657 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002658
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002659 if (client->hasPreferredDevice(true)) {
2660 // playback activity with preferred device impacts routing occurred, inform upper layers
2661 mpClientInterface->onRoutingUpdated();
2662 }
2663
Eric Laurent97ac8712018-07-27 18:59:02 -07002664 ALOGV("stopOutput() output %d, stream %d, session %d",
2665 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002666
Eric Laurent97ac8712018-07-27 18:59:02 -07002667 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002668
Eric Laurent733ce942017-12-07 12:18:25 -08002669 if (status == NO_ERROR ) {
2670 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002671 } else {
2672 return status;
2673 }
2674
2675 if (outputDesc->devices().size() == 1) {
2676 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2677 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002678 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002679 if (info != nullptr && info->getUid() == client->uid()) {
2680 info->decreaseActiveClient();
2681 if (info->getActiveClientCount() == 0) {
2682 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002683 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002684 }
2685 }
jiabin220eea12024-05-17 17:55:20 +00002686 if (com::android::media::audioserver::
2687 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2688 !outputReopened && outputDesc->isBitPerfect()) {
2689 // Only need to update the clients' internal mute when the output is bit-perfect and it
2690 // is not reopened.
2691 updateClientsInternalMute(outputDesc);
2692 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002693 }
2694 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002695}
2696
Eric Laurent97ac8712018-07-27 18:59:02 -07002697status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2698 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002699{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002700 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002701 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002702 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002703 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002704
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002705 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2706
François Gaffie1c878552018-11-22 16:53:21 +01002707 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2708 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002709 // Automatically disable the remote submix input when output is stopped on a
2710 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002711 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002712 if (isSingleDeviceType(
2713 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002714 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002715 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002716 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2717 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002718 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002719 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002720 }
2721 }
2722 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002723 if (client->hasPreferredDevice(true) &&
2724 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002725 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002726 forceDeviceUpdate = true;
2727 }
2728
Eric Laurente552edb2014-03-10 17:42:56 -07002729 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002730 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002731
Eric Laurente552edb2014-03-10 17:42:56 -07002732 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002733 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002734 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002735 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002736
2737 // If the routing does not change, if an output is routed on a device using HwGain
2738 // (aka setAudioPortConfig) and there are still active clients following different
2739 // volume group(s), force reapply volume
2740 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2741 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2742
Eric Laurente552edb2014-03-10 17:42:56 -07002743 // delay the device switch by twice the latency because stopOutput() is executed when
2744 // the track stop() command is received and at that time the audio track buffer can
2745 // still contain data that needs to be drained. The latency only covers the audio HAL
2746 // and kernel buffers. Also the latency does not always include additional delay in the
2747 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302748 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002749 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002750
2751 // force restoring the device selection on other active outputs if it differs from the
2752 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002753 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002754 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002755 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002756 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002757 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002758 desc->isActive() &&
2759 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002760 (newDevices != desc->devices())) {
2761 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2762 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002763
jiabin220eea12024-05-17 17:55:20 +00002764 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002765 // If the device is using preferred mixer attributes, the output need to
2766 // reopen with default configuration when the new selected devices are
2767 // different from current routing devices.
2768 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2769 continue;
2770 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302771 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002772
Eric Laurent57de36c2016-09-28 16:59:11 -07002773 // re-apply device specific volume if not done by setOutputDevice()
2774 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002775 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002776 }
Eric Laurente552edb2014-03-10 17:42:56 -07002777 }
2778 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002779 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002780 // update the outputs if stopping one with a stream that can affect notification routing
2781 handleNotificationRoutingForStream(stream);
2782 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002783
2784 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2785 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002786 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002787 }
2788
François Gaffiec005e562018-11-06 15:04:49 +01002789 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002790 selectOutputForMusicEffects();
2791 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002792
2793 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2794
Eric Laurente552edb2014-03-10 17:42:56 -07002795 return NO_ERROR;
2796 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002797 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002798 return INVALID_OPERATION;
2799 }
2800}
2801
jiabinbce0c1d2020-10-05 11:20:18 -07002802bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002803{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002804 ALOGV("%s portId %d", __FUNCTION__, portId);
2805
2806 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2807 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002808 // If an output descriptor is closed due to a device routing change,
2809 // then there are race conditions with releaseOutput from tracks
2810 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2811 // destroyed shortly thereafter.
2812 //
2813 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002814 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002815 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002816 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002817
2818 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002819
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302820 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2821 if (outputDesc->isClientActive(client)) {
2822 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2823 stopOutput(portId);
2824 }
2825
Eric Laurent8fc147b2018-07-22 19:13:55 -07002826 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2827 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002828 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002829 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002830 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002831 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002832 if (--outputDesc->mDirectOpenCount == 0) {
2833 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002834 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002835 }
2836 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302837
Andy Hung39efb7a2018-09-26 15:39:28 -07002838 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002839 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2840 // The output is pending reopened to query dynamic profiles and
2841 // there is no active clients
2842 closeOutput(outputDesc->mIoHandle);
2843 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2844 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2845 if (newOutputDesc == nullptr) {
2846 ALOGE("%s failed to open output", __func__);
2847 }
2848 return true;
2849 }
2850 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002851}
2852
Eric Laurentcaf7f482014-11-25 17:50:47 -08002853status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2854 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002855 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002856 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002857 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002858 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002859 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002860 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002861 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002862 audio_port_handle_t *portId,
2863 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002864{
François Gaffiec005e562018-11-06 15:04:49 +01002865 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002866 "flags %#x attributes=%s requested device ID %d",
2867 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2868 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002869
Eric Laurentad2e7b92017-09-14 20:06:42 -07002870 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002871 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002872 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002873 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002874 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002875 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002876 sp<RecordClientDescriptor> clientDesc;
2877 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002878 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002879 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002880
2881 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2882 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2883 return INVALID_OPERATION;
2884 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002885
Francois Gaffie716e1432019-01-14 16:58:59 +01002886 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2887 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002888 }
2889
Paul McLean466dc8e2015-04-17 13:15:36 -06002890 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002891 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002892 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002893
Eric Laurentad2e7b92017-09-14 20:06:42 -07002894 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2895 // possible
2896 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2897 *input != AUDIO_IO_HANDLE_NONE) {
2898 ssize_t index = mInputs.indexOfKey(*input);
2899 if (index < 0) {
2900 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2901 status = BAD_VALUE;
2902 goto error;
2903 }
2904 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002905 RecordClientVector clients = inputDesc->getClientsForSession(session);
2906 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002907 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2908 status = BAD_VALUE;
2909 goto error;
2910 }
2911 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2912 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002913 // corresponds to a new client and is only permitted from the same UID.
2914 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002915 if (clients.size() > 1) {
2916 for (const auto& client : clients) {
2917 // The client map is ordered by key values (portId) and portIds are allocated
2918 // incrementaly. So the first client in this list is the one opened by audio flinger
2919 // when the mmap stream is created and should be ignored as it does not correspond
2920 // to an actual client
2921 if (client == *clients.cbegin()) {
2922 continue;
2923 }
2924 if (uid != client->uid() && !client->isSilenced()) {
2925 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2926 uid, client->portId(), client->uid());
2927 status = INVALID_OPERATION;
2928 goto error;
2929 }
Eric Laurent331679c2018-04-16 17:03:16 -07002930 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002931 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002932 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002933 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002934
Eric Laurentfecbceb2021-02-09 14:46:43 +01002935 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002936 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002937 }
2938
2939 *input = AUDIO_IO_HANDLE_NONE;
2940 *inputType = API_INPUT_INVALID;
2941
Francois Gaffie716e1432019-01-14 16:58:59 +01002942 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002943 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002944 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002945 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002946 ALOGW("%s could not find input mix for attr %s",
2947 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002948 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002949 }
jiabinc1de2df2019-05-07 14:26:40 -07002950 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2951 String8(attr->tags + strlen("addr=")),
2952 AUDIO_FORMAT_DEFAULT);
2953 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002954 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002955 __func__, attributes.source, attributes.tags);
2956 status = BAD_VALUE;
2957 goto error;
2958 }
2959
Kevin Rocard25f9b052019-02-27 15:08:54 -08002960 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2961 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2962 } else {
2963 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2964 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002965 if (virtualDeviceId) {
2966 *virtualDeviceId = policyMix->mVirtualDeviceId;
2967 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002968 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002969 if (explicitRoutingDevice != nullptr) {
2970 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002971 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002972 // Prevent from storing invalid requested device id in clients
2973 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002974 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002975 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2976 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002977 }
François Gaffie11d30102018-11-02 16:09:09 +01002978 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002979 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002980 status = BAD_VALUE;
2981 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002982 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002983 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2984 *inputType = API_INPUT_MIX_CAPTURE;
2985 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002986 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2987 // there is an external policy, but this input is attached to a mix of recorders,
2988 // meaning it receives audio injected into the framework, so the recorder doesn't
2989 // know about it and is therefore considered "legacy"
2990 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002991
2992 if (virtualDeviceId) {
2993 *virtualDeviceId = policyMix->mVirtualDeviceId;
2994 }
François Gaffie11d30102018-11-02 16:09:09 +01002995 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002996 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002997 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002998 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002999 } else {
3000 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003001 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003002
Eric Laurent599c7582015-12-07 18:05:55 -08003003 }
3004
François Gaffiec005e562018-11-06 15:04:49 +01003005 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003006 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003007 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003008 AudioProfileVector profiles;
3009 status_t ret = getProfilesForDevices(
3010 DeviceVector(device), profiles, flags, true /*isInput*/);
3011 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003012 const auto channels = profiles[0]->getChannels();
3013 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3014 config->channel_mask = *channels.begin();
3015 }
3016 const auto sampleRates = profiles[0]->getSampleRates();
3017 if (!sampleRates.empty() &&
3018 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3019 config->sample_rate = *sampleRates.begin();
3020 }
jiabinf1c73972022-04-14 16:28:52 -07003021 config->format = profiles[0]->getFormat();
3022 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003023 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003024 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003025
Marvin Ramine5a122d2023-12-07 13:57:59 +01003026
3027 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3028 *virtualDeviceId = policyMix->mVirtualDeviceId;
3029 }
3030
Eric Laurent8f42ea12018-08-08 09:08:25 -07003031exit:
3032
François Gaffiec005e562018-11-06 15:04:49 +01003033 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3034 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003035
Francois Gaffie716e1432019-01-14 16:58:59 +01003036 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003037 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003038 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003039
Mikhail Naganov2996f672019-04-18 12:29:59 -07003040 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003041 requestedDeviceId, attributes.source, flags,
3042 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003043 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003044 // Move (if found) effect for the client session to its input
3045 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003046 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003047
3048 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3049 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003050
Eric Laurent599c7582015-12-07 18:05:55 -08003051 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003052
3053error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003054 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003055}
3056
3057
François Gaffie11d30102018-11-02 16:09:09 +01003058audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003059 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003060 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003061 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003062 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003063 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003064{
3065 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003066 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003067 bool isSoundTrigger = false;
3068
François Gaffiec005e562018-11-06 15:04:49 +01003069 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003070 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3071 if (index >= 0) {
3072 input = mSoundTriggerSessions.valueFor(session);
3073 isSoundTrigger = true;
3074 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3075 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3076 } else {
3077 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003078 }
François Gaffiec005e562018-11-06 15:04:49 +01003079 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003080 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003081 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003082 }
3083
Carter Hsua3abb402021-10-26 11:11:20 +08003084 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3085 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3086 }
3087
Eric Laurentfe231122017-11-17 17:48:06 -08003088 // sampling rate and flags may be updated by getInputProfile
3089 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3090 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003091 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003092 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003093 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003094 // find a compatible input profile (not necessarily identical in parameters)
3095 sp<IOProfile> profile = getInputProfile(
3096 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3097 if (profile == nullptr) {
3098 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003099 }
jiabin2fd710d2022-05-02 23:20:22 +00003100
Glenn Kasten05ddca52016-02-11 08:17:12 -08003101 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003102 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003103 if (samplingRate == 0) {
3104 samplingRate = profileSamplingRate;
3105 }
Eric Laurente552edb2014-03-10 17:42:56 -07003106
Eric Laurent322b4d22015-04-03 15:57:54 -07003107 if (profile->getModuleHandle() == 0) {
3108 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003109 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003110 }
3111
Eric Laurentec376dc2021-04-08 20:41:22 +02003112 // Reuse an already opened input if a client with the same session ID already exists
3113 // on that input
3114 for (size_t i = 0; i < mInputs.size(); i++) {
3115 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3116 if (desc->mProfile != profile) {
3117 continue;
3118 }
3119 RecordClientVector clients = desc->clientsList();
3120 for (const auto &client : clients) {
3121 if (session == client->session()) {
3122 return desc->mIoHandle;
3123 }
3124 }
3125 }
3126
Eric Laurent3974e3b2017-12-07 17:58:43 -08003127 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003128 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003129 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003130 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003131 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003132 continue;
3133 }
3134 // if sound trigger, reuse input if used by other sound trigger on same session
3135 // else
3136 // reuse input if active client app is not in IDLE state
3137 //
3138 RecordClientVector clients = desc->clientsList();
3139 bool doClose = false;
3140 for (const auto& client : clients) {
3141 if (isSoundTrigger != client->isSoundTrigger()) {
3142 continue;
3143 }
3144 if (client->isSoundTrigger()) {
3145 if (session == client->session()) {
3146 return desc->mIoHandle;
3147 }
3148 continue;
3149 }
3150 if (client->active() && client->appState() != APP_STATE_IDLE) {
3151 return desc->mIoHandle;
3152 }
3153 doClose = true;
3154 }
3155 if (doClose) {
3156 closeInput(desc->mIoHandle);
3157 } else {
3158 i++;
3159 }
3160 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003161 }
3162
Eric Laurentfe231122017-11-17 17:48:06 -08003163 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003164
Eric Laurentfe231122017-11-17 17:48:06 -08003165 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3166 lConfig.sample_rate = profileSamplingRate;
3167 lConfig.channel_mask = profileChannelMask;
3168 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003169
François Gaffie11d30102018-11-02 16:09:09 +01003170 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003171
3172 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003173 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003174 (profileSamplingRate != lConfig.sample_rate) ||
3175 !audio_formats_match(profileFormat, lConfig.format) ||
3176 (profileChannelMask != lConfig.channel_mask)) {
3177 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003178 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003179 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003180 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003181 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003182 }
Eric Laurent599c7582015-12-07 18:05:55 -08003183 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003184 }
3185
Eric Laurentc722f302014-12-10 11:21:49 -08003186 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003187
Eric Laurent599c7582015-12-07 18:05:55 -08003188 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003189 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003190
Eric Laurent599c7582015-12-07 18:05:55 -08003191 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003192}
3193
Eric Laurent4eb58f12018-12-07 16:41:02 -08003194status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003195{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003196 ALOGV("%s portId %d", __FUNCTION__, portId);
3197
3198 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3199 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003200 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003201 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003202 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003203 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003204 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003205 if (client->active()) {
3206 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3207 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003208 }
3209
Eric Laurent8f42ea12018-08-08 09:08:25 -07003210 audio_session_t session = client->session();
3211
Eric Laurent4eb58f12018-12-07 16:41:02 -08003212 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003213
Eric Laurent4eb58f12018-12-07 16:41:02 -08003214 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003215
Eric Laurent4eb58f12018-12-07 16:41:02 -08003216 status_t status = inputDesc->start();
3217 if (status != NO_ERROR) {
3218 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003219 }
Eric Laurente552edb2014-03-10 17:42:56 -07003220
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003221 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003222 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003223 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003224
Eric Laurent8f42ea12018-08-08 09:08:25 -07003225 // indicate active capture to sound trigger service if starting capture from a mic on
3226 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003227 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003228 if (device != nullptr) {
3229 status = setInputDevice(input, device, true /* force */);
3230 } else {
3231 ALOGW("%s no new input device can be found for descriptor %d",
3232 __FUNCTION__, inputDesc->getId());
3233 status = BAD_VALUE;
3234 }
Eric Laurente552edb2014-03-10 17:42:56 -07003235
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003236 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003237 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003238 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003239 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003240 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3241 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003242 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003243 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003244
François Gaffie11d30102018-11-02 16:09:09 +01003245 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3246 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003247 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003248 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003249 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003250
Eric Laurent8f42ea12018-08-08 09:08:25 -07003251 // automatically enable the remote submix output when input is started if not
3252 // used by a policy mix of type MIX_TYPE_RECORDERS
3253 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003254 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003255 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003256 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003257 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003258 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3259 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003260 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003261 if (address != "") {
3262 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3263 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003264 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003265 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003266 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003267 } else if (status != NO_ERROR) {
3268 // Restore client activity state.
3269 inputDesc->setClientActive(client, false);
3270 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003271 }
3272
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003273 ALOGV("%s input %d source = %d status = %d exit",
3274 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003275
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003276 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003277}
3278
Eric Laurent8fc147b2018-07-22 19:13:55 -07003279status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003280{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003281 ALOGV("%s portId %d", __FUNCTION__, portId);
3282
3283 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3284 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003285 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003286 return BAD_VALUE;
3287 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003288 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003289 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003290 if (!client->active()) {
3291 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003292 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003293 }
Carter Hsue6139d52021-07-08 10:30:20 +08003294 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003295 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003296
Eric Laurent8f42ea12018-08-08 09:08:25 -07003297 inputDesc->stop();
3298 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003299 auto current_source = inputDesc->source();
3300 setInputDevice(input, getNewInputDevice(inputDesc),
3301 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003302 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003303 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003304 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003305 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003306 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3307 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003308 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003309 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003310
3311 // automatically disable the remote submix output when input is stopped if not
3312 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003313 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003314 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003315 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003316 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003317 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3318 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003319 }
3320 if (address != "") {
3321 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3322 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003323 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003324 }
3325 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003326 resetInputDevice(input);
3327
3328 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3329 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003330 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3331 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003332 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003333 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334 }
3335 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003336 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003337 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003338}
3339
Eric Laurent8fc147b2018-07-22 19:13:55 -07003340void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003341{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003342 ALOGV("%s portId %d", __FUNCTION__, portId);
3343
3344 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3345 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003346 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003347 return;
3348 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003349 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003350 audio_io_handle_t input = inputDesc->mIoHandle;
3351
Eric Laurent8f42ea12018-08-08 09:08:25 -07003352 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003353
Andy Hung39efb7a2018-09-26 15:39:28 -07003354 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003355
3356 // If no more clients are present in this session, park effects to an orphan chain
3357 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3358 if (clientsOnSession.size() == 0) {
3359 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3360 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003361 if (inputDesc->getClientCount() > 0) {
3362 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003363 return;
3364 }
3365
Eric Laurent05b90f82014-08-27 15:32:29 -07003366 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003367 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003368 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003369}
3370
Eric Laurent8f42ea12018-08-08 09:08:25 -07003371void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003372{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003373 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003374
3375 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003376 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003377 }
3378}
3379
Eric Laurent8f42ea12018-08-08 09:08:25 -07003380void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3381{
3382 stopInput(portId);
3383 releaseInput(portId);
3384}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003385
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003386bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3387 if (input->clientsList().size() == 0
3388 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3389 return true;
3390 }
3391 for (const auto& client : input->clientsList()) {
3392 sp<DeviceDescriptor> device =
3393 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3394 client->session());
3395 if (!input->supportedDevices().contains(device)) {
3396 return true;
3397 }
3398 }
3399 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3400 return false;
3401}
3402
Eric Laurent0dd51852019-04-19 18:18:58 -07003403void AudioPolicyManager::checkCloseInputs() {
3404 // After connecting or disconnecting an input device, close input if:
3405 // - it has no client (was just opened to check profile) OR
3406 // - none of its supported devices are connected anymore OR
3407 // - one of its clients cannot be routed to one of its supported
3408 // devices anymore. Otherwise update device selection
3409 std::vector<audio_io_handle_t> inputsToClose;
3410 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003411 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003412 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003413 }
3414 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003415 for (const audio_io_handle_t handle : inputsToClose) {
3416 ALOGV("%s closing input %d", __func__, handle);
3417 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003418 }
Eric Laurentd4692962014-05-05 18:13:44 -07003419}
3420
Vlad Popa87e0e582024-05-20 18:49:20 -07003421status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3422 const char *address __unused,
3423 bool enabled,
3424 audio_stream_type_t streamToDriveAbs)
3425{
3426 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3427 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3428 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3429 toString(streamToDriveAbs).c_str());
3430 return BAD_VALUE;
3431 }
3432
3433 if (enabled) {
3434 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3435 } else {
3436 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3437 }
3438
3439 return NO_ERROR;
3440}
3441
François Gaffie251c7f02018-11-07 10:41:08 +01003442void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003443{
3444 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003445 if (indexMin < 0 || indexMax < 0) {
3446 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3447 return;
3448 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003449 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003450
3451 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003452 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3453 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003454 continue;
3455 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003456 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003457 }
Eric Laurente552edb2014-03-10 17:42:56 -07003458}
3459
Eric Laurente0720872014-03-11 09:30:41 -07003460status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003461 int index,
3462 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003463{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003464 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003465 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3466 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3467 return NO_ERROR;
3468 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303469 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3470 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003471 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003472}
3473
Eric Laurente0720872014-03-11 09:30:41 -07003474status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003475 int *index,
3476 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003477{
François Gaffiec005e562018-11-06 15:04:49 +01003478 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3479 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003480 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003481 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003482 deviceTypes = mEngine->getOutputDevicesForStream(
3483 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003484 }
jiabin9a3361e2019-10-01 09:38:30 -07003485 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003486}
3487
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003488status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003489 int index,
3490 audio_devices_t device)
3491{
3492 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003493 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3494 if (group == VOLUME_GROUP_NONE) {
3495 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003496 return BAD_VALUE;
3497 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003498 ALOGV("%s: group %d matching with %s index %d",
3499 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003500 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3501 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3502 __FUNCTION__, toString(attributes).c_str());
3503 return NO_ERROR;
3504 }
François Gaffiecfe17322018-11-07 13:41:29 +01003505 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003506 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003507 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003508 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3509 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3510 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3511 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003512 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3513
3514 status = setVolumeCurveIndex(index, device, curves);
3515 if (status != NO_ERROR) {
3516 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3517 return status;
3518 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003519
jiabin9a3361e2019-10-01 09:38:30 -07003520 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003521 auto curCurvAttrs = curves.getAttributes();
3522 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3523 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003524 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003525 } else if (!curves.getStreamTypes().empty()) {
3526 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003527 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003528 } else {
3529 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3530 return BAD_VALUE;
3531 }
jiabin9a3361e2019-10-01 09:38:30 -07003532 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3533 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003534
François Gaffiecfe17322018-11-07 13:41:29 +01003535 // update volume on all outputs and streams matching the following:
3536 // - The requested stream (or a stream matching for volume control) is active on the output
3537 // - The device (or devices) selected by the engine for this stream includes
3538 // the requested device
3539 // - For non default requested device, currently selected device on the output is either the
3540 // requested device or one of the devices selected by the engine for this stream
3541 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3542 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003543 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003544 for (size_t i = 0; i < mOutputs.size(); i++) {
3545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003546 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003547
jiabin9a3361e2019-10-01 09:38:30 -07003548 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3549 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003550 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003551
3552 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003553 continue;
3554 }
3555 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3556 curDevices.find(device) == curDevices.end()) {
3557 continue;
3558 }
3559 bool applyVolume = false;
3560 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3561 curSrcDevices.insert(device);
3562 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003563 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3564 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003565 } else {
3566 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3567 }
3568 if (!applyVolume) {
3569 continue; // next output
3570 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003571 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3572 // If a higher priority strategy is active, and the output is routed to a device with a
3573 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003574 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003575 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003576 // If the volume source is active with higher priority source, ensure at least Sw Muted
3577 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003578 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3579 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3580 false /*preferredDevice*/);
3581 if (activeClients.empty()) {
3582 continue;
3583 }
3584 bool isPreempted = false;
3585 bool isHigherPriority = productStrategy < strategy;
3586 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003587 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003588 ALOGV("%s: Strategy=%d (\nrequester:\n"
3589 " group %d, volumeGroup=%d attributes=%s)\n"
3590 " higher priority source active:\n"
3591 " volumeGroup=%d attributes=%s) \n"
3592 " on output %zu, bailing out", __func__, productStrategy,
3593 group, group, toString(attributes).c_str(),
3594 client->volumeSource(), toString(client->attributes()).c_str(), i);
3595 applyVolume = false;
3596 isPreempted = true;
3597 break;
3598 }
3599 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003600 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003601 applyVolume = true;
3602 }
3603 }
3604 if (isPreempted || applyVolume) {
3605 break;
3606 }
3607 }
3608 if (!applyVolume) {
3609 continue; // next output
3610 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003611 }
François Gaffieed91f582020-01-31 10:35:37 +01003612 //FIXME: workaround for truncated touch sounds
3613 // delayed volume change for system stream to be removed when the problem is
3614 // handled by system UI
3615 status_t volStatus = checkAndSetVolume(
3616 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003617 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003618 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3619 if (volStatus != NO_ERROR) {
3620 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003621 }
3622 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003623
3624 // update voice volume if the an active call route exists
3625 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3626 && (curSrcDevices.find(
3627 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3628 != curSrcDevices.end())) {
3629 bool isVoiceVolSrc;
3630 bool isBtScoVolSrc;
3631 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3632 isVoiceVolSrc, isBtScoVolSrc, __func__)
3633 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003634 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3635 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3636 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003637 }
3638 }
3639
François Gaffiecfe17322018-11-07 13:41:29 +01003640 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3641 return status;
3642}
3643
François Gaffieaaac0fd2018-11-22 17:56:39 +01003644status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003645 audio_devices_t device,
3646 IVolumeCurves &volumeCurves)
3647{
3648 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3649 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003650 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3651 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003652 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303653 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3654 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003655 return BAD_VALUE;
3656 }
3657 if (!audio_is_output_device(device)) {
3658 return BAD_VALUE;
3659 }
3660
3661 // Force max volume if stream cannot be muted
3662 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3663
François Gaffieaaac0fd2018-11-22 17:56:39 +01003664 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003665 volumeCurves.addCurrentVolumeIndex(device, index);
3666 return NO_ERROR;
3667}
3668
3669status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3670 int &index,
3671 audio_devices_t device)
3672{
3673 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3674 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003675 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003676 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003677 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003678 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003679 }
jiabin9a3361e2019-10-01 09:38:30 -07003680 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003681}
3682
3683status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3684 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003685 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003686{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003687 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003688 return BAD_VALUE;
3689 }
jiabin9a3361e2019-10-01 09:38:30 -07003690 index = curves.getVolumeIndex(deviceTypes);
3691 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003692 return NO_ERROR;
3693}
3694
3695status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3696 int &index)
3697{
3698 index = getVolumeCurves(attr).getVolumeIndexMin();
3699 return NO_ERROR;
3700}
3701
3702status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3703 int &index)
3704{
3705 index = getVolumeCurves(attr).getVolumeIndexMax();
3706 return NO_ERROR;
3707}
3708
Eric Laurent36829f92017-04-07 19:04:42 -07003709audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003710{
3711 // select one output among several suitable for global effects.
3712 // The priority is as follows:
3713 // 1: An offloaded output. If the effect ends up not being offloadable,
3714 // AudioFlinger will invalidate the track and the offloaded output
3715 // will be closed causing the effect to be moved to a PCM output.
3716 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003717 // 3: The primary output
3718 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003719
François Gaffiec005e562018-11-06 15:04:49 +01003720 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3721 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003722 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003723
Eric Laurent36829f92017-04-07 19:04:42 -07003724 if (outputs.size() == 0) {
3725 return AUDIO_IO_HANDLE_NONE;
3726 }
Eric Laurente552edb2014-03-10 17:42:56 -07003727
Eric Laurent36829f92017-04-07 19:04:42 -07003728 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3729 bool activeOnly = true;
3730
3731 while (output == AUDIO_IO_HANDLE_NONE) {
3732 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3733 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3734 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3735
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003736 for (audio_io_handle_t output : outputs) {
3737 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003738 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003739 continue;
3740 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003741 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3742 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003743 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003744 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003745 }
3746 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003747 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003748 }
3749 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003750 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003751 }
3752 }
3753 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3754 output = outputOffloaded;
3755 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3756 output = outputDeepBuffer;
3757 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3758 output = outputPrimary;
3759 } else {
3760 output = outputs[0];
3761 }
3762 activeOnly = false;
3763 }
3764
3765 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003766 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3767 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003768 mMusicEffectOutput = output;
3769 }
3770
3771 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003772 return output;
3773}
3774
Eric Laurent36829f92017-04-07 19:04:42 -07003775audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3776{
3777 return selectOutputForMusicEffects();
3778}
3779
Eric Laurente0720872014-03-11 09:30:41 -07003780status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003781 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003782 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003783 int session,
3784 int id)
3785{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003786 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003787 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003788 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003789 index = mInputs.indexOfKey(io);
3790 if (index < 0) {
3791 ALOGW("registerEffect() unknown io %d", io);
3792 return INVALID_OPERATION;
3793 }
Eric Laurente552edb2014-03-10 17:42:56 -07003794 }
3795 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003796 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3797 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3798 || strategy == PRODUCT_STRATEGY_NONE));
3799 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003800}
3801
Eric Laurentc241b0d2018-11-28 09:08:49 -08003802status_t AudioPolicyManager::unregisterEffect(int id)
3803{
3804 if (mEffects.getEffect(id) == nullptr) {
3805 return INVALID_OPERATION;
3806 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003807 if (mEffects.isEffectEnabled(id)) {
3808 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3809 setEffectEnabled(id, false);
3810 }
3811 return mEffects.unregisterEffect(id);
3812}
3813
3814status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3815{
3816 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3817 if (effect == nullptr) {
3818 return INVALID_OPERATION;
3819 }
3820
3821 status_t status = mEffects.setEffectEnabled(id, enabled);
3822 if (status == NO_ERROR) {
3823 mInputs.trackEffectEnabled(effect, enabled);
3824 }
3825 return status;
3826}
3827
Eric Laurent6c796322019-04-09 14:13:17 -07003828
3829status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3830{
3831 mEffects.moveEffects(ids, io);
3832 return NO_ERROR;
3833}
3834
Eric Laurentc75307b2015-03-17 15:29:32 -07003835bool AudioPolicyManager::isStreamActive(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.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003839}
3840
3841bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3842{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003843 auto vs = toVolumeSource(stream, false);
3844 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003845}
3846
Eric Laurente0720872014-03-11 09:30:41 -07003847bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003848{
3849 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003850 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003851 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003852 return true;
3853 }
3854 }
3855 return false;
3856}
3857
Eric Laurent275e8e92014-11-30 15:14:47 -08003858// Register a list of custom mixes with their attributes and format.
3859// When a mix is registered, corresponding input and output profiles are
3860// added to the remote submix hw module. The profile contains only the
3861// parameters (sampling rate, format...) specified by the mix.
3862// The corresponding input remote submix device is also connected.
3863//
3864// When a remote submix device is connected, the address is checked to select the
3865// appropriate profile and the corresponding input or output stream is opened.
3866//
3867// When capture starts, getInputForAttr() will:
3868// - 1 look for a mix matching the address passed in attribtutes tags if any
3869// - 2 if none found, getDeviceForInputSource() will:
3870// - 2.1 look for a mix matching the attributes source
3871// - 2.2 if none found, default to device selection by policy rules
3872// At this time, the corresponding output remote submix device is also connected
3873// and active playback use cases can be transferred to this mix if needed when reconnecting
3874// after AudioTracks are invalidated
3875//
3876// When playback starts, getOutputForAttr() will:
3877// - 1 look for a mix matching the address passed in attribtutes tags if any
3878// - 2 if none found, look for a mix matching the attributes usage
3879// - 3 if none found, default to device and output selection by policy rules.
3880
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003881status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003882{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003883 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3884 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003885 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003886 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003887 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003888 // examine each mix's route type
3889 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003890 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003891 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3892 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3893 ALOGE("Unsupported Policy Mix %zu of %zu: "
3894 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3895 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003896 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003897 break;
3898 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003899 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3900 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003901 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003902 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3903 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003904 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003905 rSubmixModule = mHwModules.getModuleFromName(
3906 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3907 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003908 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003909 i);
3910 res = INVALID_OPERATION;
3911 break;
3912 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003913 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003914
Eric Laurent97ac8712018-07-27 18:59:02 -07003915 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003916 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003917 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003918 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003919 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3920 } else {
3921 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3922 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003923 }
François Gaffie036e1e92015-03-19 10:16:24 +01003924
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003925 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003926 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003927 res = INVALID_OPERATION;
3928 break;
3929 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003930 audio_config_t outputConfig = mix.mFormat;
3931 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003932 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3933 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003934 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3935 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003936 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003937 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3938 audio_is_linear_pcm(outputConfig.format)
3939 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003940 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003941 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3942 audio_is_linear_pcm(inputConfig.format)
3943 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003944
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003945 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003946 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003947 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003948 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003949 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003950 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003951 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003952 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3953 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003954 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003955 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003956 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003957
3958 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3959 mix.mDeviceType, mix.mDeviceAddress,
3960 String8(), AUDIO_FORMAT_DEFAULT);
3961 if (device == nullptr) {
3962 res = INVALID_OPERATION;
3963 break;
3964 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003965
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003966 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003967 // First try to find an already opened output supporting the device
3968 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003969 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003970
Eric Laurentc529cf62020-04-17 18:19:10 -07003971 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003972 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003973 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003974 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003975 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003976 } else {
3977 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003978 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003979 }
3980 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003981 // If no output found, try to find a direct output profile supporting the device
3982 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3983 sp<HwModule> module = mHwModules[i];
3984 for (size_t j = 0;
3985 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3986 j++) {
3987 sp<IOProfile> profile = module->getOutputProfiles()[j];
3988 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3989 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3990 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003991 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003992 res = INVALID_OPERATION;
3993 } else {
3994 foundOutput = true;
3995 }
3996 }
3997 }
3998 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003999 if (res != NO_ERROR) {
4000 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004001 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004002 res = INVALID_OPERATION;
4003 break;
4004 } else if (!foundOutput) {
4005 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004006 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004007 res = INVALID_OPERATION;
4008 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004009 } else {
4010 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004011 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004012 }
Eric Laurentc722f302014-12-10 11:21:49 -08004013 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004014 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004015 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004016 if (audio_flags::audio_mix_ownership()) {
4017 // Only unregister mixes that were actually registered to not accidentally unregister
4018 // mixes that already existed previously.
4019 unregisterPolicyMixes(registeredMixes);
4020 registeredMixes.clear();
4021 } else {
4022 unregisterPolicyMixes(mixes);
4023 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004024 } else if (checkOutputs) {
4025 checkForDeviceAndOutputChanges();
4026 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004027 }
4028 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004029}
4030
4031status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4032{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004033 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004034 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004035 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004036 sp<HwModule> rSubmixModule;
4037 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004038 for (const auto& mix : mixes) {
4039 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004040
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004041 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004042 rSubmixModule = mHwModules.getModuleFromName(
4043 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4044 if (rSubmixModule == 0) {
4045 res = INVALID_OPERATION;
4046 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004047 }
4048 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004049
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004050 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004051
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004052 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004053 res = INVALID_OPERATION;
4054 continue;
4055 }
4056
Marvin Ramin0783e202024-03-05 12:45:50 +01004057 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004058 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004059 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4060 status_t currentRes =
4061 setDeviceConnectionStateInt(device,
4062 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4063 address.c_str(),
4064 "remote-submix",
4065 AUDIO_FORMAT_DEFAULT);
4066 if (!audio_flags::audio_mix_ownership()) {
4067 res = currentRes;
4068 }
4069 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004070 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004071 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004072 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004073 }
4074 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004075 }
jiabin5740f082019-08-19 15:08:30 -07004076 rSubmixModule->removeOutputProfile(address.c_str());
4077 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004078
Kevin Rocard153f92d2018-12-18 18:33:28 -08004079 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004080 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004081 res = INVALID_OPERATION;
4082 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004083 } else {
4084 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004085 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004086 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004087 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004088
4089 if (res == NO_ERROR && checkOutputs) {
4090 checkForDeviceAndOutputChanges();
4091 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004092 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004093 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004094}
4095
Marvin Raminbdefaf02023-11-01 09:10:32 +01004096status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4097 if (!audio_flags::audio_mix_test_api()) {
4098 return INVALID_OPERATION;
4099 }
4100
4101 _aidl_return.clear();
4102 _aidl_return.reserve(mPolicyMixes.size());
4103 for (const auto &policyMix: mPolicyMixes) {
4104 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4105 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4106 policyMix->mCbFlags);
4107 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004108 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004109 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004110 }
4111
Vlad Popaa5d73f32024-03-08 16:05:38 -08004112 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004113 return OK;
4114}
4115
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004116status_t AudioPolicyManager::updatePolicyMix(
4117 const AudioMix& mix,
4118 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4119 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4120 if (res == NO_ERROR) {
4121 checkForDeviceAndOutputChanges();
4122 updateCallAndOutputRouting();
4123 }
4124 return res;
4125}
4126
Mikhail Naganov100f0122018-11-29 11:22:16 -08004127void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4128{
4129 size_t i = 0;
4130 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4131 for (const auto& fmt : mManualSurroundFormats) {
4132 if (i++ != 0) dst->append(", ");
4133 std::string sfmt;
4134 FormatConverter::toString(fmt, sfmt);
4135 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4136 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4137 }
4138}
4139
Eric Laurentc529cf62020-04-17 18:19:10 -07004140// Returns true if all devices types match the predicate and are supported by one HW module
4141bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004142 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004143 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004144 const char *context,
4145 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004146 for (size_t i = 0; i < devices.size(); i++) {
4147 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004148 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004149 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004150 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004151 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004152 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004153 return false;
4154 }
4155 }
4156 return true;
4157}
4158
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004159void AudioPolicyManager::changeOutputDevicesMuteState(
4160 const AudioDeviceTypeAddrVector& devices) {
4161 ALOGVV("%s() num devices %zu", __func__, devices.size());
4162
4163 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4164 getSoftwareOutputsForDevices(devices);
4165
4166 for (size_t i = 0; i < outputs.size(); i++) {
4167 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4168 DeviceVector prevDevices = outputDesc->devices();
4169 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4170 }
4171}
4172
4173std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4174 const AudioDeviceTypeAddrVector& devices) const
4175{
4176 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4177 DeviceVector deviceDescriptors;
4178 for (size_t j = 0; j < devices.size(); j++) {
4179 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4180 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4181 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4182 ALOGE("%s: device type %#x address %s not supported or not an output device",
4183 __func__, devices[j].mType, devices[j].getAddress());
4184 continue;
4185 }
4186 deviceDescriptors.add(desc);
4187 }
4188 for (size_t i = 0; i < mOutputs.size(); i++) {
4189 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4190 continue;
4191 }
4192 outputs.push_back(mOutputs.valueAt(i));
4193 }
4194 return outputs;
4195}
4196
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004197status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004198 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004199 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004200 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4201 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004202 }
4203 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004204 if (res != NO_ERROR) {
4205 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4206 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004207 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004208
4209 checkForDeviceAndOutputChanges();
4210 updateCallAndOutputRouting();
4211
4212 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004213}
4214
4215status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4216 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004217 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4218 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004219 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004220 __FUNCTION__, uid);
4221 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004222 }
4223
Eric Laurentc529cf62020-04-17 18:19:10 -07004224 checkForDeviceAndOutputChanges();
4225 updateCallAndOutputRouting();
4226
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004227 return res;
4228}
4229
Eric Laurent2517af32020-11-25 15:31:27 +01004230
jiabin0a488932020-08-07 17:32:40 -07004231status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4232 device_role_t role,
4233 const AudioDeviceTypeAddrVector &devices) {
4234 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4235 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004236
Eric Laurentc529cf62020-04-17 18:19:10 -07004237 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004238 return BAD_VALUE;
4239 }
jiabin0a488932020-08-07 17:32:40 -07004240 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004241 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004242 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4243 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004244 return status;
4245 }
4246
4247 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004248
4249 bool forceVolumeReeval = false;
4250 // FIXME: workaround for truncated touch sounds
4251 // to be removed when the problem is handled by system UI
4252 uint32_t delayMs = 0;
4253 if (strategy == mCommunnicationStrategy) {
4254 forceVolumeReeval = true;
4255 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4256 updateInputRouting();
4257 }
4258 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004259
4260 return NO_ERROR;
4261}
4262
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004263void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4264 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004265{
4266 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004267 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004268 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004269 // Only apply special touch sound delay once
4270 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004271 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004272 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004273 for (size_t i = 0; i < mOutputs.size(); i++) {
4274 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4275 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004276 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4277 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004278 // As done in setDeviceConnectionState, we could also fix default device issue by
4279 // preventing the force re-routing in case of default dev that distinguishes on address.
4280 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004281 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004282 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004283 // If the device is using preferred mixer attributes, the output need to reopen
4284 // with default configuration when the new selected devices are different from
4285 // current routing devices.
4286 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4287 continue;
4288 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304289
4290 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4291 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004292 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004293 // Only apply special touch sound delay once
4294 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004295 }
4296 if (forceVolumeReeval && !newDevices.isEmpty()) {
4297 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4298 }
4299 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004300 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004301 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004302}
4303
Eric Laurent2517af32020-11-25 15:31:27 +01004304void AudioPolicyManager::updateInputRouting() {
4305 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304306 // Skip for hotword recording as the input device switch
4307 // is handled within sound trigger HAL
4308 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4309 continue;
4310 }
Eric Laurent2517af32020-11-25 15:31:27 +01004311 auto newDevice = getNewInputDevice(activeDesc);
4312 // Force new input selection if the new device can not be reached via current input
4313 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4314 setInputDevice(activeDesc->mIoHandle, newDevice);
4315 } else {
4316 closeInput(activeDesc->mIoHandle);
4317 }
4318 }
4319}
4320
Paul Wang5d7cdb52022-11-22 09:45:06 +00004321status_t
4322AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4323 device_role_t role,
4324 const AudioDeviceTypeAddrVector &devices) {
4325 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4326 dumpAudioDeviceTypeAddrVector(devices).c_str());
4327
Eric Laurent78fedbf2023-03-09 14:40:44 +01004328 if (!areAllDevicesSupported(
4329 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004330 return BAD_VALUE;
4331 }
4332 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4333 if (status != NO_ERROR) {
4334 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4335 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4336 return status;
4337 }
4338
4339 checkForDeviceAndOutputChanges();
4340
4341 bool forceVolumeReeval = false;
4342 // TODO(b/263479999): workaround for truncated touch sounds
4343 // to be removed when the problem is handled by system UI
4344 uint32_t delayMs = 0;
4345 if (strategy == mCommunnicationStrategy) {
4346 forceVolumeReeval = true;
4347 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4348 updateInputRouting();
4349 }
4350 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4351
4352 return NO_ERROR;
4353}
4354
4355status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4356 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004357{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004358 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004359
Paul Wang5d7cdb52022-11-22 09:45:06 +00004360 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004361 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004362 ALOGW_IF(status != NAME_NOT_FOUND,
4363 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004364 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004365 return status;
4366 }
4367
4368 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004369
4370 bool forceVolumeReeval = false;
4371 // FIXME: workaround for truncated touch sounds
4372 // to be removed when the problem is handled by system UI
4373 uint32_t delayMs = 0;
4374 if (strategy == mCommunnicationStrategy) {
4375 forceVolumeReeval = true;
4376 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4377 updateInputRouting();
4378 }
4379 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004380
4381 return NO_ERROR;
4382}
4383
jiabin0a488932020-08-07 17:32:40 -07004384status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4385 device_role_t role,
4386 AudioDeviceTypeAddrVector &devices) {
4387 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004388}
4389
Jiabin Huang3b98d322020-09-03 17:54:16 +00004390status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4391 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4392 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4393 dumpAudioDeviceTypeAddrVector(devices).c_str());
4394
Mikhail Naganov55773032020-10-01 15:08:13 -07004395 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004396 return BAD_VALUE;
4397 }
4398 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4399 ALOGW_IF(status != NO_ERROR,
4400 "Engine could not set preferred devices %s for audio source %d role %d",
4401 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4402
4403 return status;
4404}
4405
4406status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4407 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4408 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4409 dumpAudioDeviceTypeAddrVector(devices).c_str());
4410
Mikhail Naganov55773032020-10-01 15:08:13 -07004411 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004412 return BAD_VALUE;
4413 }
4414 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4415 ALOGW_IF(status != NO_ERROR,
4416 "Engine could not add preferred devices %s for audio source %d role %d",
4417 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4418
Eric Laurent2517af32020-11-25 15:31:27 +01004419 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004420 return status;
4421}
4422
4423status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4424 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4425{
4426 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4427 dumpAudioDeviceTypeAddrVector(devices).c_str());
4428
Eric Laurent78fedbf2023-03-09 14:40:44 +01004429 if (!areAllDevicesSupported(
4430 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004431 return BAD_VALUE;
4432 }
4433
4434 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4435 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004436 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004437 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004438 if (status == NO_ERROR) {
4439 updateInputRouting();
4440 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004441 return status;
4442}
4443
4444status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4445 device_role_t role) {
4446 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4447
4448 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004449 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004450 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004451 if (status == NO_ERROR) {
4452 updateInputRouting();
4453 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004454 return status;
4455}
4456
4457status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4458 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4459 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4460}
4461
Oscar Azucena90e77632019-11-27 17:12:28 -08004462status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004463 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004464 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004465 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4466 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004467 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004468 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4469 if (status != NO_ERROR) {
4470 ALOGE("%s() could not set device affinity for userId %d",
4471 __FUNCTION__, userId);
4472 return status;
4473 }
4474
4475 // reevaluate outputs for all devices
4476 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004477 changeOutputDevicesMuteState(devices);
4478 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4479 true /* skipDelays */);
4480 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004481
4482 return NO_ERROR;
4483}
4484
4485status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004486 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004487 AudioDeviceTypeAddrVector devices;
4488 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004489 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4490 if (status != NO_ERROR) {
4491 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4492 __FUNCTION__, userId);
4493 return status;
4494 }
4495
4496 // reevaluate outputs for all devices
4497 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004498 changeOutputDevicesMuteState(devices);
4499 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4500 true /* skipDelays */);
4501 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004502
4503 return NO_ERROR;
4504}
4505
Andy Hungc29d82b2018-10-05 12:23:17 -07004506void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004507{
Andy Hungc29d82b2018-10-05 12:23:17 -07004508 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004509 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004510 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004511 std::string stateLiteral;
4512 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004513 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004514 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4515 "communications", "media", "record", "dock", "system",
4516 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4517 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4518 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004519 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4520 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4521 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4522 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4523 dst->append(" (MANUAL: ");
4524 dumpManualSurroundFormats(dst);
4525 dst->append(")");
4526 }
4527 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004528 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004529 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4530 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004531 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004532 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004533
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004534 dst->append("\n");
4535 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4536 dst->append("\n");
4537 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004538 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004539 mOutputs.dump(dst);
4540 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004541 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004542 mAudioPatches.dump(dst);
4543 mPolicyMixes.dump(dst);
4544 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004545
Kevin Rocardb99cc752019-03-21 20:52:24 -07004546 dst->appendFormat(" AllowedCapturePolicies:\n");
4547 for (auto& policy : mAllowedCapturePolicies) {
4548 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4549 }
4550
jiabina84c3d32022-12-02 18:59:55 +00004551 dst->appendFormat(" Preferred mixer audio configuration:\n");
4552 for (const auto it : mPreferredMixerAttrInfos) {
4553 dst->appendFormat(" - device port id: %d\n", it.first);
4554 for (const auto preferredMixerInfoIt : it.second) {
4555 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4556 preferredMixerInfoIt.second->dump(dst);
4557 }
4558 }
4559
François Gaffiec005e562018-11-06 15:04:49 +01004560 dst->appendFormat("\nPolicy Engine dump:\n");
4561 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004562
4563 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4564 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4565 dst->appendFormat(" - device type: %s, driving stream %d\n",
4566 dumpDeviceTypes({it.first}).c_str(),
4567 mEngine->getVolumeGroupForAttributes(it.second));
4568 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004569}
4570
4571status_t AudioPolicyManager::dump(int fd)
4572{
4573 String8 result;
4574 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004575 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004576 return NO_ERROR;
4577}
4578
Kevin Rocardb99cc752019-03-21 20:52:24 -07004579status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4580{
4581 mAllowedCapturePolicies[uid] = capturePolicy;
4582 return NO_ERROR;
4583}
4584
Eric Laurente552edb2014-03-10 17:42:56 -07004585// This function checks for the parameters which can be offloaded.
4586// This can be enhanced depending on the capability of the DSP and policy
4587// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004588audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004589{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004590 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004591 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004592 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004593 offloadInfo.format,
4594 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4595 offloadInfo.has_video);
4596
jiabin2b9d5a12021-12-10 01:06:29 +00004597 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004598 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004599 }
4600
4601 // See if there is a profile to support this.
4602 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004603 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004604 offloadInfo.sample_rate,
4605 offloadInfo.format,
4606 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004607 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4608 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004609 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4610 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4611 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004612 if (profile == nullptr) {
4613 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4614 }
4615 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4616 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4617 }
4618 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004619}
4620
Michael Chana94fbb22018-04-24 14:31:19 +10004621bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4622 const audio_attributes_t& attributes) {
4623 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004624 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004625 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4626 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004627 config.sample_rate,
4628 config.format,
4629 config.channel_mask,
4630 output_flags,
4631 true /* directOnly */);
4632 ALOGV("%s() profile %sfound with name: %s, "
4633 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4634 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004635 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004636 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004637
4638 // also try the MSD module if compatible profile not found
4639 if (profile == nullptr) {
4640 profile = getMsdProfileForOutput(outputDevices,
4641 config.sample_rate,
4642 config.format,
4643 config.channel_mask,
4644 output_flags,
4645 true /* directOnly */);
4646 ALOGV("%s() MSD profile %sfound with name: %s, "
4647 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4648 __FUNCTION__, profile != 0 ? "" : "NOT ",
4649 (profile != 0 ? profile->getTagName().c_str() : "null"),
4650 config.sample_rate, config.format, config.channel_mask, output_flags);
4651 }
4652 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004653}
4654
jiabin2b9d5a12021-12-10 01:06:29 +00004655bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4656 bool durationIgnored) {
4657 if (mMasterMono) {
4658 return false; // no offloading if mono is set.
4659 }
4660
4661 // Check if offload has been disabled
4662 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4663 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4664 return false;
4665 }
4666
4667 // Check if stream type is music, then only allow offload as of now.
4668 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4669 {
4670 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4671 return false;
4672 }
4673
4674 //TODO: enable audio offloading with video when ready
4675 const bool allowOffloadWithVideo =
4676 property_get_bool("audio.offload.video", false /* default_value */);
4677 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4678 ALOGV("%s: has_video == true, returning false", __func__);
4679 return false;
4680 }
4681
4682 //If duration is less than minimum value defined in property, return false
4683 const int min_duration_secs = property_get_int32(
4684 "audio.offload.min.duration.secs", -1 /* default_value */);
4685 if (!durationIgnored) {
4686 if (min_duration_secs >= 0) {
4687 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4688 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4689 __func__, min_duration_secs);
4690 return false;
4691 }
4692 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4693 ALOGV("%s: Offload denied by duration < default min(=%u)",
4694 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4695 return false;
4696 }
4697 }
4698
4699 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4700 // creating an offloaded track and tearing it down immediately after start when audioflinger
4701 // detects there is an active non offloadable effect.
4702 // FIXME: We should check the audio session here but we do not have it in this context.
4703 // This may prevent offloading in rare situations where effects are left active by apps
4704 // in the background.
4705 if (mEffects.isNonOffloadableEffectEnabled()) {
4706 return false;
4707 }
4708
4709 return true;
4710}
4711
4712audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4713 const audio_config_t *config) {
4714 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4715 offloadInfo.format = config->format;
4716 offloadInfo.sample_rate = config->sample_rate;
4717 offloadInfo.channel_mask = config->channel_mask;
4718 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4719 offloadInfo.has_video = false;
4720 offloadInfo.is_streaming = false;
4721 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4722
4723 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4724 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4725 audio_flags_to_audio_output_flags(attr->flags, &flags);
4726 // only retain flags that will drive compressed offload or passthrough
4727 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4728 if (offloadPossible) {
4729 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4730 }
4731 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4732
Dorin Drimusfae3c642022-03-17 18:36:30 +01004733 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004734 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004735 DeviceVector outputDevices = engineOutputDevices;
4736 // the MSD module checks for different conditions and output devices
4737 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4738 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4739 continue;
4740 }
4741 outputDevices = getMsdAudioOutDevices();
4742 }
jiabin2b9d5a12021-12-10 01:06:29 +00004743 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004744 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004745 config->sample_rate, nullptr /*updatedSamplingRate*/,
4746 config->format, nullptr /*updatedFormat*/,
4747 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004748 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004749 continue;
4750 }
4751 // reject profiles not corresponding to a device currently available
4752 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4753 continue;
4754 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004755 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4756 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004757 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004758 != AUDIO_DIRECT_NOT_SUPPORTED) {
4759 // Already reports offload gapless supported. No need to report offload support.
4760 continue;
4761 }
4762 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4763 != AUDIO_OUTPUT_FLAG_NONE) {
4764 // If offload gapless is reported, no need to report offload support.
4765 directMode = (audio_direct_mode_t) ((directMode &
4766 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4767 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4768 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004769 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004770 }
4771 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004772 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004773 }
4774 }
4775 }
4776 return directMode;
4777}
4778
Dorin Drimusf2196d82022-01-03 12:11:18 +01004779status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4780 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004781 if (mEffects.isNonOffloadableEffectEnabled()) {
4782 return OK;
4783 }
jiabinf1c73972022-04-14 16:28:52 -07004784 DeviceVector devices;
4785 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004786 if (status != OK) {
4787 return status;
4788 }
4789 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4790 if (devices.empty()) {
4791 return OK; // no output devices for the attributes
4792 }
jiabinf1c73972022-04-14 16:28:52 -07004793 return getProfilesForDevices(devices, audioProfilesVector,
4794 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004795}
4796
jiabina84c3d32022-12-02 18:59:55 +00004797status_t AudioPolicyManager::getSupportedMixerAttributes(
4798 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4799 ALOGV("%s, portId=%d", __func__, portId);
4800 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4801 if (deviceDescriptor == nullptr) {
4802 ALOGE("%s the requested device is currently unavailable", __func__);
4803 return BAD_VALUE;
4804 }
jiabin96daffc2023-05-11 17:51:55 +00004805 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4806 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4807 deviceDescriptor->type());
4808 return BAD_VALUE;
4809 }
jiabina84c3d32022-12-02 18:59:55 +00004810 for (const auto& hwModule : mHwModules) {
4811 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4812 if (curProfile->supportsDevice(deviceDescriptor)) {
4813 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4814 }
4815 }
4816 }
4817 return NO_ERROR;
4818}
4819
4820status_t AudioPolicyManager::setPreferredMixerAttributes(
4821 const audio_attributes_t *attr,
4822 audio_port_handle_t portId,
4823 uid_t uid,
4824 const audio_mixer_attributes_t *mixerAttributes) {
4825 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4826 "mixerBehavior=%d}, uid=%d, portId=%u",
4827 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4828 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4829 mixerAttributes->mixer_behavior, uid, portId);
4830 if (attr->usage != AUDIO_USAGE_MEDIA) {
4831 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4832 return BAD_VALUE;
4833 }
4834 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4835 if (deviceDescriptor == nullptr) {
4836 ALOGE("%s the requested device is currently unavailable", __func__);
4837 return BAD_VALUE;
4838 }
4839 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4840 ALOGE("%s(%d), type=%d, is not a usb output device",
4841 __func__, portId, deviceDescriptor->type());
4842 return BAD_VALUE;
4843 }
4844
4845 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4846 audio_flags_to_audio_output_flags(attr->flags, &flags);
4847 flags = (audio_output_flags_t) (flags |
4848 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4849 sp<IOProfile> profile = nullptr;
4850 DeviceVector devices(deviceDescriptor);
4851 for (const auto& hwModule : mHwModules) {
4852 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4853 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004854 && curProfile->getCompatibilityScore(
4855 devices,
4856 mixerAttributes->config.sample_rate,
4857 nullptr /*updatedSamplingRate*/,
4858 mixerAttributes->config.format,
4859 nullptr /*updatedFormat*/,
4860 mixerAttributes->config.channel_mask,
4861 nullptr /*updatedChannelMask*/,
4862 flags,
4863 false /*exactMatchRequiredForInputFlags*/)
4864 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004865 profile = curProfile;
4866 break;
4867 }
4868 }
4869 }
4870 if (profile == nullptr) {
4871 ALOGE("%s, there is no compatible profile found", __func__);
4872 return BAD_VALUE;
4873 }
4874
4875 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4876 sp<PreferredMixerAttributesInfo>::make(
4877 uid, portId, profile, flags, *mixerAttributes);
4878 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4879 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4880
4881 // If 1) there is any client from the preferred mixer configuration owner that is currently
4882 // active and matches the strategy and 2) current output is on the preferred device and the
4883 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4884 // configuration.
4885 std::vector<audio_io_handle_t> outputsToReopen;
4886 for (size_t i = 0; i < mOutputs.size(); i++) {
4887 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004888 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4889 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004890 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004891 } else {
4892 for (const auto &client: output->getActiveClients()) {
4893 if (client->uid() == uid && client->strategy() == strategy) {
4894 client->setIsInvalid();
4895 outputsToReopen.push_back(output->mIoHandle);
4896 }
jiabina84c3d32022-12-02 18:59:55 +00004897 }
4898 }
4899 }
4900 }
4901 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4902 config.sample_rate = mixerAttributes->config.sample_rate;
4903 config.channel_mask = mixerAttributes->config.channel_mask;
4904 config.format = mixerAttributes->config.format;
4905 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004906 sp<SwAudioOutputDescriptor> desc =
4907 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4908 if (desc == nullptr) {
4909 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4910 continue;
4911 }
jiabin220eea12024-05-17 17:55:20 +00004912 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004913 }
4914
4915 return NO_ERROR;
4916}
4917
4918sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004919 audio_port_handle_t devicePortId,
4920 product_strategy_t strategy,
4921 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004922 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4923 if (it == mPreferredMixerAttrInfos.end()) {
4924 return nullptr;
4925 }
jiabind9a58d32023-06-01 17:57:30 +00004926 if (activeBitPerfectPreferred) {
4927 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004928 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004929 return info;
4930 }
4931 }
jiabina84c3d32022-12-02 18:59:55 +00004932 }
jiabind9a58d32023-06-01 17:57:30 +00004933 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4934 return strategyMatchedMixerAttrInfoIt == it->second.end()
4935 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004936}
4937
4938status_t AudioPolicyManager::getPreferredMixerAttributes(
4939 const audio_attributes_t *attr,
4940 audio_port_handle_t portId,
4941 audio_mixer_attributes_t* mixerAttributes) {
4942 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4943 portId, mEngine->getProductStrategyForAttributes(*attr));
4944 if (info == nullptr) {
4945 return NAME_NOT_FOUND;
4946 }
4947 *mixerAttributes = info->getMixerAttributes();
4948 return NO_ERROR;
4949}
4950
4951status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4952 audio_port_handle_t portId,
4953 uid_t uid) {
4954 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4955 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4956 if (preferredMixerAttrInfo == nullptr) {
4957 return NAME_NOT_FOUND;
4958 }
4959 if (preferredMixerAttrInfo->getUid() != uid) {
4960 ALOGE("%s, requested uid=%d, owned uid=%d",
4961 __func__, uid, preferredMixerAttrInfo->getUid());
4962 return PERMISSION_DENIED;
4963 }
4964 mPreferredMixerAttrInfos[portId].erase(strategy);
4965 if (mPreferredMixerAttrInfos[portId].empty()) {
4966 mPreferredMixerAttrInfos.erase(portId);
4967 }
4968
4969 // Reconfig existing output
4970 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4971 for (size_t i = 0; i < mOutputs.size(); i++) {
4972 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4973 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4974 }
4975 }
4976 for (const auto output : potentialOutputsToReopen) {
4977 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4978 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4979 preferredMixerAttrInfo->getFlags())) {
4980 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4981 }
4982 }
4983 return NO_ERROR;
4984}
4985
Eric Laurent6a94d692014-05-20 11:18:06 -07004986status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4987 audio_port_type_t type,
4988 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004989 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004990 unsigned int *generation)
4991{
jiabin19cdba52020-11-24 11:28:58 -08004992 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4993 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004994 return BAD_VALUE;
4995 }
4996 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004997 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 *num_ports = 0;
4999 }
5000
5001 size_t portsWritten = 0;
5002 size_t portsMax = *num_ports;
5003 *num_ports = 0;
5004 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005005 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5006 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005008 for (const auto& dev : mAvailableOutputDevices) {
5009 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005010 continue;
5011 }
5012 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005013 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005014 }
5015 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 }
5018 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005019 for (const auto& dev : mAvailableInputDevices) {
5020 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005021 continue;
5022 }
5023 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005024 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005025 }
5026 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005028 }
5029 }
5030 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5031 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5032 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5033 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5034 }
5035 *num_ports += mInputs.size();
5036 }
5037 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005038 size_t numOutputs = 0;
5039 for (size_t i = 0; i < mOutputs.size(); i++) {
5040 if (!mOutputs[i]->isDuplicated()) {
5041 numOutputs++;
5042 if (portsWritten < portsMax) {
5043 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5044 }
5045 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005046 }
Eric Laurent84c70242014-06-23 08:46:27 -07005047 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005048 }
5049 }
jiabina84c3d32022-12-02 18:59:55 +00005050
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005052 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005053 return NO_ERROR;
5054}
5055
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005056status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5057 std::vector<media::AudioPortFw>* _aidl_return) {
5058 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5059 audio_port_v7 port;
5060 dev->toAudioPort(&port);
5061 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5062 _aidl_return->push_back(std::move(aidlPort));
5063 return OK;
5064 };
5065
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005066 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005067 for (const auto& dev : module->getDeclaredDevices()) {
5068 if (role == media::AudioPortRole::NONE ||
5069 ((role == media::AudioPortRole::SOURCE)
5070 == audio_is_input_device(dev->type()))) {
5071 RETURN_STATUS_IF_ERROR(pushPort(dev));
5072 }
5073 }
5074 }
5075 return OK;
5076}
5077
jiabin19cdba52020-11-24 11:28:58 -08005078status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005079{
Eric Laurent99fcae42018-05-17 16:59:18 -07005080 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5081 return BAD_VALUE;
5082 }
5083 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5084 if (dev != 0) {
5085 dev->toAudioPort(port);
5086 return NO_ERROR;
5087 }
5088 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5089 if (dev != 0) {
5090 dev->toAudioPort(port);
5091 return NO_ERROR;
5092 }
5093 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5094 if (out != 0) {
5095 out->toAudioPort(port);
5096 return NO_ERROR;
5097 }
5098 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5099 if (in != 0) {
5100 in->toAudioPort(port);
5101 return NO_ERROR;
5102 }
5103 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005104}
5105
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005106status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5107 audio_patch_handle_t *handle,
5108 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005109{
François Gaffieafd4cea2019-11-18 15:50:22 +01005110 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005111 if (handle == NULL || patch == NULL) {
5112 return BAD_VALUE;
5113 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005114 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005115 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005116 return BAD_VALUE;
5117 }
5118 // only one source per audio patch supported for now
5119 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005120 return INVALID_OPERATION;
5121 }
Eric Laurent874c42872014-08-08 15:13:39 -07005122 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005123 return INVALID_OPERATION;
5124 }
Eric Laurent874c42872014-08-08 15:13:39 -07005125 for (size_t i = 0; i < patch->num_sinks; i++) {
5126 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5127 return INVALID_OPERATION;
5128 }
5129 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005130
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005131 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5132 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5133 if (srcDevice == nullptr || sinkDevice == nullptr) {
5134 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5135 return BAD_VALUE;
5136 }
5137 ALOGV("%s between source %s and sink %s", __func__,
5138 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5139 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5140 // Default attributes, default volume priority, not to infer with non raw audio patches.
5141 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5142 const struct audio_port_config *source = &patch->sources[0];
5143 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005144 new SourceClientDescriptor(
5145 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5146 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005147 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005148 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005149
5150 status_t status =
5151 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5152
5153 if (status != NO_ERROR) {
5154 return INVALID_OPERATION;
5155 }
5156 mAudioSources.add(portId, sourceDesc);
5157 return NO_ERROR;
5158}
5159
5160status_t AudioPolicyManager::connectAudioSourceToSink(
5161 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5162 const struct audio_patch *patch,
5163 audio_patch_handle_t &handle,
5164 uid_t uid, uint32_t delayMs)
5165{
5166 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5167 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5168 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5169 return INVALID_OPERATION;
5170 }
5171 sourceDesc->connect(handle, sinkDevice);
5172 if (isMsdPatch(handle)) {
5173 return NO_ERROR;
5174 }
5175 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5176 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5177 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5178 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5179 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5180 goto FailurePatchAdded;
5181 }
5182 status = swOutput->start();
5183 if (status != NO_ERROR) {
5184 goto FailureSourceAdded;
5185 }
5186 swOutput->addClient(sourceDesc);
5187 status = startSource(swOutput, sourceDesc, &delayMs);
5188 if (status != NO_ERROR) {
5189 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5190 goto FailureSourceActive;
5191 }
5192 if (delayMs != 0) {
5193 usleep(delayMs * 1000);
5194 }
5195 return NO_ERROR;
5196
5197FailureSourceActive:
5198 swOutput->stop();
5199 releaseOutput(sourceDesc->portId());
5200FailureSourceAdded:
5201 sourceDesc->setSwOutput(nullptr);
5202FailurePatchAdded:
5203 releaseAudioPatchInternal(handle);
5204 return INVALID_OPERATION;
5205}
5206
5207status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5208 audio_patch_handle_t *handle,
5209 uid_t uid, uint32_t delayMs,
5210 const sp<SourceClientDescriptor>& sourceDesc)
5211{
5212 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 sp<AudioPatch> patchDesc;
5214 ssize_t index = mAudioPatches.indexOfKey(*handle);
5215
François Gaffieafd4cea2019-11-18 15:50:22 +01005216 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5217 patch->sources[0].role,
5218 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005219#if LOG_NDEBUG == 0
5220 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005221 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5222 patch->sinks[i].role,
5223 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005224 }
5225#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005226
5227 if (index >= 0) {
5228 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005229 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5230 __func__, mUidCached, patchDesc->getUid(), uid);
5231 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005232 return INVALID_OPERATION;
5233 }
5234 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005235 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 }
5237
5238 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005239 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005240 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005241 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005242 return BAD_VALUE;
5243 }
Eric Laurent84c70242014-06-23 08:46:27 -07005244 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5245 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005246 if (patchDesc != 0) {
5247 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005248 ALOGV("%s source id differs for patch current id %d new id %d",
5249 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005250 return BAD_VALUE;
5251 }
5252 }
Eric Laurent874c42872014-08-08 15:13:39 -07005253 DeviceVector devices;
5254 for (size_t i = 0; i < patch->num_sinks; i++) {
5255 // Only support mix to devices connection
5256 // TODO add support for mix to mix connection
5257 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005258 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005259 return INVALID_OPERATION;
5260 }
5261 sp<DeviceDescriptor> devDesc =
5262 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5263 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005264 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005265 return BAD_VALUE;
5266 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005267
jiabin66acc432024-02-06 00:57:36 +00005268 if (outputDesc->mProfile->getCompatibilityScore(
5269 DeviceVector(devDesc),
5270 patch->sources[0].sample_rate,
5271 nullptr, // updatedSamplingRate
5272 patch->sources[0].format,
5273 nullptr, // updatedFormat
5274 patch->sources[0].channel_mask,
5275 nullptr, // updatedChannelMask
5276 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005277 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005278 return INVALID_OPERATION;
5279 }
5280 devices.add(devDesc);
5281 }
5282 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 return INVALID_OPERATION;
5284 }
Eric Laurent874c42872014-08-08 15:13:39 -07005285
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005287 ALOGV("%s setting device %s on output %d",
5288 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305289 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005290 index = mAudioPatches.indexOfKey(*handle);
5291 if (index >= 0) {
5292 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005293 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 }
5295 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005296 patchDesc->setUid(uid);
5297 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005298 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005299 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 return INVALID_OPERATION;
5301 }
5302 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5303 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5304 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005305 // only one sink supported when connecting an input device to a mix
5306 if (patch->num_sinks > 1) {
5307 return INVALID_OPERATION;
5308 }
François Gaffie53615e22015-03-19 09:24:12 +01005309 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005310 if (inputDesc == NULL) {
5311 return BAD_VALUE;
5312 }
5313 if (patchDesc != 0) {
5314 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5315 return BAD_VALUE;
5316 }
5317 }
François Gaffie11d30102018-11-02 16:09:09 +01005318 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005319 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005320 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 return BAD_VALUE;
5322 }
5323
jiabin66acc432024-02-06 00:57:36 +00005324 if (inputDesc->mProfile->getCompatibilityScore(
5325 DeviceVector(device),
5326 patch->sinks[0].sample_rate,
5327 nullptr, /*updatedSampleRate*/
5328 patch->sinks[0].format,
5329 nullptr, /*updatedFormat*/
5330 patch->sinks[0].channel_mask,
5331 nullptr, /*updatedChannelMask*/
5332 // FIXME for the parameter type,
5333 // and the NONE
5334 (audio_output_flags_t)
5335 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005336 return INVALID_OPERATION;
5337 }
5338 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005339 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005340 device->toString().c_str(), inputDesc->mIoHandle);
5341 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005342 index = mAudioPatches.indexOfKey(*handle);
5343 if (index >= 0) {
5344 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005345 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 }
5347 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005348 patchDesc->setUid(uid);
5349 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005350 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005351 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005352 return INVALID_OPERATION;
5353 }
5354 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5355 // device to device connection
5356 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005357 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005358 return BAD_VALUE;
5359 }
5360 }
François Gaffie11d30102018-11-02 16:09:09 +01005361 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005362 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005363 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005364 return BAD_VALUE;
5365 }
Eric Laurent874c42872014-08-08 15:13:39 -07005366
Eric Laurent6a94d692014-05-20 11:18:06 -07005367 //update source and sink with our own data as the data passed in the patch may
5368 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005369 PatchBuilder patchBuilder;
5370 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005371
5372 // if first sink is to MSD, establish single MSD patch
5373 if (getMsdAudioOutDevices().contains(
5374 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5375 ALOGV("%s patching to MSD", __FUNCTION__);
5376 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5377 goto installPatch;
5378 }
5379
François Gaffieafd4cea2019-11-18 15:50:22 +01005380 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5381 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005382
Eric Laurent874c42872014-08-08 15:13:39 -07005383 for (size_t i = 0; i < patch->num_sinks; i++) {
5384 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005385 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005386 return INVALID_OPERATION;
5387 }
François Gaffie11d30102018-11-02 16:09:09 +01005388 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005389 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005390 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005391 return BAD_VALUE;
5392 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005393 audio_port_config sinkPortConfig = {};
5394 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5395 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005396
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005397 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5398 // volume management purpose (tracking activity)
5399 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5400 // in config XML to reach the sink so that is can be declared as available.
5401 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005402 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005403 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005404 // take care of dynamic routing for SwOutput selection,
5405 audio_attributes_t attributes = sourceDesc->attributes();
5406 audio_stream_type_t stream = sourceDesc->stream();
5407 audio_attributes_t resultAttr;
5408 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5409 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005410 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5411 config.channel_mask =
5412 (audio_channel_mask_get_representation(sourceMask)
5413 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5414 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005415 config.format = sourceDesc->config().format;
5416 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5417 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5418 bool isRequestedDeviceForExclusiveUse = false;
5419 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005420 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005421 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005422 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5423 &stream, sourceDesc->uid(), &config, &flags,
5424 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005425 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005426 if (output == AUDIO_IO_HANDLE_NONE) {
5427 ALOGV("%s no output for device %s",
5428 __FUNCTION__, sinkDevice->toString().c_str());
5429 return INVALID_OPERATION;
5430 }
5431 outputDesc = mOutputs.valueFor(output);
5432 if (outputDesc->isDuplicated()) {
5433 ALOGE("%s output is duplicated", __func__);
5434 return INVALID_OPERATION;
5435 }
François Gaffie7e39df22022-04-26 12:48:49 +02005436 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5437 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005438 } else {
5439 // Same for "raw patches" aka created from createAudioPatch API
5440 SortedVector<audio_io_handle_t> outputs =
5441 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5442 // if the sink device is reachable via an opened output stream, request to
5443 // go via this output stream by adding a second source to the patch
5444 // description
5445 output = selectOutput(outputs);
5446 if (output == AUDIO_IO_HANDLE_NONE) {
5447 ALOGE("%s no output available for internal patch sink", __func__);
5448 return INVALID_OPERATION;
5449 }
5450 outputDesc = mOutputs.valueFor(output);
5451 if (outputDesc->isDuplicated()) {
5452 ALOGV("%s output for device %s is duplicated",
5453 __func__, sinkDevice->toString().c_str());
5454 return INVALID_OPERATION;
5455 }
François Gaffie7e39df22022-04-26 12:48:49 +02005456 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005457 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005458 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005459 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005460 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005461 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005462 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5463 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005464 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5465 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005466 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005467 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005468 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005469 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005470 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005471 return INVALID_OPERATION;
5472 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005473 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005474 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005475 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005476 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005477 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005478 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005479 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005480 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5481 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005482 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005483 }
Eric Laurent83b88082014-06-20 18:31:16 -07005484 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005485 }
5486 // TODO: check from routing capabilities in config file and other conflicting patches
5487
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005488installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005489 status_t status = installPatch(
5490 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005491 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005492 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005493 return INVALID_OPERATION;
5494 }
5495 } else {
5496 return BAD_VALUE;
5497 }
5498 } else {
5499 return BAD_VALUE;
5500 }
5501 return NO_ERROR;
5502}
5503
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005504status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005505{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005506 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005507 ssize_t index = mAudioPatches.indexOfKey(handle);
5508
5509 if (index < 0) {
5510 return BAD_VALUE;
5511 }
5512 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005513 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5514 __func__, mUidCached, patchDesc->getUid(), uid);
5515 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005516 return INVALID_OPERATION;
5517 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005518 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5519 for (size_t i = 0; i < mAudioSources.size(); i++) {
5520 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5521 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5522 portId = sourceDesc->portId();
5523 break;
5524 }
5525 }
5526 return portId != AUDIO_PORT_HANDLE_NONE ?
5527 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005528}
Eric Laurent6a94d692014-05-20 11:18:06 -07005529
François Gaffieafd4cea2019-11-18 15:50:22 +01005530status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005531 uint32_t delayMs,
5532 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005533{
5534 ALOGV("%s patch %d", __func__, handle);
5535 if (mAudioPatches.indexOfKey(handle) < 0) {
5536 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5537 return BAD_VALUE;
5538 }
5539 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005540 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005541 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005542 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005543 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005544 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005545 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005546 return BAD_VALUE;
5547 }
5548
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305549 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005550 getNewOutputDevices(outputDesc, true /*fromCache*/),
5551 true,
5552 0,
5553 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005554 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5555 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005556 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005557 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005558 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005559 return BAD_VALUE;
5560 }
5561 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005562 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005563 true,
5564 NULL);
5565 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005566 status_t status =
5567 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5568 ALOGV("%s patch panel returned %d patchHandle %d",
5569 __func__, status, patchDesc->getAfHandle());
5570 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005571 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005572 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005573 // SW or HW Bridge
5574 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5575 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005576 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005577 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5578 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5579 outputDesc = sourceDesc->swOutput().promote();
5580 }
5581 if (outputDesc == nullptr) {
5582 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5583 // releaseOutput has already called closeOutput in case of direct output
5584 return NO_ERROR;
5585 }
François Gaffie7e39df22022-04-26 12:48:49 +02005586 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005587 // While using a HwBridge, force reconsidering device only if not reusing an existing
5588 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005589 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005590 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5591 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5592 // Reconsider device only for cases:
5593 // 1 / Active Output
5594 // 2 / Inactive Output previously hosting HwBridge
5595 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5596 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5597 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305598 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005599 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5600 outputDesc->devices(),
5601 force,
5602 0,
5603 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005604 } else {
5605 return BAD_VALUE;
5606 }
5607 } else {
5608 return BAD_VALUE;
5609 }
5610 return NO_ERROR;
5611}
5612
5613status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5614 struct audio_patch *patches,
5615 unsigned int *generation)
5616{
François Gaffie53615e22015-03-19 09:24:12 +01005617 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005618 return BAD_VALUE;
5619 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005620 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005621 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005622}
5623
Eric Laurente1715a42014-05-20 11:30:42 -07005624status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005625{
Eric Laurente1715a42014-05-20 11:30:42 -07005626 ALOGV("setAudioPortConfig()");
5627
5628 if (config == NULL) {
5629 return BAD_VALUE;
5630 }
5631 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5632 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005633 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5634 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005635 }
5636
Eric Laurenta121f902014-06-03 13:32:54 -07005637 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005638 if (config->type == AUDIO_PORT_TYPE_MIX) {
5639 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005640 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005641 if (outputDesc == NULL) {
5642 return BAD_VALUE;
5643 }
Eric Laurent84c70242014-06-23 08:46:27 -07005644 ALOG_ASSERT(!outputDesc->isDuplicated(),
5645 "setAudioPortConfig() called on duplicated output %d",
5646 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005647 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005648 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005649 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005650 if (inputDesc == NULL) {
5651 return BAD_VALUE;
5652 }
Eric Laurenta121f902014-06-03 13:32:54 -07005653 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005654 } else {
5655 return BAD_VALUE;
5656 }
5657 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5658 sp<DeviceDescriptor> deviceDesc;
5659 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5660 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5661 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5662 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5663 } else {
5664 return BAD_VALUE;
5665 }
5666 if (deviceDesc == NULL) {
5667 return BAD_VALUE;
5668 }
Eric Laurenta121f902014-06-03 13:32:54 -07005669 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005670 } else {
5671 return BAD_VALUE;
5672 }
5673
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005674 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005675 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5676 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005677 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005678 audioPortConfig->toAudioPortConfig(&newConfig, config);
5679 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005680 }
Eric Laurenta121f902014-06-03 13:32:54 -07005681 if (status != NO_ERROR) {
5682 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005683 }
Eric Laurente1715a42014-05-20 11:30:42 -07005684
5685 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005686}
5687
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005688void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5689{
Eric Laurentd60560a2015-04-10 11:31:20 -07005690 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005691 clearAudioPatches(uid);
5692 clearSessionRoutes(uid);
5693}
5694
Eric Laurent6a94d692014-05-20 11:18:06 -07005695void AudioPolicyManager::clearAudioPatches(uid_t uid)
5696{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005697 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005698 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005699 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005700 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005701 }
5702 }
5703}
5704
François Gaffiec005e562018-11-06 15:04:49 +01005705void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005706{
François Gaffiec005e562018-11-06 15:04:49 +01005707 // Take the first attributes following the product strategy as it is used to retrieve the routed
5708 // device. All attributes wihin a strategy follows the same "routing strategy"
5709 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5710 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005711 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005712 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005713 for (size_t j = 0; j < mOutputs.size(); j++) {
5714 if (mOutputs.keyAt(j) == ouptutToSkip) {
5715 continue;
5716 }
5717 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005718 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005719 continue;
5720 }
5721 // If the default device for this strategy is on another output mix,
5722 // invalidate all tracks in this strategy to force re connection.
5723 // Otherwise select new device on the output mix.
5724 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005725 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005726 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005727 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005728 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005729 // If the device is using preferred mixer attributes, the output need to reopen
5730 // with default configuration when the new selected devices are different from
5731 // current routing devices.
5732 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5733 continue;
5734 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305735 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005736 }
5737 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005738 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005739}
5740
5741void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5742{
5743 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005744 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005745 for (size_t i = 0; i < mOutputs.size(); i++) {
5746 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005747 for (const auto& client : outputDesc->getClientIterable()) {
5748 if (client->hasPreferredDevice() && client->uid() == uid) {
5749 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005750 auto clientStrategy = client->strategy();
5751 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5752 end(affectedStrategies)) {
5753 continue;
5754 }
5755 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005756 }
5757 }
5758 }
5759 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005760 for (const auto& strategy : affectedStrategies) {
5761 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005762 }
5763
5764 // remove input routes associated with this uid
5765 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005766 for (size_t i = 0; i < mInputs.size(); i++) {
5767 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005768 for (const auto& client : inputDesc->getClientIterable()) {
5769 if (client->hasPreferredDevice() && client->uid() == uid) {
5770 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5771 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005772 }
5773 }
5774 }
5775 // reroute inputs if necessary
5776 SortedVector<audio_io_handle_t> inputsToClose;
5777 for (size_t i = 0; i < mInputs.size(); i++) {
5778 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005779 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005780 inputsToClose.add(inputDesc->mIoHandle);
5781 }
5782 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005783 for (const auto& input : inputsToClose) {
5784 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005785 }
5786}
5787
Eric Laurentd60560a2015-04-10 11:31:20 -07005788void AudioPolicyManager::clearAudioSources(uid_t uid)
5789{
5790 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005791 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5792 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005793 stopAudioSource(mAudioSources.keyAt(i));
5794 }
5795 }
5796}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005797
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005798status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5799 audio_io_handle_t *ioHandle,
5800 audio_devices_t *device)
5801{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005802 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5803 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005804 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005805 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5806 if (deviceDesc == nullptr) {
5807 return INVALID_OPERATION;
5808 }
5809 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005810
François Gaffiedf372692015-03-19 10:43:27 +01005811 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005812}
5813
Eric Laurentd60560a2015-04-10 11:31:20 -07005814status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005815 const audio_attributes_t *attributes,
5816 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005817 uid_t uid) {
5818 return startAudioSourceInternal(source, attributes, portId, uid,
David Li48b6a832024-07-01 13:14:10 +00005819 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurent963dbcc2024-06-20 12:34:15 +00005820}
5821
5822status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5823 const audio_attributes_t *attributes,
5824 audio_port_handle_t *portId,
David Li48b6a832024-07-01 13:14:10 +00005825 uid_t uid, bool internal, bool isCallRx,
5826 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005827{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005828 ALOGV("%s", __FUNCTION__);
5829 *portId = AUDIO_PORT_HANDLE_NONE;
5830
5831 if (source == NULL || attributes == NULL || portId == NULL) {
5832 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5833 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005834 return BAD_VALUE;
5835 }
5836
Eric Laurentd60560a2015-04-10 11:31:20 -07005837 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5838 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005839 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5840 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005841 return INVALID_OPERATION;
5842 }
5843
François Gaffie11d30102018-11-02 16:09:09 +01005844 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005845 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005846 String8(source->ext.device.address),
5847 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005848 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005849 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005850 return BAD_VALUE;
5851 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005852
jiabin4ef93452019-09-10 14:29:54 -07005853 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005854
François Gaffieaaac0fd2018-11-22 17:56:39 +01005855 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005856 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005857 mEngine->getStreamTypeForAttributes(*attributes),
5858 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005859 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005860
David Li48b6a832024-07-01 13:14:10 +00005861 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005862 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005863 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005864 }
5865 return status;
5866}
5867
David Li48b6a832024-07-01 13:14:10 +00005868status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5869 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005870{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005871 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005872
5873 // make sure we only have one patch per source.
5874 disconnectAudioSource(sourceDesc);
5875
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005876 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005877 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5878 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5879 sourceDesc->srcDevice()->type(),
5880 String8(sourceDesc->srcDevice()->address().c_str()),
5881 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005882 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005883 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005884 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005885 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005886 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5887 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5888 return INVALID_OPERATION;
5889 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005890 PatchBuilder patchBuilder;
5891 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5892 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005893
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005894 return connectAudioSourceToSink(
David Li48b6a832024-07-01 13:14:10 +00005895 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005896}
5897
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005898status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005899{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005900 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5901 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005902 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005903 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005904 return BAD_VALUE;
5905 }
5906 status_t status = disconnectAudioSource(sourceDesc);
5907
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005908 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005909 return status;
5910}
5911
Andy Hung2ddee192015-12-18 17:34:44 -08005912status_t AudioPolicyManager::setMasterMono(bool mono)
5913{
5914 if (mMasterMono == mono) {
5915 return NO_ERROR;
5916 }
5917 mMasterMono = mono;
5918 // if enabling mono we close all offloaded devices, which will invalidate the
5919 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5920 // for recreating the new AudioTrack as non-offloaded PCM.
5921 //
5922 // If disabling mono, we leave all tracks as is: we don't know which clients
5923 // and tracks are able to be recreated as offloaded. The next "song" should
5924 // play back offloaded.
5925 if (mMasterMono) {
5926 Vector<audio_io_handle_t> offloaded;
5927 for (size_t i = 0; i < mOutputs.size(); ++i) {
5928 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5929 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5930 offloaded.push(desc->mIoHandle);
5931 }
5932 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005933 for (const auto& handle : offloaded) {
5934 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005935 }
5936 }
5937 // update master mono for all remaining outputs
5938 for (size_t i = 0; i < mOutputs.size(); ++i) {
5939 updateMono(mOutputs.keyAt(i));
5940 }
5941 return NO_ERROR;
5942}
5943
5944status_t AudioPolicyManager::getMasterMono(bool *mono)
5945{
5946 *mono = mMasterMono;
5947 return NO_ERROR;
5948}
5949
Eric Laurentac9cef52017-06-09 15:46:26 -07005950float AudioPolicyManager::getStreamVolumeDB(
5951 audio_stream_type_t stream, int index, audio_devices_t device)
5952{
jiabin9a3361e2019-10-01 09:38:30 -07005953 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005954}
5955
jiabin81772902018-04-02 17:52:27 -07005956status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5957 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005958 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005959{
Kriti Dang6537def2021-03-02 13:46:59 +01005960 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5961 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005962 return BAD_VALUE;
5963 }
Kriti Dang6537def2021-03-02 13:46:59 +01005964 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5965 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005966
5967 size_t formatsWritten = 0;
5968 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005969
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005970 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005971 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5972 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005973 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005974 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005975 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005976 bool formatEnabled = true;
5977 switch (forceUse) {
5978 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005979 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005980 break;
5981 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5982 formatEnabled = false;
5983 break;
5984 default: // AUTO or ALWAYS => true
5985 break;
jiabin81772902018-04-02 17:52:27 -07005986 }
5987 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5988 }
jiabin81772902018-04-02 17:52:27 -07005989 }
5990 return NO_ERROR;
5991}
5992
Kriti Dang6537def2021-03-02 13:46:59 +01005993status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5994 audio_format_t *surroundFormats) {
5995 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5996 return BAD_VALUE;
5997 }
5998 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5999 __func__, *numSurroundFormats, surroundFormats);
6000
6001 size_t formatsWritten = 0;
6002 size_t formatsMax = *numSurroundFormats;
6003 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6004
6005 // Return formats from all device profiles that have already been resolved by
6006 // checkOutputsForDevice().
6007 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6008 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6009 audio_devices_t deviceType = device->type();
6010 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6011 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006012 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6013 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006014 continue;
6015 }
6016 // Formats reported by sink devices
6017 std::unordered_set<audio_format_t> formatset;
6018 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6019 formatset.insert(it->second.begin(), it->second.end());
6020 }
6021
6022 // Formats hard-coded in the in policy configuration file (if any).
6023 FormatVector encodedFormats = device->encodedFormats();
6024 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6025 // Filter the formats which are supported by the vendor hardware.
6026 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006027 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006028 formats.insert(*it);
6029 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006030 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006031 if (pair.second.count(*it) != 0) {
6032 formats.insert(pair.first);
6033 break;
6034 }
6035 }
6036 }
6037 }
6038 }
6039 *numSurroundFormats = formats.size();
6040 for (const auto& format: formats) {
6041 if (formatsWritten < formatsMax) {
6042 surroundFormats[formatsWritten++] = format;
6043 }
6044 }
6045 return NO_ERROR;
6046}
6047
jiabin81772902018-04-02 17:52:27 -07006048status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6049{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006050 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006051 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6052 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006053 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006054 return BAD_VALUE;
6055 }
6056
Mikhail Naganov100f0122018-11-29 11:22:16 -08006057 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6058 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006059 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006060 return INVALID_OPERATION;
6061 }
6062
Mikhail Naganov100f0122018-11-29 11:22:16 -08006063 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006064 return NO_ERROR;
6065 }
6066
Mikhail Naganov100f0122018-11-29 11:22:16 -08006067 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006068 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006069 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006070 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006071 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006072 }
6073 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006074 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006075 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006076 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006077 }
6078 }
6079
6080 sp<SwAudioOutputDescriptor> outputDesc;
6081 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006082 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6083 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006084 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6085 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006086 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006087 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006088 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006089 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6090 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006091 name.c_str(),
6092 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006093 if (status != NO_ERROR) {
6094 continue;
6095 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006096 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006097 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6098 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006099 name.c_str(),
6100 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006101 profileUpdated |= (status == NO_ERROR);
6102 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006103 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006104 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006105 AUDIO_DEVICE_IN_HDMI);
6106 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6107 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006108 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006109 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006110 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6111 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6112 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006113 name.c_str(),
6114 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006115 if (status != NO_ERROR) {
6116 continue;
6117 }
6118 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6119 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6120 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006121 name.c_str(),
6122 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006123 profileUpdated |= (status == NO_ERROR);
6124 }
6125
jiabin81772902018-04-02 17:52:27 -07006126 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006127 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006128 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006129 }
6130
6131 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6132}
6133
Eric Laurent5ada82e2019-08-29 17:53:54 -07006134void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006135{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006136 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006137 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006138 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006139 }
6140}
6141
jiabin6012f912018-11-02 17:06:30 -07006142bool AudioPolicyManager::isHapticPlaybackSupported()
6143{
6144 for (const auto& hwModule : mHwModules) {
6145 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6146 for (const auto &outProfile : outputProfiles) {
6147 struct audio_port audioPort;
6148 outProfile->toAudioPort(&audioPort);
6149 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6150 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6151 return true;
6152 }
6153 }
6154 }
6155 }
6156 return false;
6157}
6158
Carter Hsu325a8eb2022-01-19 19:56:51 +08006159bool AudioPolicyManager::isUltrasoundSupported()
6160{
6161 bool hasUltrasoundOutput = false;
6162 bool hasUltrasoundInput = false;
6163 for (const auto& hwModule : mHwModules) {
6164 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6165 if (!hasUltrasoundOutput) {
6166 for (const auto &outProfile : outputProfiles) {
6167 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6168 hasUltrasoundOutput = true;
6169 break;
6170 }
6171 }
6172 }
6173
6174 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6175 if (!hasUltrasoundInput) {
6176 for (const auto &inputProfile : inputProfiles) {
6177 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6178 hasUltrasoundInput = true;
6179 break;
6180 }
6181 }
6182 }
6183
6184 if (hasUltrasoundOutput && hasUltrasoundInput)
6185 return true;
6186 }
6187 return false;
6188}
6189
Atneya Nair698f5ef2022-12-15 16:15:09 -08006190bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6191{
6192 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6193 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6194 for (const auto& hwModule : mHwModules) {
6195 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6196 for (const auto &inputProfile : inputProfiles) {
6197 if ((inputProfile->getFlags() & mask) == mask) {
6198 return true;
6199 }
6200 }
6201 }
6202 return false;
6203}
6204
Eric Laurent8340e672019-11-06 11:01:08 -08006205bool AudioPolicyManager::isCallScreenModeSupported()
6206{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006207 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006208}
6209
6210
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006211status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006212{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006213 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006214 if (!sourceDesc->isConnected()) {
6215 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6216 return NO_ERROR;
6217 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006218 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6219 if (swOutput != 0) {
6220 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006221 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006222 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006223 }
jiabinbce0c1d2020-10-05 11:20:18 -07006224 if (releaseOutput(sourceDesc->portId())) {
6225 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6226 // no need to release audio patch here but just return NO_ERROR.
6227 return NO_ERROR;
6228 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006229 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006230 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006231 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006232 // close Hwoutput and remove from mHwOutputs
6233 } else {
6234 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6235 }
6236 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006237 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006238 sourceDesc->disconnect();
6239 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006240}
6241
François Gaffiec005e562018-11-06 15:04:49 +01006242sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6243 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006244{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006245 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006246 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006247 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006248 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006249 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6250 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006251 source = sourceDesc;
6252 break;
6253 }
6254 }
6255 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006256}
6257
Eric Laurentb4f42a92022-01-17 17:37:31 +01006258bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006259 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006260 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006261{
6262 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6263 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006264 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006265 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006266 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6267 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6268 return false;
6269 }
6270 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6271 return false;
6272 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006273 }
6274
Eric Laurentd332bc82023-08-04 11:45:23 +02006275 // The caller can have the audio config criteria ignored by either passing a null ptr or
6276 // the AUDIO_CONFIG_INITIALIZER value.
6277 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006278 // some positional channel masks and PCM format and for stereo if low latency performance
6279 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006280
6281 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006282 static const bool stereo_spatialization_enabled =
6283 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006284 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006285 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006286 ? audio_channel_mask_contains_stereo(config->channel_mask)
6287 : audio_is_channel_mask_spatialized(config->channel_mask);
6288 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006289 return false;
6290 }
6291 if (!audio_is_linear_pcm(config->format)) {
6292 return false;
6293 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006294 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6295 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6296 return false;
6297 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006298 }
6299
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006300 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006301 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006302 if (profile == nullptr) {
6303 return false;
6304 }
6305
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006306 return true;
6307}
6308
Shunkai Yao57b93392024-04-26 04:12:21 +00006309// The Spatializer output is compatible with Haptic use cases if:
6310// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6311// with client if client haptic channel bits were set, or
6312// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6313// including the haptic bits or creating the HapticGenerator effect for same session.
6314bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6315 const audio_config_t* config, audio_session_t sessionId) const {
6316 const auto clientHapticChannel =
6317 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6318 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6319 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6320
6321 if (threadOutputHapticChannel) {
6322 // check format and sampleRate match if client haptic channel mask exist
6323 if (clientHapticChannel) {
6324 return mSpatializerOutput->getFormat() == config->format &&
6325 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6326 }
6327 return true;
6328 } else {
6329 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6330 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6331 // HapticGenerator effect for this session) are not supported.
6332 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006333 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006334 }
6335}
6336
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006337void AudioPolicyManager::checkVirtualizerClientRoutes() {
6338 std::set<audio_stream_type_t> streamsToInvalidate;
6339 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006340 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6341 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006342 audio_attributes_t attr = client->attributes();
6343 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6344 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6345 audio_config_base_t clientConfig = client->config();
6346 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006347 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006348 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006349 streamsToInvalidate.insert(client->stream());
6350 }
6351 }
6352 }
6353
jiabinc44b3462022-12-08 12:52:31 -08006354 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006355}
6356
Eric Laurente191d1b2022-04-15 11:59:25 +02006357
6358bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6359 const sp<SwAudioOutputDescriptor>& outputDesc) {
6360 if (outputDesc->isDuplicated()) {
6361 return false;
6362 }
6363 DeviceVector devices = outputDesc->supportedDevices();
6364 for (size_t i = 0; i < mOutputs.size(); i++) {
6365 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6366 if (desc == outputDesc || desc->isDuplicated()) {
6367 continue;
6368 }
6369 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6370 if (!sharedDevices.isEmpty()
6371 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6372 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6373 return false;
6374 }
6375 }
6376 return true;
6377}
6378
6379
Eric Laurentfa0f6742021-08-17 18:39:44 +02006380status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006381 const audio_attributes_t *attr,
6382 audio_io_handle_t *output) {
6383 *output = AUDIO_IO_HANDLE_NONE;
6384
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006385 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6386 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6387 audio_config_t *configPtr = nullptr;
6388 audio_config_t config;
6389 if (mixerConfig != nullptr) {
6390 config = audio_config_initializer(mixerConfig);
6391 configPtr = &config;
6392 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006393 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006394 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006395 return BAD_VALUE;
6396 }
6397
6398 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006399 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006400 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006401 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006402 return BAD_VALUE;
6403 }
6404
Eric Laurente191d1b2022-04-15 11:59:25 +02006405 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006406 for (size_t i = 0; i < mOutputs.size(); i++) {
6407 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006408 if (!desc->isDuplicated()
6409 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6410 spatializerOutputs.push_back(desc);
6411 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006412 }
6413 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006414 mSpatializerOutput.clear();
6415 bool outputsChanged = false;
6416 for (const auto& desc : spatializerOutputs) {
6417 if (desc->mProfile == profile
6418 && (configPtr == nullptr
6419 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6420 mSpatializerOutput = desc;
6421 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6422 } else {
6423 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6424 " and devices %s", __func__, desc->mIoHandle,
6425 configPtr != nullptr ? configPtr->channel_mask : 0,
6426 devices.toString().c_str());
6427 closeOutput(desc->mIoHandle);
6428 outputsChanged = true;
6429 }
Eric Laurent39095982021-08-24 18:29:27 +02006430 }
6431
Eric Laurente191d1b2022-04-15 11:59:25 +02006432 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006433 sp<SwAudioOutputDescriptor> desc =
6434 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006435 if (desc != nullptr) {
6436 mSpatializerOutput = desc;
6437 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006438 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006439 }
6440
6441 checkVirtualizerClientRoutes();
6442
Eric Laurente191d1b2022-04-15 11:59:25 +02006443 if (outputsChanged) {
6444 mPreviousOutputs = mOutputs;
6445 mpClientInterface->onAudioPortListUpdate();
6446 }
6447
6448 if (mSpatializerOutput == nullptr) {
6449 ALOGV("%s could not open spatializer output with requested config", __func__);
6450 return BAD_VALUE;
6451 }
Eric Laurent39095982021-08-24 18:29:27 +02006452 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006453 ALOGV("%s returning new spatializer output %d", __func__, *output);
6454 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006455}
6456
Eric Laurentfa0f6742021-08-17 18:39:44 +02006457status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6458 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006459 return INVALID_OPERATION;
6460 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006461 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006462 return BAD_VALUE;
6463 }
Eric Laurent39095982021-08-24 18:29:27 +02006464
Eric Laurente191d1b2022-04-15 11:59:25 +02006465 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6466 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6467 closeOutput(mSpatializerOutput->mIoHandle);
6468 //from now on mSpatializerOutput is null
6469 checkVirtualizerClientRoutes();
6470 }
Eric Laurent39095982021-08-24 18:29:27 +02006471
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006472 return NO_ERROR;
6473}
6474
Eric Laurente552edb2014-03-10 17:42:56 -07006475// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006476// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006477// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006478uint32_t AudioPolicyManager::nextAudioPortGeneration()
6479{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006480 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006481}
6482
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006483AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006484 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006485 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006486 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006487 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006488 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006489 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006490 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006491 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006492 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006493 mAudioPortGeneration(1),
6494 mBeaconMuteRefCount(0),
6495 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006496 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006497 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006498 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006499 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006500{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006501}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006502
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006503status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006504 if (mEngine == nullptr) {
6505 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006506 }
6507 mEngine->setObserver(this);
6508 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006509 if (status != NO_ERROR) {
6510 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6511 return status;
6512 }
François Gaffie2110e042015-03-24 08:41:51 +01006513
jiabin29230182023-04-04 21:02:36 +00006514 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6515 // at the end of this function.
6516 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006517 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6518 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6519
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006520 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006521 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006522 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006523
Eric Laurent3a4311c2014-03-17 12:00:47 -07006524 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006525 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6526 defaultOutputDevice == nullptr ||
6527 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6528 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6529 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006530 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006531 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006532 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006533
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006534 // Silence ALOGV statements
6535 property_set("log.tag." LOG_TAG, "D");
6536
Eric Laurente552edb2014-03-10 17:42:56 -07006537 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006538 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006539}
6540
Eric Laurente0720872014-03-11 09:30:41 -07006541AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006542{
Eric Laurente552edb2014-03-10 17:42:56 -07006543 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006544 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006545 }
6546 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006547 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006548 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006549 mAvailableOutputDevices.clear();
6550 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006551 mOutputs.clear();
6552 mInputs.clear();
6553 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006554 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006555 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006556}
6557
Eric Laurente0720872014-03-11 09:30:41 -07006558status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006559{
Eric Laurent87ffa392015-05-22 10:32:38 -07006560 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006561}
6562
Eric Laurente552edb2014-03-10 17:42:56 -07006563// ---
6564
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006565void AudioPolicyManager::onNewAudioModulesAvailable()
6566{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006567 DeviceVector newDevices;
6568 onNewAudioModulesAvailableInt(&newDevices);
6569 if (!newDevices.empty()) {
6570 nextAudioPortGeneration();
6571 mpClientInterface->onAudioPortListUpdate();
6572 }
6573}
6574
6575void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6576{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006577 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006578 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6579 continue;
6580 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006581 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006582 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6583 handle != AUDIO_MODULE_HANDLE_NONE) {
6584 hwModule->setHandle(handle);
6585 } else {
6586 ALOGW("could not load HW module %s", hwModule->getName());
6587 continue;
6588 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006589 }
6590 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006591 // open all output streams needed to access attached devices.
6592 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006593 // This also validates mAvailableOutputDevices list
6594 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6595 if (!outProfile->canOpenNewIo()) {
6596 ALOGE("Invalid Output profile max open count %u for profile %s",
6597 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6598 continue;
6599 }
6600 if (!outProfile->hasSupportedDevices()) {
6601 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6602 continue;
6603 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006604 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6605 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006606 mTtsOutputAvailable = true;
6607 }
6608
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006609 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006610 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006611 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006612 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6613 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006614 } else {
6615 // choose first device present in profile's SupportedDevices also part of
6616 // mAvailableOutputDevices.
6617 if (availProfileDevices.isEmpty()) {
6618 continue;
6619 }
6620 supportedDevice = availProfileDevices.itemAt(0);
6621 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006622 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006623 continue;
6624 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306625
6626 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6627 && availProfileDevices.areAllDevicesAttached()) {
6628 ALOGV("%s skip opening output for mmap profile %s", __func__,
6629 outProfile->getTagName().c_str());
6630 continue;
6631 }
6632
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006633 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6634 mpClientInterface);
6635 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006636 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006637 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006638 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6639 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006640 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006641 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006642 if (status != NO_ERROR) {
6643 ALOGW("Cannot open output stream for devices %s on hw module %s",
6644 supportedDevice->toString().c_str(), hwModule->getName());
6645 continue;
6646 }
6647 for (const auto &device : availProfileDevices) {
6648 // give a valid ID to an attached device once confirmed it is reachable
6649 if (!device->isAttached()) {
6650 device->attach(hwModule);
6651 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006652 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006653 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006654 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6655 }
6656 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006657 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006658 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6659 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006660 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006661 }
Eric Laurent39095982021-08-24 18:29:27 +02006662 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006663 outputDesc->close();
6664 } else {
6665 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306666 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006667 DeviceVector(supportedDevice),
6668 true,
6669 0,
6670 NULL);
6671 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006672 }
6673 // open input streams needed to access attached devices to validate
6674 // mAvailableInputDevices list
6675 for (const auto& inProfile : hwModule->getInputProfiles()) {
6676 if (!inProfile->canOpenNewIo()) {
6677 ALOGE("Invalid Input profile max open count %u for profile %s",
6678 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6679 continue;
6680 }
6681 if (!inProfile->hasSupportedDevices()) {
6682 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6683 continue;
6684 }
6685 // chose first device present in profile's SupportedDevices also part of
6686 // available input devices
6687 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006688 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006689 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006690 ALOGV("%s: Input device list is empty! for profile %s",
6691 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006692 continue;
6693 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306694
6695 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6696 && availProfileDevices.areAllDevicesAttached()) {
6697 ALOGV("%s skip opening input for mmap profile %s", __func__,
6698 inProfile->getTagName().c_str());
6699 continue;
6700 }
6701
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006702 sp<AudioInputDescriptor> inputDesc =
6703 new AudioInputDescriptor(inProfile, mpClientInterface);
6704
6705 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6706 status_t status = inputDesc->open(nullptr,
6707 availProfileDevices.itemAt(0),
6708 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006709 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006710 &input);
6711 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306712 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6713 __func__, availProfileDevices.toString().c_str(),
6714 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006715 continue;
6716 }
6717 for (const auto &device : availProfileDevices) {
6718 // give a valid ID to an attached device once confirmed it is reachable
6719 if (!device->isAttached()) {
6720 device->attach(hwModule);
6721 device->importAudioPortAndPickAudioProfile(inProfile, true);
6722 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006723 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006724 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6725 }
6726 }
6727 inputDesc->close();
6728 }
6729 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006730
6731 // Check if spatializer outputs can be closed until used.
6732 // mOutputs vector never contains duplicated outputs at this point.
6733 std::vector<audio_io_handle_t> outputsClosed;
6734 for (size_t i = 0; i < mOutputs.size(); i++) {
6735 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6736 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6737 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6738 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006739 nextAudioPortGeneration();
6740 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6741 if (index >= 0) {
6742 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6743 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6744 patchDesc->getAfHandle(), 0);
6745 mAudioPatches.removeItemsAt(index);
6746 mpClientInterface->onAudioPatchListUpdate();
6747 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006748 desc->close();
6749 }
6750 }
6751 for (auto output : outputsClosed) {
6752 removeOutput(output);
6753 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006754}
6755
Eric Laurent98e38192018-02-15 18:31:53 -08006756void AudioPolicyManager::addOutput(audio_io_handle_t output,
6757 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006758{
Eric Laurent1c333e22014-05-20 10:48:17 -07006759 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006760 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006761 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006762 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006763 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006764}
6765
François Gaffie53615e22015-03-19 09:24:12 +01006766void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6767{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006768 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6769 ALOGV("%s: removing primary output", __func__);
6770 mPrimaryOutput = nullptr;
6771 }
François Gaffie53615e22015-03-19 09:24:12 +01006772 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006773 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006774}
6775
Eric Laurent98e38192018-02-15 18:31:53 -08006776void AudioPolicyManager::addInput(audio_io_handle_t input,
6777 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006778{
Eric Laurent1c333e22014-05-20 10:48:17 -07006779 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006780 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006781}
Eric Laurente552edb2014-03-10 17:42:56 -07006782
François Gaffie11d30102018-11-02 16:09:09 +01006783status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006784 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006785 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006786{
François Gaffie11d30102018-11-02 16:09:09 +01006787 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006788 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006789 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006790
François Gaffie11d30102018-11-02 16:09:09 +01006791 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006792 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006793 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006794 }
Eric Laurente552edb2014-03-10 17:42:56 -07006795
Eric Laurent3b73df72014-03-11 09:06:29 -07006796 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006797 // first call getAudioPort to get the supported attributes from the HAL
6798 struct audio_port_v7 port = {};
6799 device->toAudioPort(&port);
6800 status_t status = mpClientInterface->getAudioPort(&port);
6801 if (status == NO_ERROR) {
6802 device->importAudioPort(port);
6803 }
6804
6805 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006806 for (size_t i = 0; i < mOutputs.size(); i++) {
6807 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006808 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006809 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006810 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6811 mOutputs.keyAt(i), device->toString().c_str());
6812 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006813 }
6814 }
6815 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006816 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006817 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006818 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6819 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006820 if (profile->supportsDevice(device)) {
6821 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306822 ALOGV("%s(): adding profile %s from module %s",
6823 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006824 }
6825 }
6826 }
6827
Eric Laurent7b279bb2015-12-14 10:18:23 -08006828 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006829
Eric Laurente552edb2014-03-10 17:42:56 -07006830 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006831 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006832 return BAD_VALUE;
6833 }
6834
6835 // open outputs for matching profiles if needed. Direct outputs are also opened to
6836 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6837 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006838 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006839
6840 // nothing to do if one output is already opened for this profile
6841 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006842 for (j = 0; j < outputs.size(); j++) {
6843 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006844 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006845 // matching profile: save the sample rates, format and channel masks supported
6846 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006847 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006848 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006849 }
Eric Laurente552edb2014-03-10 17:42:56 -07006850 break;
6851 }
6852 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006853 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006854 continue;
6855 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306856 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6857 ALOGV("%s skip opening output for mmap profile %s",
6858 __func__, profile->getTagName().c_str());
6859 continue;
6860 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006861 if (!profile->canOpenNewIo()) {
6862 ALOGW("Max Output number %u already opened for this profile %s",
6863 profile->maxOpenCount, profile->getTagName().c_str());
6864 continue;
6865 }
6866
Eric Laurent83efe1c2017-07-09 16:51:08 -07006867 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006868 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006869 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6870 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006871 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006872 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006873 profiles.removeAt(profile_index);
6874 profile_index--;
6875 } else {
6876 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006877 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006878 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006879 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6880 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006881 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006882 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006883
François Gaffie11d30102018-11-02 16:09:09 +01006884 if (device_distinguishes_on_address(deviceType)) {
6885 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6886 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306887 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6888 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006889 }
Eric Laurente552edb2014-03-10 17:42:56 -07006890 ALOGV("checkOutputsForDevice(): adding output %d", output);
6891 }
6892 }
6893
6894 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006895 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006896 return BAD_VALUE;
6897 }
Eric Laurentd4692962014-05-05 18:13:44 -07006898 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006899 // check if one opened output is not needed any more after disconnecting one device
6900 for (size_t i = 0; i < mOutputs.size(); i++) {
6901 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006902 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006903 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006904 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006905 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006906 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006907 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006908 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6909 mOutputs.keyAt(i));
6910 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006911 }
Eric Laurente552edb2014-03-10 17:42:56 -07006912 }
6913 }
Eric Laurentd4692962014-05-05 18:13:44 -07006914 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006915 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006916 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6917 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006918 if (!profile->supportsDevice(device)) {
6919 continue;
6920 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306921 ALOGV("%s(): clearing direct output profile %s on module %s",
6922 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006923 profile->clearAudioProfiles();
6924 if (!profile->hasDynamicAudioProfile()) {
6925 continue;
6926 }
6927 // When a device is disconnected, if there is an IOProfile that contains dynamic
6928 // profiles and supports the disconnected device, call getAudioPort to repopulate
6929 // the capabilities of the devices that is supported by the IOProfile.
6930 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6931 if (supportedDevice == device ||
6932 !mAvailableOutputDevices.contains(supportedDevice)) {
6933 continue;
6934 }
6935 struct audio_port_v7 port;
6936 supportedDevice->toAudioPort(&port);
6937 status_t status = mpClientInterface->getAudioPort(&port);
6938 if (status == NO_ERROR) {
6939 supportedDevice->importAudioPort(port);
6940 }
Eric Laurente552edb2014-03-10 17:42:56 -07006941 }
6942 }
6943 }
6944 }
6945 return NO_ERROR;
6946}
6947
François Gaffie11d30102018-11-02 16:09:09 +01006948status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006949 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006950{
François Gaffie11d30102018-11-02 16:09:09 +01006951 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006952 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006953 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006954 }
6955
Eric Laurentd4692962014-05-05 18:13:44 -07006956 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006957 sp<AudioInputDescriptor> desc;
6958
jiabinbf5f4262023-04-12 21:48:34 +00006959 // first call getAudioPort to get the supported attributes from the HAL
6960 struct audio_port_v7 port = {};
6961 device->toAudioPort(&port);
6962 status_t status = mpClientInterface->getAudioPort(&port);
6963 if (status == NO_ERROR) {
6964 device->importAudioPort(port);
6965 }
6966
Eric Laurent0dd51852019-04-19 18:18:58 -07006967 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006968 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006969 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006970 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006971 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006972 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006973 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006974
François Gaffie11d30102018-11-02 16:09:09 +01006975 if (profile->supportsDevice(device)) {
6976 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306977 ALOGV("%s : adding profile %s from module %s", __func__,
6978 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006979 }
6980 }
6981 }
6982
Eric Laurent0dd51852019-04-19 18:18:58 -07006983 if (profiles.isEmpty()) {
6984 ALOGW("%s: No input profile available for device %s",
6985 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006986 return BAD_VALUE;
6987 }
6988
6989 // open inputs for matching profiles if needed. Direct inputs are also opened to
6990 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6991 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6992
Eric Laurent1c333e22014-05-20 10:48:17 -07006993 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006994
Eric Laurentd4692962014-05-05 18:13:44 -07006995 // nothing to do if one input is already opened for this profile
6996 size_t input_index;
6997 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6998 desc = mInputs.valueAt(input_index);
6999 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007000 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007001 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007002 }
Eric Laurentd4692962014-05-05 18:13:44 -07007003 break;
7004 }
7005 }
7006 if (input_index != mInputs.size()) {
7007 continue;
7008 }
7009
Jaideep Sharma44824a22024-06-18 16:32:34 +05307010 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7011 ALOGV("%s skip opening input for mmap profile %s",
7012 __func__, profile->getTagName().c_str());
7013 continue;
7014 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007015 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307016 ALOGW("%s Max Input number %u already opened for this profile %s",
7017 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007018 continue;
7019 }
7020
Eric Laurentfe231122017-11-17 17:48:06 -08007021 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007022 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307023 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00007024 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7025 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007026
Eric Laurentcf2c0212014-07-25 16:20:43 -07007027 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007028 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007029 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007030 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007031 mpClientInterface->setParameters(input, String8(param));
7032 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007033 }
jiabin12537fc2023-10-12 17:56:08 +00007034 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007035 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307036 ALOGW("%s direct input missing param for profile %s", __func__,
7037 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007038 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007039 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007040 }
7041
Eric Laurent0dd51852019-04-19 18:18:58 -07007042 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007043 addInput(input, desc);
7044 }
7045 } // endif input != 0
7046
Eric Laurentcf2c0212014-07-25 16:20:43 -07007047 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307048 ALOGW("%s could not open input for device %s on profile %s", __func__,
7049 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007050 profiles.removeAt(profile_index);
7051 profile_index--;
7052 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007053 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007054 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007055 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307056 ALOGV("%s: adding input %d for profile %s", __func__,
7057 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007058
7059 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307060 ALOGV("%s: closing input %d for profile %s", __func__,
7061 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007062 closeInput(input);
7063 }
Eric Laurentd4692962014-05-05 18:13:44 -07007064 }
7065 } // end scan profiles
7066
7067 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007068 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007069 return BAD_VALUE;
7070 }
7071 } else {
7072 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007073 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007074 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007075 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007076 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007077 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007078 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007079 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307080 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7081 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007082 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007083 }
7084 }
7085 }
7086 } // end disconnect
7087
7088 return NO_ERROR;
7089}
7090
7091
Eric Laurente0720872014-03-11 09:30:41 -07007092void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007093{
7094 ALOGV("closeOutput(%d)", output);
7095
François Gaffie1c878552018-11-22 16:53:21 +01007096 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7097 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007098 ALOGW("closeOutput() unknown output %d", output);
7099 return;
7100 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007101 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007102 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007103
Eric Laurente552edb2014-03-10 17:42:56 -07007104 // look for duplicated outputs connected to the output being removed.
7105 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007106 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7107 if (dupOutput->isDuplicated() &&
7108 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7109 sp<SwAudioOutputDescriptor> remainingOutput =
7110 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007111 // As all active tracks on duplicated output will be deleted,
7112 // and as they were also referenced on the other output, the reference
7113 // count for their stream type must be adjusted accordingly on
7114 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007115 const bool wasActive = remainingOutput->isActive();
7116 // Note: no-op on the closing output where all clients has already been set inactive
7117 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007118 // stop() will be a no op if the output is still active but is needed in case all
7119 // active streams refcounts where cleared above
7120 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007121 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007122 }
Eric Laurente552edb2014-03-10 17:42:56 -07007123 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7124 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7125
7126 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007127 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007128 }
7129 }
7130
Eric Laurent05b90f82014-08-27 15:32:29 -07007131 nextAudioPortGeneration();
7132
François Gaffie1c878552018-11-22 16:53:21 +01007133 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007134 if (index >= 0) {
7135 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007136 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7137 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007138 mAudioPatches.removeItemsAt(index);
7139 mpClientInterface->onAudioPatchListUpdate();
7140 }
7141
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007142 if (closingOutputWasActive) {
7143 closingOutput->stop();
7144 }
François Gaffie1c878552018-11-22 16:53:21 +01007145 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007146 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007147 for (const auto device : closingOutput->devices()) {
7148 device->setPreferredConfig(nullptr);
7149 }
7150 }
Eric Laurente552edb2014-03-10 17:42:56 -07007151
François Gaffie53615e22015-03-19 09:24:12 +01007152 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007153 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007154 if (closingOutput == mSpatializerOutput) {
7155 mSpatializerOutput.clear();
7156 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007157
7158 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7159 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007160 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007161 bool directOutputOpen = false;
7162 for (size_t i = 0; i < mOutputs.size(); i++) {
7163 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7164 directOutputOpen = true;
7165 break;
7166 }
7167 }
7168 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007169 ALOGV("no direct outputs open, reset MSD patches");
7170 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7171 // how output devices for patching are resolved. Avoid by caching and reusing the
7172 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7173 // devices to patch to. This may be complicated by the fact that devices may become
7174 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007175 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007176 }
7177 }
jiabin220eea12024-05-17 17:55:20 +00007178
7179 if (closingOutput->mPreferredAttrInfo != nullptr) {
7180 closingOutput->mPreferredAttrInfo->resetActiveClient();
7181 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007182}
7183
7184void AudioPolicyManager::closeInput(audio_io_handle_t input)
7185{
7186 ALOGV("closeInput(%d)", input);
7187
7188 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7189 if (inputDesc == NULL) {
7190 ALOGW("closeInput() unknown input %d", input);
7191 return;
7192 }
7193
Eric Laurent6a94d692014-05-20 11:18:06 -07007194 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007195
François Gaffie11d30102018-11-02 16:09:09 +01007196 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007197 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007198 if (index >= 0) {
7199 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007200 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7201 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007202 mAudioPatches.removeItemsAt(index);
7203 mpClientInterface->onAudioPatchListUpdate();
7204 }
7205
François Gaffie6ebbce02023-07-19 13:27:53 +02007206 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007207 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007208 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007209
François Gaffie11d30102018-11-02 16:09:09 +01007210 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7211 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007212 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007213 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007214 }
Eric Laurente552edb2014-03-10 17:42:56 -07007215}
7216
François Gaffie11d30102018-11-02 16:09:09 +01007217SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7218 const DeviceVector &devices,
7219 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007220{
7221 SortedVector<audio_io_handle_t> outputs;
7222
François Gaffie11d30102018-11-02 16:09:09 +01007223 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007224 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007225 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007226 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007227 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007228 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007229 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007230 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007231 outputs.add(openOutputs.keyAt(i));
7232 }
7233 }
7234 return outputs;
7235}
7236
Mikhail Naganov37977152018-07-11 15:54:44 -07007237void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7238{
7239 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7240 // output is suspended before any tracks are moved to it
7241 checkA2dpSuspend();
7242 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007243 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007244 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007245 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007246 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007247 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7248 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7249 // configuration changes will ultimately be rerouted correctly. We can still avoid
7250 // unnecessary rerouting by caching and reusing the arguments to
7251 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7252 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007253 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007254 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007255 // an event that changed routing likely occurred, inform upper layers
7256 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007257}
7258
François Gaffiec005e562018-11-06 15:04:49 +01007259bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7260 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007261{
François Gaffiec005e562018-11-06 15:04:49 +01007262 return mEngine->getProductStrategyForAttributes(lAttr) ==
7263 mEngine->getProductStrategyForAttributes(rAttr);
7264}
7265
Francois Gaffieff1eb522020-05-06 18:37:04 +02007266void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7267{
7268 for (size_t i = 0; i < mAudioSources.size(); i++) {
7269 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7270 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007271 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007272 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007273 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007274 }
7275 }
7276}
7277
7278void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7279{
7280 for (size_t i = 0; i < mAudioSources.size(); i++) {
7281 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7282 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7283 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7284 disconnectAudioSource(sourceDesc);
7285 }
7286 }
7287}
7288
François Gaffiec005e562018-11-06 15:04:49 +01007289void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7290{
7291 auto psId = mEngine->getProductStrategyForAttributes(attr);
7292
7293 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7294 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007295
François Gaffie11d30102018-11-02 16:09:09 +01007296 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7297 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007298
Eric Laurentc209fe42020-06-05 18:11:23 -07007299 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007300 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007301 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007302 // take into account dynamic audio policies related changes: if a client is now associated
7303 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007304 // invalidate clients on outputs that do not support all the newly selected devices for the
7305 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007306 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007307 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007308 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007309 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007310 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007311
Eric Laurentc209fe42020-06-05 18:11:23 -07007312 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7313 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7314 continue;
7315 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007316 if (!desc->supportsAllDevices(newDevices)) {
7317 invalidatedOutputs.push_back(desc);
7318 break;
7319 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007320 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007321 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007322 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7323 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7324 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007325 if (status == OK) {
7326 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7327 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7328 maxLatency = desc->latency();
7329 }
7330 invalidatedOutputs.push_back(desc);
7331 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007332 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007333 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007334 }
7335 }
7336
Eric Laurent56ed8842022-11-15 16:04:41 +01007337 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007338 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7339 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007340 for (audio_io_handle_t srcOut : srcOutputs) {
7341 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007342 if (desc == nullptr) continue;
7343
7344 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007345 maxLatency = desc->latency();
7346 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007347
Eric Laurent56ed8842022-11-15 16:04:41 +01007348 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007349 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007350 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007351 // a client on a non direct outputs has necessarily a linear PCM format
7352 // so we can call selectOutput() safely
7353 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7354 client->flags(),
7355 client->config().format,
7356 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007357 client->config().sample_rate,
7358 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007359 if (newOutput != srcOut) {
7360 invalidate = true;
7361 break;
7362 }
7363 } else {
7364 sp<IOProfile> profile = getProfileForOutput(newDevices,
7365 client->config().sample_rate,
7366 client->config().format,
7367 client->config().channel_mask,
7368 client->flags(),
7369 true /* directOnly */);
7370 if (profile != desc->mProfile) {
7371 invalidate = true;
7372 break;
7373 }
7374 }
7375 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007376 // mute strategy while moving tracks from one output to another
7377 if (invalidate) {
7378 invalidatedOutputs.push_back(desc);
7379 if (desc->isStrategyActive(psId)) {
7380 setStrategyMute(psId, true, desc);
7381 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7382 newDevices.types());
7383 }
Eric Laurente552edb2014-03-10 17:42:56 -07007384 }
François Gaffiec005e562018-11-06 15:04:49 +01007385 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007386 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007387 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007388 }
Eric Laurente552edb2014-03-10 17:42:56 -07007389 }
7390
Eric Laurent56ed8842022-11-15 16:04:41 +01007391 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7392 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7393 std::to_string(srcOutputs[0]).c_str(),
7394 std::to_string(dstOutputs[0]).c_str());
7395
François Gaffiec005e562018-11-06 15:04:49 +01007396 // Move effects associated to this stream from previous output to new output
7397 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007398 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007399 }
François Gaffiec005e562018-11-06 15:04:49 +01007400 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007401 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007402 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007403 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007404 desc->setTracksInvalidatedStatusByStrategy(psId);
7405 }
Eric Laurente552edb2014-03-10 17:42:56 -07007406 }
7407 }
7408}
7409
Eric Laurente0720872014-03-11 09:30:41 -07007410void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007411{
François Gaffiec005e562018-11-06 15:04:49 +01007412 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7413 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7414 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007415 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007416 }
Eric Laurente552edb2014-03-10 17:42:56 -07007417}
7418
Kevin Rocard153f92d2018-12-18 18:33:28 -08007419void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007420 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007421 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007422 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007423 for (size_t i = 0; i < mOutputs.size(); i++) {
7424 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7425 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007426 sp<AudioPolicyMix> primaryMix;
7427 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007428 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007429 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7430 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7431 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007432 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7433 for (auto &secondaryMix : secondaryMixes) {
7434 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7435 if (outputDesc != nullptr &&
jiabin6d66b372024-11-25 20:04:29 +00007436 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE &&
7437 outputDesc != outputDescriptor) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007438 secondaryDescs.push_back(outputDesc);
7439 }
7440 }
7441
jiabinc44b3462022-12-08 12:52:31 -08007442 if (status != OK &&
7443 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7444 // When it failed to query secondary output, only invalidate the client that is not
7445 // MMAP. The reason is that MMAP stream will not support secondary output.
7446 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007447 } else if (!std::equal(
7448 client->getSecondaryOutputs().begin(),
7449 client->getSecondaryOutputs().end(),
7450 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungced57302024-08-14 11:37:57 -07007451 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7452 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007453 // If the format is not PCM, the tracks should be invalidated to get correct
7454 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007455 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007456 } else {
7457 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7458 std::vector<audio_io_handle_t> secondaryOutputIds;
7459 for (const auto &secondaryDesc: secondaryDescs) {
7460 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7461 weakSecondaryDescs.push_back(secondaryDesc);
7462 }
7463 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7464 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007465 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007466 }
7467 }
7468 }
jiabin10a03f12021-05-07 23:46:28 +00007469 if (!trackSecondaryOutputs.empty()) {
7470 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7471 }
jiabinc44b3462022-12-08 12:52:31 -08007472 if (!clientsToInvalidate.empty()) {
7473 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7474 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007475 }
7476}
7477
Eric Laurent2517af32020-11-25 15:31:27 +01007478bool AudioPolicyManager::isScoRequestedForComm() const {
7479 AudioDeviceTypeAddrVector devices;
7480 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7481 for (const auto &device : devices) {
7482 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7483 return true;
7484 }
7485 }
7486 return false;
7487}
7488
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007489bool AudioPolicyManager::isHearingAidUsedForComm() const {
7490 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7491 true /*fromCache*/);
7492 for (const auto &device : devices) {
7493 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7494 return true;
7495 }
7496 }
7497 return false;
7498}
7499
7500
Eric Laurente0720872014-03-11 09:30:41 -07007501void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007502{
François Gaffie53615e22015-03-19 09:24:12 +01007503 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007504 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007505 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007506 return;
7507 }
7508
Eric Laurent3a4311c2014-03-17 12:00:47 -07007509 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007510 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7511 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007512 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007513
7514 // if suspended, restore A2DP output if:
7515 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007516 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007517 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007518 //
Eric Laurentf732e072016-08-03 19:30:28 -07007519 // if not suspended, suspend A2DP output if:
7520 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007521 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007522 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007523 //
7524 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007525 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007526 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007527 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007528 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007529
7530 mpClientInterface->restoreOutput(a2dpOutput);
7531 mA2dpSuspended = false;
7532 }
7533 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007534 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007535 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007536 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007537 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007538
7539 mpClientInterface->suspendOutput(a2dpOutput);
7540 mA2dpSuspended = true;
7541 }
7542 }
7543}
7544
François Gaffie11d30102018-11-02 16:09:09 +01007545DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7546 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007547{
François Gaffiedb1755b2023-09-01 11:50:35 +02007548 if (outputDesc == nullptr) {
7549 return DeviceVector{};
7550 }
François Gaffie11d30102018-11-02 16:09:09 +01007551
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007552 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007553 if (index >= 0) {
7554 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007555 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007556 ALOGV("%s device %s forced by patch %d", __func__,
7557 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7558 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007559 }
7560 }
7561
Dean Wheatley514b4312020-06-17 21:45:00 +10007562 // Do not retrieve engine device for outputs through MSD
7563 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7564 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7565 return outputDesc->devices();
7566 }
7567
Eric Laurent97ac8712018-07-27 18:59:02 -07007568 // Honor explicit routing requests only if no client using default routing is active on this
7569 // input: a specific app can not force routing for other apps by setting a preferred device.
7570 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007571 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007572 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007573 if (device != nullptr) {
7574 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007575 }
7576
François Gaffiea807ef92018-11-05 10:44:33 +01007577 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7578 // of setForceUse / Default Bus device here
7579 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7580 if (device != nullptr) {
7581 return DeviceVector(device);
7582 }
7583
François Gaffiedb1755b2023-09-01 11:50:35 +02007584 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007585 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7586 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307587 auto hasStreamActive = [&](auto stream) {
7588 return hasStream(streams, stream) && isStreamActive(stream, 0);
7589 };
Eric Laurent484e9272018-06-07 17:29:23 -07007590
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307591 auto doGetOutputDevicesForVoice = [&]() {
7592 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007593 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307594 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007595 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7596 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307597 };
7598
7599 // With low-latency playing on speaker, music on WFD, when the first low-latency
7600 // output is stopped, getNewOutputDevices checks for a product strategy
7601 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007602 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307603 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7604 // stream is associated to the output descriptor.
7605 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7606 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7607 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7608 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007609 // Retrieval of devices for voice DL is done on primary output profile, cannot
7610 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007611 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007612 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7613 break;
7614 }
Eric Laurente552edb2014-03-10 17:42:56 -07007615 }
François Gaffiec005e562018-11-06 15:04:49 +01007616 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007617 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007618}
7619
François Gaffie11d30102018-11-02 16:09:09 +01007620sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7621 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007622{
François Gaffie11d30102018-11-02 16:09:09 +01007623 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007624
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007625 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007626 if (index >= 0) {
7627 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007628 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007629 ALOGV("getNewInputDevice() device %s forced by patch %d",
7630 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7631 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007632 }
7633 }
7634
Eric Laurent97ac8712018-07-27 18:59:02 -07007635 // Honor explicit routing requests only if no client using default routing is active on this
7636 // input: a specific app can not force routing for other apps by setting a preferred device.
7637 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007638 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7639 if (device != nullptr) {
7640 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007641 }
7642
Eric Laurentdc95a252018-04-12 12:46:56 -07007643 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007644 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007645 audio_attributes_t attributes;
7646 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007647 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007648 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7649 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007650 attributes = topClient->attributes();
7651 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007652 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007653 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007654 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7655 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007656 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007657 }
7658
Francois Gaffie716e1432019-01-14 16:58:59 +01007659 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7660 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007661 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007662 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007663 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007664 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007665
Eric Laurente552edb2014-03-10 17:42:56 -07007666 return device;
7667}
7668
Eric Laurent794fde22016-03-11 09:50:45 -08007669bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7670 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007671 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007672}
7673
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007674status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007675 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007676 if (devices == nullptr) {
7677 return BAD_VALUE;
7678 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007679
Andy Hung6d23c0f2022-02-16 09:37:15 -08007680 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007681 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7682 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007683 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007684 for (const auto& device : curDevices) {
7685 devices->push_back(device->getDeviceTypeAddr());
7686 }
7687 return NO_ERROR;
7688}
7689
Eric Laurente0720872014-03-11 09:30:41 -07007690void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007691 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007692 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007693 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007694 updateDevicesAndOutputs();
7695 break;
7696 default:
7697 break;
7698 }
7699}
7700
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007701uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007702
7703 // skip beacon mute management if a dedicated TTS output is available
7704 if (mTtsOutputAvailable) {
7705 return 0;
7706 }
7707
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007708 switch(event) {
7709 case STARTING_OUTPUT:
7710 mBeaconMuteRefCount++;
7711 break;
7712 case STOPPING_OUTPUT:
7713 if (mBeaconMuteRefCount > 0) {
7714 mBeaconMuteRefCount--;
7715 }
7716 break;
7717 case STARTING_BEACON:
7718 mBeaconPlayingRefCount++;
7719 break;
7720 case STOPPING_BEACON:
7721 if (mBeaconPlayingRefCount > 0) {
7722 mBeaconPlayingRefCount--;
7723 }
7724 break;
7725 }
7726
7727 if (mBeaconMuteRefCount > 0) {
7728 // any playback causes beacon to be muted
7729 return setBeaconMute(true);
7730 } else {
7731 // no other playback: unmute when beacon starts playing, mute when it stops
7732 return setBeaconMute(mBeaconPlayingRefCount == 0);
7733 }
7734}
7735
7736uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7737 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7738 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7739 // keep track of muted state to avoid repeating mute/unmute operations
7740 if (mBeaconMuted != mute) {
7741 // mute/unmute AUDIO_STREAM_TTS on all outputs
7742 ALOGV("\t muting %d", mute);
7743 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007744 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7745 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7746 ALOGV("\t no tts volume source available");
7747 return 0;
7748 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007749 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007750 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007751 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007752 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007753 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007754 maxLatency = latency;
7755 }
7756 }
7757 mBeaconMuted = mute;
7758 return maxLatency;
7759 }
7760 return 0;
7761}
7762
Eric Laurente0720872014-03-11 09:30:41 -07007763void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007764{
François Gaffiec005e562018-11-06 15:04:49 +01007765 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007766 mPreviousOutputs = mOutputs;
7767}
7768
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007769uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007770 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007771 uint32_t delayMs)
7772{
7773 // mute/unmute strategies using an incompatible device combination
7774 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7775 // if unmuting, unmute only after the specified delay
7776 if (outputDesc->isDuplicated()) {
7777 return 0;
7778 }
7779
7780 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007781 DeviceVector devices = outputDesc->devices();
7782 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007783
François Gaffiec005e562018-11-06 15:04:49 +01007784 auto productStrategies = mEngine->getOrderedProductStrategies();
7785 for (const auto &productStrategy : productStrategies) {
7786 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7787 DeviceVector curDevices =
7788 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7789 curDevices = curDevices.filter(outputDesc->supportedDevices());
7790 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007791 bool doMute = false;
7792
François Gaffiec005e562018-11-06 15:04:49 +01007793 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007794 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007795 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7796 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007797 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007798 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007799 }
Eric Laurent99401132014-05-07 19:48:15 -07007800 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007801 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007802 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007803 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007804 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007805 continue;
7806 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307807 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007808 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7809 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7810 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007811 if (mute) {
7812 // FIXME: should not need to double latency if volume could be applied
7813 // immediately by the audioflinger mixer. We must account for the delay
7814 // between now and the next time the audioflinger thread for this output
7815 // will process a buffer (which corresponds to one buffer size,
7816 // usually 1/2 or 1/4 of the latency).
7817 if (muteWaitMs < desc->latency() * 2) {
7818 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007819 }
7820 }
7821 }
7822 }
7823 }
7824 }
7825
Eric Laurent99401132014-05-07 19:48:15 -07007826 // temporary mute output if device selection changes to avoid volume bursts due to
7827 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007828 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007829 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007830
Eric Laurentdc462862016-07-19 12:29:53 -07007831 if (muteWaitMs < tempMuteWaitMs) {
7832 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007833 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007834
7835 // If recommended duration is defined, replace temporary mute duration to avoid
7836 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7837 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7838 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7839 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7840 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7841
François Gaffieaaac0fd2018-11-22 17:56:39 +01007842 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7843 // make sure that we do not start the temporary mute period too early in case of
7844 // delayed device change
7845 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7846 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007847 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007848 }
7849 }
7850
Eric Laurente552edb2014-03-10 17:42:56 -07007851 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7852 if (muteWaitMs > delayMs) {
7853 muteWaitMs -= delayMs;
7854 usleep(muteWaitMs * 1000);
7855 return muteWaitMs;
7856 }
7857 return 0;
7858}
7859
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307860uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7861 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007862 const DeviceVector &devices,
7863 bool force,
7864 int delayMs,
7865 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007866 bool requiresMuteCheck, bool requiresVolumeCheck,
7867 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007868{
jiabin3ff8d7d2022-12-13 06:27:44 +00007869 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307870 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7871 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7872 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007873 uint32_t muteWaitMs;
7874
7875 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307876 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007877 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307878 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007879 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007880 return muteWaitMs;
7881 }
Eric Laurente552edb2014-03-10 17:42:56 -07007882
7883 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007884 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007885 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007886 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007887
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307888 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7889 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007890
7891 if (!filteredDevices.isEmpty()) {
7892 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007893 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007894
7895 // if the outputs are not materially active, there is no need to mute.
7896 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007897 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007898 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307899 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7900 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007901 muteWaitMs = 0;
7902 }
Eric Laurente552edb2014-03-10 17:42:56 -07007903
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007904 bool outputRouted = outputDesc->isRouted();
7905
Eric Laurent79ea9582020-06-11 18:49:24 -07007906 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7907 // output profile or if new device is not supported AND previous device(s) is(are) still
7908 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007909 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307910 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7911 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007912 // restore previous device after evaluating strategy mute state
7913 outputDesc->setDevices(prevDevices);
7914 return muteWaitMs;
7915 }
7916
Eric Laurente552edb2014-03-10 17:42:56 -07007917 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007918 // the requested device is AUDIO_DEVICE_NONE
7919 // OR the requested device is the same as current device
7920 // AND force is not specified
7921 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007922 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007923 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307924 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7925 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7926 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007927 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307928 ALOGV("%s %s setting same device on routed output, force apply volumes",
7929 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007930 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7931 }
Eric Laurente552edb2014-03-10 17:42:56 -07007932 return muteWaitMs;
7933 }
7934
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307935 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7936 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007937
Eric Laurente552edb2014-03-10 17:42:56 -07007938 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007939 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007940 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007941 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007942 PatchBuilder patchBuilder;
7943 patchBuilder.addSource(outputDesc);
7944 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7945 for (const auto &filteredDevice : filteredDevices) {
7946 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007947 }
7948
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007949 // Add half reported latency to delayMs when muteWaitMs is null in order
7950 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007951 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7952 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7953 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007954 }
Eric Laurente552edb2014-03-10 17:42:56 -07007955
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007956 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7957 if (!skipMuteDelay) {
7958 // update stream volumes according to new device
7959 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7960 }
Eric Laurente552edb2014-03-10 17:42:56 -07007961
7962 return muteWaitMs;
7963}
7964
Eric Laurentc75307b2015-03-17 15:29:32 -07007965status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007966 int delayMs,
7967 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007968{
Eric Laurent6a94d692014-05-20 11:18:06 -07007969 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007970 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7971 return INVALID_OPERATION;
7972 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007973 if (patchHandle) {
7974 index = mAudioPatches.indexOfKey(*patchHandle);
7975 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007976 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007977 }
7978 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007979 return INVALID_OPERATION;
7980 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007981 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007982 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007983 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007984 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007985 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007986 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007987 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007988 return status;
7989}
7990
7991status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007992 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007993 bool force,
7994 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007995{
7996 status_t status = NO_ERROR;
7997
Eric Laurent1f2f2232014-06-02 12:01:23 -07007998 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007999 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8000 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008001
François Gaffie11d30102018-11-02 16:09:09 +01008002 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008003 PatchBuilder patchBuilder;
8004 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008005 // AUDIO_SOURCE_HOTWORD is for internal use only:
8006 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008007 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8008 auto result = usecase;
8009 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8010 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8011 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008012 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008013 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008014 if (audio_is_remote_submix_device(device->type())) {
8015 // remote submix HAL does not support audio conversion, need source device
8016 // audio config to match the sink input descriptor audio config, otherwise AIDL
8017 // HAL patching will fail
8018 audio_port_config srcDevicePortConfig = {};
8019 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8020 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8021 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8022 srcDevicePortConfig.format = inputDesc->getFormat();
8023 patchBuilder.addSource(srcDevicePortConfig);
8024 } else {
8025 patchBuilder.addSource(device);
8026 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008027 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008028 }
8029 }
8030 return status;
8031}
8032
Eric Laurent6a94d692014-05-20 11:18:06 -07008033status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8034 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008035{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008036 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008037 ssize_t index;
8038 if (patchHandle) {
8039 index = mAudioPatches.indexOfKey(*patchHandle);
8040 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008041 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008042 }
8043 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008044 return INVALID_OPERATION;
8045 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008046 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008047 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008048 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008049 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008050 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008051 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008052 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008053 return status;
8054}
8055
François Gaffie11d30102018-11-02 16:09:09 +01008056sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008057 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008058 audio_format_t& format,
8059 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008060 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008061{
8062 // Choose an input profile based on the requested capture parameters: select the first available
8063 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008064 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008065
Atneya Nair0f0a8032022-12-12 16:20:12 -08008066 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8067 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8068 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8069
8070 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008071
jiabin2fd710d2022-05-02 23:20:22 +00008072 for (;;) {
8073 sp<IOProfile> firstInexact = nullptr;
8074 uint32_t updatedSamplingRate = 0;
8075 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8076 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8077 for (const auto& hwModule : mHwModules) {
8078 for (const auto& profile : hwModule->getInputProfiles()) {
8079 // profile->log();
8080 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008081 if (profile->getCompatibilityScore(
8082 DeviceVector(device),
8083 samplingRate,
8084 &updatedSamplingRate,
8085 format,
8086 &updatedFormat,
8087 channelMask,
8088 &updatedChannelMask,
8089 // FIXME ugly cast
8090 (audio_output_flags_t) flags,
8091 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8092 samplingRate = updatedSamplingRate;
8093 format = updatedFormat;
8094 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008095 return profile;
8096 }
jiabin66acc432024-02-06 00:57:36 +00008097 if (firstInexact == nullptr
8098 && profile->getCompatibilityScore(
8099 DeviceVector(device),
8100 samplingRate,
8101 &updatedSamplingRate,
8102 format,
8103 &updatedFormat,
8104 channelMask,
8105 &updatedChannelMask,
8106 // FIXME ugly cast
8107 (audio_output_flags_t) flags,
8108 false /*exactMatchRequiredForInputFlags*/)
8109 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008110 firstInexact = profile;
8111 }
8112 }
8113 }
8114
8115 if (firstInexact != nullptr) {
8116 samplingRate = updatedSamplingRate;
8117 format = updatedFormat;
8118 channelMask = updatedChannelMask;
8119 return firstInexact;
8120 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8121 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8122 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8123 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8124 flags = AUDIO_INPUT_FLAG_NONE;
8125 } else { // fail
8126 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8127 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8128 samplingRate, format, channelMask, oriFlags);
8129 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008130 }
8131 }
jiabin2fd710d2022-05-02 23:20:22 +00008132
8133 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008134}
8135
Vlad Popa87e0e582024-05-20 18:49:20 -07008136float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8137 VolumeSource volumeSource,
8138 int index,
8139 const DeviceTypeSet &deviceTypes)
8140{
8141 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8142 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8143 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8144
8145 if (com_android_media_audio_abs_volume_index_fix()) {
8146 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8147 mAbsoluteVolumeDrivingStreams.end()) {
8148 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8149 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8150 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8151 ALOGD("%s: no group matching with %s", __FUNCTION__,
8152 toString(attributesToDriveAbs).c_str());
8153 return volumeDb;
8154 }
8155
8156 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8157 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8158 if (vsToDriveAbs == volumeSource) {
8159 // attenuation is applied by the abs volume controller
8160 return volumeDbMax;
8161 } else {
8162 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8163 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8164 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8165 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8166 curvesAbs.getVolumeIndexMax());
8167 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8168 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8169 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8170 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8171 return newVolumeDb;
8172 }
8173 }
8174 return volumeDb;
8175 } else {
8176 return volumeDb;
8177 }
8178}
8179
François Gaffieaaac0fd2018-11-22 17:56:39 +01008180float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8181 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008182 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008183 const DeviceTypeSet& deviceTypes,
8184 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008185{
Vlad Popa87e0e582024-05-20 18:49:20 -07008186 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008187 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8188 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8189
8190 if (!computeInternalInteraction) {
8191 return volumeDb;
8192 }
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008193
8194 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8195 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8196 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8197 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008198 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8199 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8200 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8201 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8202 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008203 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008204 mOutputs.isActive(ringVolumeSrc, 0)) {
8205 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008206 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8207 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008208 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008209 }
8210
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008211 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008212 if ((volumeSource != callVolumeSrc && (isInCall() ||
8213 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008214 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008215 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8216 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008217 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8218 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8219 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008220 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008221 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008222 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008223 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008224 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8225 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008226 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008227 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8228 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8229 // programmatically muted.
8230 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8231 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8232 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008233 bool exemptFromCapping =
8234 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8235 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008236 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8237 volumeSource, volumeDb);
8238 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008239 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8240 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8241 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008242 }
8243 }
Eric Laurente552edb2014-03-10 17:42:56 -07008244 // if a headset is connected, apply the following rules to ring tones and notifications
8245 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008246 // - always attenuate notifications volume by 6dB
8247 // - attenuate ring tones volume by 6dB unless music is not playing and
8248 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008249 // - if music is playing, always limit the volume to current music volume,
8250 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008251 if (!Intersection(deviceTypes,
8252 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8253 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008254 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8255 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008256 ((volumeSource == alarmVolumeSrc ||
8257 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008258 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8259 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8260 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008261 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8262 curves.canBeMuted()) {
8263
Eric Laurente552edb2014-03-10 17:42:56 -07008264 // when the phone is ringing we must consider that music could have been paused just before
8265 // by the music application and behave as if music was active if the last music track was
8266 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008267 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8268 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008269 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008270 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008271 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8272 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008273 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008274 float musicVolDb = computeVolume(musicCurves,
8275 musicVolumeSrc,
8276 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008277 musicDevice,
8278 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008279 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8280 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8281 if (volumeDb > minVolDb) {
8282 volumeDb = minVolDb;
8283 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008284 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008285 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8286 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008287 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8288 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8289 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8290 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008291 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008292 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008293 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8294 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008295 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8296 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008297 }
8298 }
jiabin9a3361e2019-10-01 09:38:30 -07008299 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008300 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008301 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008302 }
8303 }
8304
François Gaffie43c73442018-11-08 08:21:55 +01008305 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008306}
8307
Eric Laurent3839bc02018-07-10 18:33:34 -07008308int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008309 VolumeSource fromVolumeSource,
8310 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008311{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008312 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008313 return srcIndex;
8314 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008315 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8316 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008317 float minSrc = (float)srcCurves.getVolumeIndexMin();
8318 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8319 float minDst = (float)dstCurves.getVolumeIndexMin();
8320 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008321
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008322 // preserve mute request or correct range
8323 if (srcIndex < minSrc) {
8324 if (srcIndex == 0) {
8325 return 0;
8326 }
8327 srcIndex = minSrc;
8328 } else if (srcIndex > maxSrc) {
8329 srcIndex = maxSrc;
8330 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008331 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8332}
8333
François Gaffieaaac0fd2018-11-22 17:56:39 +01008334status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8335 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008336 int index,
8337 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008338 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008339 int delayMs,
8340 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008341{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008342 // APM is single threaded, and single instance.
8343 static std::set<IVolumeCurves*> invalidCurvesReported;
8344
François Gaffieaaac0fd2018-11-22 17:56:39 +01008345 // do not change actual attributes volume if the attributes is muted
8346 if (outputDesc->isMuted(volumeSource)) {
8347 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8348 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008349 return NO_ERROR;
8350 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008351
Eric Laurent5baf07c2024-01-11 16:57:27 +00008352 bool isVoiceVolSrc;
8353 bool isBtScoVolSrc;
8354 if (!isVolumeConsistentForCalls(
8355 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008356 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008357 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008358 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008359 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008360
jiabin9a3361e2019-10-01 09:38:30 -07008361 if (deviceTypes.empty()) {
8362 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008363 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008364 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008365 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008366 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008367
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008368 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008369 if (!invalidCurvesReported.count(&curves)) {
8370 invalidCurvesReported.insert(&curves);
8371 String8 dump;
8372 curves.dump(&dump);
8373 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8374 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008375 return BAD_VALUE;
8376 }
8377
jiabin9a3361e2019-10-01 09:38:30 -07008378 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8379 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008380 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008381 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008382 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8383 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008384 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008385 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008386 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008387 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8388 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008389
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008390 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008391 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8392 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8393 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008394 }
Eric Laurente552edb2014-03-10 17:42:56 -07008395 return NO_ERROR;
8396}
8397
Eric Laurent5baf07c2024-01-11 16:57:27 +00008398void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008399 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008400 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008401 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008402 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008403 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008404 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8405 } else {
8406 voiceVolume = index == 0 ? 0.0 : 1.0;
8407 }
8408 if (voiceVolume != mLastVoiceVolume) {
8409 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8410 mLastVoiceVolume = voiceVolume;
8411 }
8412}
8413
8414bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8415 const DeviceTypeSet& deviceTypes,
8416 bool& isVoiceVolSrc,
8417 bool& isBtScoVolSrc,
8418 const char* caller) {
8419 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8420 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8421 const bool isScoRequested = isScoRequestedForComm();
8422 const bool isHAUsed = isHearingAidUsedForComm();
8423
8424 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8425 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8426
8427 if ((callVolSrc != btScoVolSrc) &&
8428 ((isVoiceVolSrc && isScoRequested) ||
8429 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8430 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8431 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8432 volumeSource, isScoRequested ? " " : " not ");
8433 return false;
8434 }
8435 return true;
8436}
8437
Eric Laurentc75307b2015-03-17 15:29:32 -07008438void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008439 const DeviceTypeSet& deviceTypes,
8440 int delayMs,
8441 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008442{
jiabincd510522020-01-22 09:40:55 -08008443 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008444 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8445 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8446 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008447 curves.getVolumeIndex(deviceTypes),
8448 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008449 }
8450}
8451
François Gaffiec005e562018-11-06 15:04:49 +01008452void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8453 bool on,
8454 const sp<AudioOutputDescriptor>& outputDesc,
8455 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008456 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008457{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008458 std::vector<VolumeSource> sourcesToMute;
8459 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8460 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8461 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008462 VolumeSource source = toVolumeSource(attributes, false);
8463 if ((source != VOLUME_SOURCE_NONE) &&
8464 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8465 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008466 sourcesToMute.push_back(source);
8467 }
Eric Laurente552edb2014-03-10 17:42:56 -07008468 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008469 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008470 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008471 }
8472
Eric Laurente552edb2014-03-10 17:42:56 -07008473}
8474
François Gaffieaaac0fd2018-11-22 17:56:39 +01008475void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8476 bool on,
8477 const sp<AudioOutputDescriptor>& outputDesc,
8478 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008479 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008480{
jiabin9a3361e2019-10-01 09:38:30 -07008481 if (deviceTypes.empty()) {
8482 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008483 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008484 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008485 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008486 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008487 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008488 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008489 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8490 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008491 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008492 }
8493 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008494 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8495 // ignored
8496 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008497 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008498 if (!outputDesc->isMuted(volumeSource)) {
8499 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008500 return;
8501 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008502 if (outputDesc->decMuteCount(volumeSource) == 0) {
8503 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008504 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008505 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008506 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008507 delayMs);
8508 }
8509 }
8510}
8511
François Gaffie53615e22015-03-19 09:24:12 +01008512bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8513{
François Gaffiec005e562018-11-06 15:04:49 +01008514 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008515 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8516 return true;
8517 }
8518
8519 // has known usage?
8520 switch (paa->usage) {
8521 case AUDIO_USAGE_UNKNOWN:
8522 case AUDIO_USAGE_MEDIA:
8523 case AUDIO_USAGE_VOICE_COMMUNICATION:
8524 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8525 case AUDIO_USAGE_ALARM:
8526 case AUDIO_USAGE_NOTIFICATION:
8527 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8528 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8529 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8530 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8531 case AUDIO_USAGE_NOTIFICATION_EVENT:
8532 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8533 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8534 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8535 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008536 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008537 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008538 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008539 case AUDIO_USAGE_EMERGENCY:
8540 case AUDIO_USAGE_SAFETY:
8541 case AUDIO_USAGE_VEHICLE_STATUS:
8542 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008543 break;
8544 default:
8545 return false;
8546 }
8547 return true;
8548}
8549
François Gaffie2110e042015-03-24 08:41:51 +01008550audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8551{
8552 return mEngine->getForceUse(usage);
8553}
8554
Eric Laurent96d1dda2022-03-14 17:14:19 +01008555bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008556 return isStateInCall(mEngine->getPhoneState());
8557}
8558
Eric Laurent96d1dda2022-03-14 17:14:19 +01008559bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008560 return is_state_in_call(state);
8561}
8562
Eric Laurentf9cccec2022-11-16 19:12:00 +01008563bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008564 audio_mode_t mode = mEngine->getPhoneState();
8565 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008566 || (mode == AUDIO_MODE_CALL_SCREEN)
8567 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008568}
8569
Eric Laurentf9cccec2022-11-16 19:12:00 +01008570bool AudioPolicyManager::isInCallOrScreening() const {
8571 audio_mode_t mode = mEngine->getPhoneState();
8572 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8573}
8574
Eric Laurentd60560a2015-04-10 11:31:20 -07008575void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8576{
8577 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008578 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008579 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008580 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008581 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008582 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008583 }
8584 }
8585
8586 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8587 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8588 bool release = false;
8589 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8590 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8591 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8592 source->ext.device.type == deviceDesc->type()) {
8593 release = true;
8594 }
8595 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008596 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008597 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8598 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8599 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008600 sink->ext.device.type == deviceDesc->type() &&
8601 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8602 || strncmp(sink->ext.device.address, address,
8603 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008604 release = true;
8605 }
8606 }
8607 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008608 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8609 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008610 }
8611 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008612
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008613 mInputs.clearSessionRoutesForDevice(deviceDesc);
8614
Francois Gaffie716e1432019-01-14 16:58:59 +01008615 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008616}
8617
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008618void AudioPolicyManager::modifySurroundFormats(
8619 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008620 std::unordered_set<audio_format_t> enforcedSurround(
8621 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008622 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008623 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008624 allSurround.insert(pair.first);
8625 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8626 }
Phil Burk09bc4612016-02-24 15:58:15 -08008627
8628 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8629 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008630 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008631 // This is the resulting set of formats depending on the surround mode:
8632 // 'all surround' = allSurround
8633 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8634 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8635 // 'manual surround' = mManualSurroundFormats
8636 // AUTO: formats v 'enforced surround'
8637 // ALWAYS: formats v 'all surround' v 'enforced surround'
8638 // NEVER: formats ^ 'non-surround'
8639 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008640
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008641 std::unordered_set<audio_format_t> formatSet;
8642 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8643 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008644 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008645 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008646 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008647 formatSet.insert(*formatIter);
8648 }
8649 }
8650 } else {
8651 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8652 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008653 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008654
jiabin81772902018-04-02 17:52:27 -07008655 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008656 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008657 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8658 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8659 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008660 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008661 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8662 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8663 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008664 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008665 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008666 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008667 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008668 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008669 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008670}
8671
jiabin06e4bab2019-07-29 10:13:34 -07008672void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8673 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008674 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8675 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8676
8677 // If NEVER, then remove support for channelMasks > stereo.
8678 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008679 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8680 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008681 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008682 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008683 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008684 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008685 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008686 }
8687 }
jiabin81772902018-04-02 17:52:27 -07008688 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8689 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8690 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008691 bool supports5dot1 = false;
8692 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008693 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008694 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8695 supports5dot1 = true;
8696 break;
8697 }
8698 }
8699 // If not then add 5.1 support.
8700 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008701 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008702 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008703 }
Phil Burk09bc4612016-02-24 15:58:15 -08008704 }
8705}
8706
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008707void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008708 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008709 const sp<IOProfile>& profile) {
8710 if (!profile->hasDynamicAudioProfile()) {
8711 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008712 }
François Gaffie112b0af2015-11-19 16:13:25 +01008713
jiabin12537fc2023-10-12 17:56:08 +00008714 audio_port_v7 devicePort;
8715 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008716
jiabin12537fc2023-10-12 17:56:08 +00008717 audio_port_v7 mixPort;
8718 profile->toAudioPort(&mixPort);
8719 mixPort.ext.mix.handle = ioHandle;
8720
8721 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8722 if (status != NO_ERROR) {
8723 ALOGE("%s failed to query the attributes of the mix port", __func__);
8724 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008725 }
jiabin12537fc2023-10-12 17:56:08 +00008726
8727 std::set<audio_format_t> supportedFormats;
8728 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8729 supportedFormats.insert(mixPort.audio_profiles[i].format);
8730 }
8731 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8732 mReportedFormatsMap[devDesc] = formats;
8733
8734 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008735 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8736 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008737 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8738 modifySurroundFormats(devDesc, &formats);
8739 size_t modifiedNumProfiles = 0;
8740 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8741 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8742 formats.end()) {
8743 // Skip the format that is not present after modifying surround formats.
8744 continue;
8745 }
8746 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8747 sizeof(struct audio_profile));
8748 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8749 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8750 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8751 modifySurroundChannelMasks(&channels);
8752 std::copy(channels.begin(), channels.end(),
8753 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8754 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8755 }
8756 mixPort.num_audio_profiles = modifiedNumProfiles;
8757 }
8758 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008759}
Eric Laurentd60560a2015-04-10 11:31:20 -07008760
Mikhail Naganovdc769682018-05-04 15:34:08 -07008761status_t AudioPolicyManager::installPatch(const char *caller,
8762 audio_patch_handle_t *patchHandle,
8763 AudioIODescriptorInterface *ioDescriptor,
8764 const struct audio_patch *patch,
8765 int delayMs)
8766{
8767 ssize_t index = mAudioPatches.indexOfKey(
8768 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8769 *patchHandle : ioDescriptor->getPatchHandle());
8770 sp<AudioPatch> patchDesc;
8771 status_t status = installPatch(
8772 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8773 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008774 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008775 }
8776 return status;
8777}
8778
8779status_t AudioPolicyManager::installPatch(const char *caller,
8780 ssize_t index,
8781 audio_patch_handle_t *patchHandle,
8782 const struct audio_patch *patch,
8783 int delayMs,
8784 uid_t uid,
8785 sp<AudioPatch> *patchDescPtr)
8786{
8787 sp<AudioPatch> patchDesc;
8788 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8789 if (index >= 0) {
8790 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008791 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008792 }
8793
8794 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8795 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8796 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8797 if (status == NO_ERROR) {
8798 if (index < 0) {
8799 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008800 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008801 } else {
8802 patchDesc->mPatch = *patch;
8803 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008804 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008805 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008806 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008807 }
8808 nextAudioPortGeneration();
8809 mpClientInterface->onAudioPatchListUpdate();
8810 }
8811 if (patchDescPtr) *patchDescPtr = patchDesc;
8812 return status;
8813}
8814
jiabinbce0c1d2020-10-05 11:20:18 -07008815bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8816{
8817 const TrackClientVector activeClients = output->getActiveClients();
8818 if (activeClients.empty()) {
8819 return true;
8820 }
8821 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8822 if (index < 0) {
8823 ALOGE("%s, no audio patch found while there are active clients on output %d",
8824 __func__, output->getId());
8825 return false;
8826 }
8827 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8828 DeviceVector routedDevices;
8829 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8830 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8831 patchDesc->mPatch.sinks[i].id);
8832 if (device == nullptr) {
8833 ALOGE("%s, no audio device found with id(%d)",
8834 __func__, patchDesc->mPatch.sinks[i].id);
8835 return false;
8836 }
8837 routedDevices.add(device);
8838 }
8839 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008840 if (client->isInvalid()) {
8841 // No need to take care about invalidated clients.
8842 continue;
8843 }
jiabinbce0c1d2020-10-05 11:20:18 -07008844 sp<DeviceDescriptor> preferredDevice =
8845 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8846 if (mEngine->getOutputDevicesForAttributes(
8847 client->attributes(), preferredDevice, false) == routedDevices) {
8848 return false;
8849 }
8850 }
8851 return true;
8852}
8853
8854sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008855 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008856 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8857 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008858{
8859 for (const auto& device : devices) {
8860 // TODO: This should be checking if the profile supports the device combo.
8861 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008862 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8863 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008864 return nullptr;
8865 }
8866 }
8867 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8868 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008869 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008870 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11008871 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008872 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008873 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008874 return nullptr;
8875 }
jiabin14b50cc2023-12-13 19:01:52 +00008876 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8877 auto portConfig = desc->getConfig();
8878 for (const auto& device : devices) {
8879 device->setPreferredConfig(&portConfig);
8880 }
8881 }
jiabinbce0c1d2020-10-05 11:20:18 -07008882
8883 // Here is where the out_set_parameters() for card & device gets called
8884 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8885 const audio_devices_t deviceType = device->type();
8886 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008887 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008888 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8889 mpClientInterface->setParameters(output, String8(param));
8890 free(param);
8891 }
jiabin12537fc2023-10-12 17:56:08 +00008892 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008893 if (!profile->hasValidAudioProfile()) {
8894 ALOGW("%s() missing param", __func__);
8895 desc->close();
8896 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008897 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8898 // Reopen the output with the best audio profile picked by APM when the profile supports
8899 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008900 desc->close();
8901 output = AUDIO_IO_HANDLE_NONE;
8902 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8903 profile->pickAudioProfile(
8904 config.sample_rate, config.channel_mask, config.format);
8905 config.offload_info.sample_rate = config.sample_rate;
8906 config.offload_info.channel_mask = config.channel_mask;
8907 config.offload_info.format = config.format;
8908
Dean Wheatleydfb67b82024-01-23 09:36:29 +11008909 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008910 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008911 if (status != NO_ERROR) {
8912 return nullptr;
8913 }
8914 }
8915
8916 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07008917 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
8918 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
8919 hwModule->getHalVersionMajor() >= 3) {
8920 setOutputDevices(__func__, desc, devices, true, 0, NULL);
8921 }
baek.kim -61c20122022-07-27 10:05:32 +00008922 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8923 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8924
jiabinbce0c1d2020-10-05 11:20:18 -07008925 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8926 sp<AudioPolicyMix> policyMix;
8927 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8928 policyMix->setOutput(desc);
8929 desc->mPolicyMix = policyMix;
8930 } else {
8931 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008932 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008933 }
8934
baek.kim -61c20122022-07-27 10:05:32 +00008935 } else if (hasPrimaryOutput() && speaker != nullptr
8936 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008937 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8938 // no duplicated output for:
8939 // - direct outputs
8940 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008941 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008942 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8943
8944 //TODO: configure audio effect output stage here
8945
8946 // open a duplicating output thread for the new output and the primary output
8947 sp<SwAudioOutputDescriptor> dupOutputDesc =
8948 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8949 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8950 if (status == NO_ERROR) {
8951 // add duplicated output descriptor
8952 addOutput(duplicatedOutput, dupOutputDesc);
8953 } else {
8954 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8955 mPrimaryOutput->mIoHandle, output);
8956 desc->close();
8957 removeOutput(output);
8958 nextAudioPortGeneration();
8959 return nullptr;
8960 }
8961 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008962 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8963 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8964 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008965 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008966 }
jiabinbce0c1d2020-10-05 11:20:18 -07008967 return desc;
8968}
8969
jiabinf1c73972022-04-14 16:28:52 -07008970status_t AudioPolicyManager::getDevicesForAttributes(
8971 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8972 // Devices are determined in the following precedence:
8973 //
8974 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8975 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8976 //
8977 // If no such dynamic policy then
8978 // 2) Devices containing an active client using setPreferredDevice
8979 // with same strategy as the attributes.
8980 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8981 //
8982 // If no corresponding active client with setPreferredDevice then
8983 // 3) Devices associated with the strategy determined by the attributes
8984 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8985 //
8986 // See related getOutputForAttrInt().
8987
8988 // check dynamic policies but only for primary descriptors (secondary not used for audible
8989 // audio routing, only used for duplication for playback capture)
8990 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008991 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008992 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008993 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8994 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8995 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008996 if (status != OK) {
8997 return status;
8998 }
8999
9000 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9001 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9002 // as they are unaffected by device/stream volume
9003 // (per SwAudioOutputDescriptor::isFixedVolume()).
9004 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9005 ) {
9006 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9007 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9008 devices.add(deviceDesc);
9009 } else {
9010 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9011 // which selects setPreferredDevice if active. This means forVolume call
9012 // will take an active setPreferredDevice, if such exists.
9013
9014 devices = mEngine->getOutputDevicesForAttributes(
9015 attr, nullptr /* preferredDevice */, false /* fromCache */);
9016 }
9017
9018 if (forVolume) {
9019 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9020 // for single volume control in AudioService (such relationship should exist if
9021 // SPEAKER_SAFE is present).
9022 //
9023 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9024 DeviceVector speakerSafeDevices =
9025 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9026 if (!speakerSafeDevices.isEmpty()) {
9027 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9028 devices.remove(speakerSafeDevices);
9029 }
9030 }
9031
9032 return NO_ERROR;
9033}
9034
9035status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9036 AudioProfileVector& audioProfiles,
9037 uint32_t flags,
9038 bool isInput) {
9039 for (const auto& hwModule : mHwModules) {
9040 // the MSD module checks for different conditions
9041 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9042 continue;
9043 }
9044 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9045 : hwModule->getOutputProfiles();
9046 for (const auto& profile : ioProfiles) {
9047 if (!profile->areAllDevicesSupported(devices) ||
9048 !profile->isCompatibleProfileForFlags(
9049 flags, false /*exactMatchRequiredForInputFlags*/)) {
9050 continue;
9051 }
9052 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9053 }
9054 }
9055
9056 if (!isInput) {
9057 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9058 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9059 if (msdModule != nullptr) {
9060 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9061 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9062 for (const auto &profile: msdModule->getOutputProfiles()) {
9063 if (!profile->asAudioPort()->isDirectOutput()) {
9064 continue;
9065 }
9066 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9067 }
9068 } else {
9069 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9070 }
9071 }
9072 }
9073
9074 return NO_ERROR;
9075}
9076
jiabin3ff8d7d2022-12-13 06:27:44 +00009077sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9078 const audio_config_t *config,
9079 audio_output_flags_t flags,
9080 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009081 closeOutput(outputDesc->mIoHandle);
9082 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9083 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9084 if (preferredOutput == nullptr) {
9085 ALOGE("%s failed to reopen output device=%d, caller=%s",
9086 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009087 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009088 return preferredOutput;
9089}
9090
9091void AudioPolicyManager::reopenOutputsWithDevices(
9092 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9093 for (const auto& [output, devices] : outputsToReopen) {
9094 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9095 closeOutput(output);
9096 openOutputWithProfileAndDevice(desc->mProfile, devices);
9097 }
jiabina84c3d32022-12-02 18:59:55 +00009098}
9099
jiabinc44b3462022-12-08 12:52:31 -08009100PortHandleVector AudioPolicyManager::getClientsForStream(
9101 audio_stream_type_t streamType) const {
9102 PortHandleVector clients;
9103 for (size_t i = 0; i < mOutputs.size(); ++i) {
9104 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9105 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9106 }
9107 return clients;
9108}
9109
9110void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9111 PortHandleVector clients;
9112 for (auto stream : streams) {
9113 PortHandleVector clientsForStream = getClientsForStream(stream);
9114 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9115 }
9116 mpClientInterface->invalidateTracks(clients);
9117}
9118
jiabin220eea12024-05-17 17:55:20 +00009119void AudioPolicyManager::updateClientsInternalMute(
9120 const sp<android::SwAudioOutputDescriptor> &desc) {
9121 if (!desc->isBitPerfect() ||
9122 !com::android::media::audioserver::
9123 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9124 // This is only used for bit perfect output now.
9125 return;
9126 }
9127 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9128 bool bitPerfectClientInternalMute = false;
9129 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9130 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9131 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9132 bitPerfectClient = client;
9133 continue;
9134 }
9135 bool muted = false;
9136 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9137 // System sound is muted.
9138 muted = true;
9139 } else {
9140 bitPerfectClientInternalMute = true;
9141 }
9142 if (client->setInternalMute(muted)) {
9143 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9144 if (!result.ok()) {
9145 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9146 continue;
9147 }
9148 media::TrackInternalMuteInfo info;
9149 info.portId = result.value();
9150 info.muted = client->getInternalMute();
9151 clientsInternalMute.push_back(std::move(info));
9152 }
9153 }
9154 if (bitPerfectClient != nullptr &&
9155 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9156 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9157 if (result.ok()) {
9158 media::TrackInternalMuteInfo info;
9159 info.portId = result.value();
9160 info.muted = bitPerfectClient->getInternalMute();
9161 clientsInternalMute.push_back(std::move(info));
9162 } else {
9163 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9164 __func__, bitPerfectClient->portId());
9165 }
9166 }
9167 if (!clientsInternalMute.empty()) {
9168 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9169 status != NO_ERROR) {
9170 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9171 }
9172 }
9173}
9174
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009175} // namespace android