blob: d51266521ebedd1cda54d60d845588bd8c90d4ed [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
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000125void 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);
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
131 status != OK) {
132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganov3754b642024-04-17 18:31:04 +0000222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530377 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700378 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } // end if is output device
380
Eric Laurente552edb2014-03-10 17:42:56 -0700381 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700382 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700384 switch (state)
385 {
386 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700390 return INVALID_OPERATION;
391 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700392
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530393 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (mAvailableInputDevices.add(device) < 0) {
396 return NO_MEMORY;
397 }
398
François Gaffie44481e72016-04-20 07:49:57 +0200399 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
400 // parameters on newly connected devices (instead of opening the inputs...)
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000401 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700402 // Propagate device availability to Engine
403 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200404
Eric Laurent0dd51852019-04-19 18:18:58 -0700405 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700406 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
407
Eric Laurent0dd51852019-04-19 18:18:58 -0700408 mAvailableInputDevices.remove(device);
409
jiabinc0048632023-04-27 22:04:31 +0000410 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100411
412 mHwModules.cleanUpForDevice(device);
413
Eric Laurentd4692962014-05-05 18:13:44 -0700414 return INVALID_OPERATION;
415 }
416
Eric Laurentd4692962014-05-05 18:13:44 -0700417 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700418
419 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700420 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700421 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return INVALID_OPERATION;
424 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700425
François Gaffie11d30102018-11-02 16:09:09 +0100426 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700427
jiabinc0048632023-04-27 22:04:31 +0000428 // Notify the HAL to prepare to disconnect device
429 broadcastDeviceConnectionState(
430 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700431
François Gaffie11d30102018-11-02 16:09:09 +0100432 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700433
434 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100435
jiabinc0048632023-04-27 22:04:31 +0000436 // Set Disconnect to HALs
437 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
438
Kriti Dangef6be8f2020-11-05 11:58:19 +0100439 // remove device from mReportedFormatsMap cache
440 mReportedFormatsMap.erase(device);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700441
442 // Propagate device availability to Engine
443 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700444 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700445
446 default:
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449 }
450
Eric Laurent0dd51852019-04-19 18:18:58 -0700451 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700452 // As the input device list can impact the output device selection, update
453 // getDeviceForStrategy() cache
454 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700455
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100456 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200457 // Reconnect Audio Source
458 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
459 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
460 checkAudioSourceForAttributes(attributes);
461 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700462 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100463 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700464 }
465
Eric Laurentb52c1522014-05-20 11:27:36 -0700466 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530467 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700468 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700469 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700470
François Gaffie11d30102018-11-02 16:09:09 +0100471 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700472 return BAD_VALUE;
473}
474
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100475status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
476 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800477 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000478 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
479 devDescr->setName(device_name);
480 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100481}
482
Eric Laurent736a1022019-03-27 18:28:46 -0700483void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
484 audio_policy_dev_state_t state) {
485
486 // the Engine does not have to know about remote submix devices used by dynamic audio policies
487 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
488 return;
489 }
490 mEngine->setDeviceConnectionState(device, state);
491}
492
493
Eric Laurente0720872014-03-11 09:30:41 -0700494audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100495 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700496{
Eric Laurent634b7142016-04-20 13:48:02 -0700497 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800498 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
499 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700500 (strlen(device_address) != 0)/*matchAddress*/);
501
502 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100503 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700504 device, device_address);
505 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
506 }
François Gaffie53615e22015-03-19 09:24:12 +0100507
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 DeviceVector *deviceVector;
509
Eric Laurente552edb2014-03-10 17:42:56 -0700510 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700511 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700512 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700513 deviceVector = &mAvailableInputDevices;
514 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100515 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700516 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700517 }
Eric Laurent634b7142016-04-20 13:48:02 -0700518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 return (deviceVector->getDevice(
520 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800522}
523
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
525 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 const char *device_name,
527 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
530 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800532 // connect/disconnect only 1 device at a time
533 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
534
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800535 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700536 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538 // Nothing to do: device is not connected
539 return NO_ERROR;
540 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800542
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700543 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 // configure codecs.
545 // Handle two specific cases by sending a set parameter to
546 // configure A2DP codecs. No need to toggle device state.
547 // Case 1: A2DP active device switches from primary to primary
548 // module
549 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100550 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700551 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800552 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
553 if (availablePrimaryOutputDevices().contains(devDesc) &&
554 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100555 bool isA2dp = audio_is_a2dp_out_device(device);
556 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
557 : String8(AudioParameter::keyReconfigLeSupported);
558 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800559 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100560 int isReconfigSupported;
561 repliedParameters.getInt(supportKey, isReconfigSupported);
562 if (isReconfigSupported) {
563 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
564 : String8(AudioParameter::keyReconfigLe);
565 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 param.add(key, String8("true"));
567 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
568 devDesc->setEncodedFormat(encodedFormat);
569 return NO_ERROR;
570 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700571 }
572 }
cnx421bd2dcc42020-07-11 14:58:44 +0800573 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000574 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800575 for (size_t i = 0; i < mOutputs.size(); i++) {
576 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000577 // mute media strategies to avoid sending the music tail into
578 // the earpiece or headset.
579 if (desc->isStrategyActive(musicStrategy)) {
580 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
581 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
582 tempRecommendedMuteDuration : desc->latency() * 4;
583 if (muteWaitMs < tempMuteDurationMs) {
584 muteWaitMs = tempMuteDurationMs;
585 }
586 }
cnx421bd2dcc42020-07-11 14:58:44 +0800587 setStrategyMute(musicStrategy, true, desc);
588 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
589 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
590 nullptr, true /*fromCache*/).types());
591 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000592 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
593 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
594 // happens after the actual device switch.
595 if (muteWaitMs > 0) {
596 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
597 usleep(muteWaitMs * 1000);
598 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800599 // Toggle the device state: UNAVAILABLE -> AVAILABLE
600 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100601 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800602 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800603 device_address, device_name,
604 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800605 if (status != NO_ERROR) {
606 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
607 status);
608 return status;
609 }
610
611 status = setDeviceConnectionState(device,
612 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800613 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800614 if (status != NO_ERROR) {
615 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
616 status);
617 return status;
618 }
619
620 return NO_ERROR;
621}
622
Pattydd807582021-11-04 21:01:03 +0800623status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
624 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800625{
Pattydd807582021-11-04 21:01:03 +0800626 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800627 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800628 std::unordered_set<audio_format_t> formatSet;
629 sp<HwModule> primaryModule =
630 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700631 if (primaryModule == nullptr) {
632 ALOGE("%s() unable to get primary module", __func__);
633 return NO_INIT;
634 }
Pattydd807582021-11-04 21:01:03 +0800635
636 DeviceTypeSet audioDeviceSet;
637
638 switch(device) {
639 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
640 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
641 break;
642 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800643 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
644 break;
645 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
646 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800647 break;
648 default:
649 ALOGE("%s() device type 0x%08x not supported", __func__, device);
650 return BAD_VALUE;
651 }
652
jiabin9a3361e2019-10-01 09:38:30 -0700653 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800654 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800655 for (const auto& device : declaredDevices) {
656 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800657 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800658 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800659 return status;
660}
661
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
663{
664 DeviceVector rxSinkdevices{};
665 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
666 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
667 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
668 auto rxSinkDevice = rxSinkdevices.itemAt(0);
669 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
670 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
671 // retrieve Rx Source device descriptor
672 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
673 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
674
675 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
676 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
677 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
678 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
679 return DeviceVector(rxSinkDevice);
680 }
681 }
682 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
683 // the device returned is not necessarily reachable via this output
684 // (filter later by setOutputDevices())
685 return getNewOutputDevices(mPrimaryOutput, fromCache);
686}
687
688status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
689{
François Gaffiedb1755b2023-09-01 11:50:35 +0200690 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100691 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
692 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
693 }
694 return INVALID_OPERATION;
695}
696
697status_t AudioPolicyManager::updateCallRoutingInternal(
698 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700699{
700 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100701 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700702 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200703 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700704 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100705 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700706 }
François Gaffie11d30102018-11-02 16:09:09 +0100707
Francois Gaffie716e1432019-01-14 16:58:59 +0100708 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100709 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200710
711 disconnectTelephonyAudioSource(mCallRxSourceClient);
712 disconnectTelephonyAudioSource(mCallTxSourceClient);
713
714 if (rxDevices.isEmpty()) {
715 ALOGW("%s() no selected output device", __func__);
716 return INVALID_OPERATION;
717 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000718 if (txSourceDevice == nullptr) {
719 ALOGE("%s() selected input device not available", __func__);
720 return INVALID_OPERATION;
721 }
François Gaffiec005e562018-11-06 15:04:49 +0100722
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100723 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100724 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700725
François Gaffie9eb18552018-11-05 10:33:26 +0100726 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700727 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100728 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700729 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100730 // retrieve Rx Source and Tx Sink device descriptors
731 sp<DeviceDescriptor> rxSourceDevice =
732 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
733 String8(),
734 AUDIO_FORMAT_DEFAULT);
735 sp<DeviceDescriptor> txSinkDevice =
736 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
737 String8(),
738 AUDIO_FORMAT_DEFAULT);
739
740 // RX and TX Telephony device are declared by Primary Audio HAL
741 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
742 (telephonyRxModule->getHalVersionMajor() >= 3)) {
743 if (rxSourceDevice == 0 || txSinkDevice == 0) {
744 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100745 ALOGE("%s() no telephony Tx and/or RX device", __func__);
746 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100747 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100748 // createAudioPatchInternal now supports both HW / SW bridging
749 createRxPatch = true;
750 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100751 } else {
752 // If the RX device is on the primary HW module, then use legacy routing method for
753 // voice calls via setOutputDevice() on primary output.
754 // Otherwise, create two audio patches for TX and RX path.
755 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
756 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700757 // If the TX device is also on the primary HW module, setOutputDevice() will take care
758 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100759 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
760 (txSinkDevice != 0);
761 }
762 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
763 // Otherwise, create two audio patches for TX and RX path.
764 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200765 if (!hasPrimaryOutput()) {
766 ALOGW("%s() no primary output available", __func__);
767 return INVALID_OPERATION;
768 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530769 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700770 } else { // create RX path audio patch
David Li48b6a832024-07-01 13:14:10 +0000771 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800772 // If the TX device is on the primary HW module but RX device is
773 // on other HW module, SinkMetaData of telephony input should handle it
774 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700775 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700776 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100777 // terminate active capture if on the same HW module as the call TX source device
778 // FIXME: would be better to refine to only inputs whose profile connects to the
779 // call TX device but this information is not in the audio patch and logic here must be
780 // symmetric to the one in startInput()
781 for (const auto& activeDesc : mInputs.getActiveInputs()) {
782 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
783 closeActiveClients(activeDesc);
784 }
785 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200786 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800787 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100788 if (waitMs != nullptr) {
789 *waitMs = muteWaitMs;
790 }
791 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800792}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700793
Mikhail Naganov100f0122018-11-29 11:22:16 -0800794bool AudioPolicyManager::isDeviceOfModule(
795 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
796 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
797 if (module != 0) {
798 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
799 .indexOf(devDesc) != NAME_NOT_FOUND
800 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
801 .indexOf(devDesc) != NAME_NOT_FOUND;
802 }
803 return false;
804}
805
David Li48b6a832024-07-01 13:14:10 +0000806void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200807{
Francois Gaffie601801d2021-06-22 13:27:39 +0200808 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200809 const struct audio_port_config source = {
810 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
811 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
812 };
813 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100814
815 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent963dbcc2024-06-20 12:34:15 +0000816 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Li48b6a832024-07-01 13:14:10 +0000817 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100818 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
819 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200820 ALOGE_IF(mCallRxSourceClient == nullptr,
821 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200822}
823
Francois Gaffie601801d2021-06-22 13:27:39 +0200824void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200825{
Francois Gaffie601801d2021-06-22 13:27:39 +0200826 if (clientDesc == nullptr) {
827 return;
828 }
829 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
830 "%s error stopping audio source", __func__);
831 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200832}
833
834void AudioPolicyManager::connectTelephonyTxAudioSource(
835 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
836 uint32_t delayMs)
837{
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200839 if (srcDevice == nullptr || sinkDevice == nullptr) {
840 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
841 return;
842 }
843 PatchBuilder patchBuilder;
844 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
845 ALOGV("%s between source %s and sink %s", __func__,
846 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200847 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200848 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
849
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200850 struct audio_port_config source = {};
851 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100852 mCallTxSourceClient = new SourceClientDescriptor(
853 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurent963dbcc2024-06-20 12:34:15 +0000854 mCommunnicationStrategy, toVolumeSource(aa), true,
855 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100856 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
857
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200858 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
859 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200860 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
861 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200862 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
863 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200864 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200865 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200866}
867
Eric Laurente0720872014-03-11 09:30:41 -0700868void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700869{
870 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100871 // store previous phone state for management of sonification strategy below
872 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100873 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100874
875 if (mEngine->setPhoneState(state) != NO_ERROR) {
876 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700877 return;
878 }
François Gaffie2110e042015-03-24 08:41:51 +0100879 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700880 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700881 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700882 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800883 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700884 }
885
François Gaffie2110e042015-03-24 08:41:51 +0100886 /**
887 * Switching to or from incall state or switching between telephony and VoIP lead to force
888 * routing command.
889 */
Eric Laurent74b71512019-11-06 17:21:57 -0800890 bool force = ((isStateInCall(oldState) != isStateInCall(state))
891 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700892
893 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700894 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700895
Eric Laurente552edb2014-03-10 17:42:56 -0700896 int delayMs = 0;
897 if (isStateInCall(state)) {
898 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100899 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
900 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700901 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700902 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700903 // mute media and sonification strategies and delay device switch by the largest
904 // latency of any output where either strategy is active.
905 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100906 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
907 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
908 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700909 (delayMs < (int)desc->latency()*2)) {
910 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700911 }
François Gaffiec005e562018-11-06 15:04:49 +0100912 setStrategyMute(musicStrategy, true, desc);
913 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
914 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
915 nullptr, true /*fromCache*/).types());
916 setStrategyMute(sonificationStrategy, true, desc);
917 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
918 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
919 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700920 }
921 }
922
François Gaffiedb1755b2023-09-01 11:50:35 +0200923 if (state == AUDIO_MODE_IN_CALL) {
924 (void)updateCallRouting(false /*fromCache*/, delayMs);
925 } else {
926 if (oldState == AUDIO_MODE_IN_CALL) {
927 disconnectTelephonyAudioSource(mCallRxSourceClient);
928 disconnectTelephonyAudioSource(mCallTxSourceClient);
929 }
930 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100931 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
932 // force routing command to audio hardware when ending call
933 // even if no device change is needed
934 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
935 rxDevices = mPrimaryOutput->devices();
936 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530937 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700938 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700939 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700940
jiabin3ff8d7d2022-12-13 06:27:44 +0000941 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700942 // reevaluate routing on all outputs in case tracks have been started during the call
943 for (size_t i = 0; i < mOutputs.size(); i++) {
944 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100945 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000946 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
947 && desc->mPreferredAttrInfo != nullptr) {
948 // If the output is using preferred mixer attributes and the audio mode is not normal,
949 // the output need to reopen with default configuration.
950 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
951 continue;
952 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200953 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
954 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530955 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200956 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700957 }
958 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000959 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700960
Eric Laurent96d1dda2022-03-14 17:14:19 +0100961 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
962
Eric Laurente552edb2014-03-10 17:42:56 -0700963 if (isStateInCall(state)) {
964 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700965 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800966 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
968
969 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100970 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
971 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700972}
973
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700974audio_mode_t AudioPolicyManager::getPhoneState() {
975 return mEngine->getPhoneState();
976}
977
Eric Laurente0720872014-03-11 09:30:41 -0700978void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100979 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700980{
François Gaffie2110e042015-03-24 08:41:51 +0100981 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700982 if (config == mEngine->getForceUse(usage)) {
983 return;
984 }
Eric Laurente552edb2014-03-10 17:42:56 -0700985
François Gaffie2110e042015-03-24 08:41:51 +0100986 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
987 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
988 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700989 }
François Gaffie2110e042015-03-24 08:41:51 +0100990 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
991 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
992 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700993
994 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700995 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800996
Eric Laurent22fcda22019-05-17 16:28:47 -0700997 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
998 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800999 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001000 }
1001
Eric Laurentdc462862016-07-19 12:29:53 -07001002 //FIXME: workaround for truncated touch sounds
1003 // to be removed when the problem is handled by system UI
1004 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001005 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1006 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1007 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001008
1009 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001010 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001011}
1012
Eric Laurente0720872014-03-11 09:30:41 -07001013void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001014{
1015 ALOGV("setSystemProperty() property %s, value %s", property, value);
1016}
1017
Dorin Drimusecc9f422022-03-09 17:57:40 +01001018// Find an MSD output profile compatible with the parameters passed.
1019// When "directOnly" is set, restrict search to profiles for direct outputs.
1020sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1021 const DeviceVector& devices,
1022 uint32_t samplingRate,
1023 audio_format_t format,
1024 audio_channel_mask_t channelMask,
1025 audio_output_flags_t flags,
1026 bool directOnly)
1027{
1028 flags = getRelevantFlags(flags, directOnly);
1029
1030 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1031 if (msdModule != nullptr) {
1032 // for the msd module check if there are patches to the output devices
1033 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1034 HwModuleCollection modules;
1035 modules.add(msdModule);
1036 return searchCompatibleProfileHwModules(
1037 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1038 flags, directOnly);
1039 }
1040 }
1041 return nullptr;
1042}
1043
Michael Chana94fbb22018-04-24 14:31:19 +10001044// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1045// search to profiles for direct outputs.
1046sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001047 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001048 uint32_t samplingRate,
1049 audio_format_t format,
1050 audio_channel_mask_t channelMask,
1051 audio_output_flags_t flags,
1052 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001053{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001054 flags = getRelevantFlags(flags, directOnly);
1055
1056 return searchCompatibleProfileHwModules(
1057 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1058}
1059
1060audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1061 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001062 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 // only retain flags that will drive the direct output profile selection
1064 // if explicitly requested
1065 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001066 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1068 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001069 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001070 return flags;
1071}
Eric Laurent861a6282015-05-18 15:40:16 -07001072
Dorin Drimusecc9f422022-03-09 17:57:40 +01001073sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1074 const HwModuleCollection& hwModules,
1075 const DeviceVector& devices,
1076 uint32_t samplingRate,
1077 audio_format_t format,
1078 audio_channel_mask_t channelMask,
1079 audio_output_flags_t flags,
1080 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001081 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001082 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001083 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001084 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001085 samplingRate, NULL /*updatedSamplingRate*/,
1086 format, NULL /*updatedFormat*/,
1087 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001088 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001089 continue;
1090 }
1091 // reject profiles not corresponding to a device currently available
1092 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1093 continue;
1094 }
1095 // reject profiles if connected device does not support codec
1096 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1097 continue;
1098 }
1099 if (!directOnly) {
1100 return curProfile;
1101 }
1102
1103 // when searching for direct outputs, if several profiles are compatible, give priority
1104 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001105 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001106 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001107 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001108 }
1109 profile = curProfile;
1110 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1111 break;
1112 }
Eric Laurente552edb2014-03-10 17:42:56 -07001113 }
1114 }
Eric Laurent861a6282015-05-18 15:40:16 -07001115 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001116}
1117
Eric Laurentfa0f6742021-08-17 18:39:44 +02001118sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001119 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001120{
1121 for (const auto& hwModule : mHwModules) {
1122 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001123 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001124 continue;
1125 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001126 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001127 // reject profiles not corresponding to a device currently available
1128 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1129 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1130 continue;
1131 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001132 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1133 != devices.size()) {
1134 continue;
1135 }
1136 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001137 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1138 return curProfile;
1139 }
1140 }
1141 return nullptr;
1142}
1143
Eric Laurentf4e63452017-11-06 19:31:46 +00001144audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001145{
François Gaffiec005e562018-11-06 15:04:49 +01001146 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001147
1148 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1149 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1150 // format, flags, etc. This may result in some discrepancy for functions that utilize
1151 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1152 // and AudioSystem::getOutputSamplingRate().
1153
François Gaffie11d30102018-11-02 16:09:09 +01001154 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001155 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1156 if (stream == AUDIO_STREAM_MUSIC &&
1157 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1158 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1159 }
1160 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001161
François Gaffie11d30102018-11-02 16:09:09 +01001162 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1163 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001164 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001165}
1166
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001167status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1168 const audio_attributes_t *srcAttr,
1169 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001170{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001171 if (srcAttr != NULL) {
1172 if (!isValidAttributes(srcAttr)) {
1173 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1174 __func__,
1175 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1176 srcAttr->tags);
1177 return BAD_VALUE;
1178 }
1179 *dstAttr = *srcAttr;
1180 } else {
1181 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1182 ALOGE("%s: invalid stream type", __func__);
1183 return BAD_VALUE;
1184 }
François Gaffiec005e562018-11-06 15:04:49 +01001185 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001186 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001187
1188 // Only honor audibility enforced when required. The client will be
1189 // forced to reconnect if the forced usage changes.
1190 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001191 dstAttr->flags = static_cast<audio_flags_mask_t>(
1192 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001193 }
1194
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001195 return NO_ERROR;
1196}
1197
Kevin Rocard153f92d2018-12-18 18:33:28 -08001198status_t AudioPolicyManager::getOutputForAttrInt(
1199 audio_attributes_t *resultAttr,
1200 audio_io_handle_t *output,
1201 audio_session_t session,
1202 const audio_attributes_t *attr,
1203 audio_stream_type_t *stream,
1204 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001205 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001206 audio_output_flags_t *flags,
1207 audio_port_handle_t *selectedDeviceId,
1208 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001209 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001210 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001211 bool *isSpatialized,
1212 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001213{
François Gaffiec005e562018-11-06 15:04:49 +01001214 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001215 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001216 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001217 const sp<DeviceDescriptor> requestedDevice =
1218 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1219
Eric Laurent8a1095a2019-11-08 14:44:16 -08001220 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001221 *isSpatialized = false;
1222
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001223 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1224 if (status != NO_ERROR) {
1225 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001226 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001227 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001228 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001229 }
François Gaffiec005e562018-11-06 15:04:49 +01001230 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001231
François Gaffiec005e562018-11-06 15:04:49 +01001232 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1233 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001234
Oscar Azucena873d10f2023-01-12 18:34:42 -08001235 bool usePrimaryOutputFromPolicyMixes = false;
1236
Kevin Rocard153f92d2018-12-18 18:33:28 -08001237 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1238 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1239 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001240 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001241 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1242 .channel_mask = config->channel_mask,
1243 .format = config->format,
1244 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001245 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001246 mAvailableOutputDevices, requestedDevice, primaryMix,
1247 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001248 if (status != OK) {
1249 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001250 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001251
Kevin Rocard153f92d2018-12-18 18:33:28 -08001252 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001253 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungced57302024-08-14 11:37:57 -07001254 && (!audio_is_linear_pcm(config->format) ||
1255 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001256 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001257 return BAD_VALUE;
1258 }
1259 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001260 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001261 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1262 primaryMix->mDeviceAddress,
1263 AUDIO_FORMAT_DEFAULT);
1264 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001265 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001266 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1267 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001268 // if a direct output can be opened to deliver the track's multi-channel content to the
1269 // output rather than being downmixed by the primary output, then use this direct
1270 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1271 // mix.
1272 bool tryDirectForChannelMask = policyDesc != nullptr
1273 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1274 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001275 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001276 audio_io_handle_t newOutput;
1277 status = openDirectOutput(
1278 *stream, session, config,
1279 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001280 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001281 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001282 policyDesc = mOutputs.valueFor(newOutput);
1283 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001284 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001285 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001286 policyDesc = nullptr;
1287 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001288 }
1289 if (policyDesc != nullptr) {
1290 policyDesc->mPolicyMix = primaryMix;
1291 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001292 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1293 : AUDIO_PORT_HANDLE_NONE;
1294 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1295 // Remove direct flag as it is not on a direct output.
1296 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1297 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001298
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001299 ALOGV("getOutputForAttr() returns output %d", *output);
1300 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1301 *outputType = API_OUT_MIX_PLAYBACK;
1302 } else {
1303 *outputType = API_OUTPUT_LEGACY;
1304 }
1305 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001306 } else {
1307 if (policyMixDevice != nullptr) {
1308 ALOGE("%s, try to use primary mix but no output found", __func__);
1309 return INVALID_OPERATION;
1310 }
1311 // Fallback to default engine selection as the selected primary mix device is not
1312 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001313 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001314 }
François Gaffiec005e562018-11-06 15:04:49 +01001315 // Virtual sources must always be dynamicaly or explicitly routed
1316 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1317 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1318 return BAD_VALUE;
1319 }
1320 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1321 // in order to let the choice of the order to future vendor engine
1322 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001323
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001324 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001325 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001326 }
1327
Nadav Barb2f18162018-07-18 13:01:53 +03001328 // Set incall music only if device was explicitly set, and fallback to the device which is
1329 // chosen by the engine if not.
1330 // FIXME: provide a more generic approach which is not device specific and move this back
1331 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001332 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001333 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001334 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001335 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001336 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001337 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001338 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001339 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001340 }
1341 }
1342
François Gaffiec005e562018-11-06 15:04:49 +01001343 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1344 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1345 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001346
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001347 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001348 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001349 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001350 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001351 ALOGV("%s() Using MSD devices %s instead of devices %s",
1352 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001353 } else {
1354 *output = AUDIO_IO_HANDLE_NONE;
1355 }
1356 }
1357 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001358 sp<PreferredMixerAttributesInfo> info = nullptr;
1359 if (outputDevices.size() == 1) {
1360 info = getPreferredMixerAttributesInfo(
1361 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001362 mEngine->getProductStrategyForAttributes(*resultAttr),
1363 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001364 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1365 // and it is currently active.
1366 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001367 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001368 info = nullptr;
1369 }
jiabin220eea12024-05-17 17:55:20 +00001370 if (com::android::media::audioserver::
1371 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1372 if (info != nullptr && info->getUid() == uid &&
1373 info->configMatches(*config) &&
1374 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1375 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1376 [this, &outputDevices](audio_usage_t usage) {
1377 return mOutputs.isUsageActiveOnDevice(
1378 usage, outputDevices[0]); }))) {
1379 // Bit-perfect request is not allowed when the phone mode is not normal or
1380 // there is any higher priority user case active.
1381 return INVALID_OPERATION;
1382 }
1383 }
jiabina84c3d32022-12-02 18:59:55 +00001384 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001385 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001386 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001387 // The client will be active if the client is currently preferred mixer owner and the
1388 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001389 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001390 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001391 && info->getUid() == uid
1392 && *output != AUDIO_IO_HANDLE_NONE
1393 // When bit-perfect output is selected for the preferred mixer attributes owner,
1394 // only need to consider the config matches.
1395 && mOutputs.valueFor(*output)->isConfigurationMatched(
1396 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001397
1398 if (*isBitPerfect) {
1399 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1400 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001401 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001402 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001403 AudioProfileVector profiles;
1404 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1405 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001406 const auto channels = profiles[0]->getChannels();
1407 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1408 config->channel_mask = *channels.begin();
1409 }
1410 const auto sampleRates = profiles[0]->getSampleRates();
1411 if (!sampleRates.empty() &&
1412 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1413 config->sample_rate = *sampleRates.begin();
1414 }
jiabinf1c73972022-04-14 16:28:52 -07001415 config->format = profiles[0]->getFormat();
1416 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001417 return INVALID_OPERATION;
1418 }
Paul McLeanaa981192015-03-21 09:55:15 -07001419
François Gaffiec005e562018-11-06 15:04:49 +01001420 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001421 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001422 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001423 *selectedDeviceId = outputDevice->getId();
1424 break;
1425 }
1426 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001427
Eric Laurent8a1095a2019-11-08 14:44:16 -08001428 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1429 *outputType = API_OUTPUT_TELEPHONY_TX;
1430 } else {
1431 *outputType = API_OUTPUT_LEGACY;
1432 }
1433
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001434 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1435
1436 return NO_ERROR;
1437}
1438
1439status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1440 audio_io_handle_t *output,
1441 audio_session_t session,
1442 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001443 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001444 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001445 audio_output_flags_t *flags,
1446 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001447 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001448 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001449 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001450 bool *isSpatialized,
1451 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001452{
1453 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1454 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1455 return INVALID_OPERATION;
1456 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001457 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001458 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001459 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001460 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001461 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001462 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001463 const sp<DeviceDescriptor> requestedDevice =
1464 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1465
1466 // Prevent from storing invalid requested device id in clients
1467 const audio_port_handle_t sanitizedRequestedPortId =
1468 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1469 *selectedDeviceId = sanitizedRequestedPortId;
1470
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001471 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001472 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001473 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1474 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001475 if (status != NO_ERROR) {
1476 return status;
1477 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001478 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001479 if (secondaryOutputs != nullptr) {
1480 for (auto &secondaryMix : secondaryMixes) {
1481 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1482 if (outputDesc != nullptr &&
1483 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1484 secondaryOutputs->push_back(outputDesc->mIoHandle);
1485 weakSecondaryOutputDescs.push_back(outputDesc);
1486 }
1487 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001488 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001489
Eric Laurent8fc147b2018-07-22 19:13:55 -07001490 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001491 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001492 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001493 };
jiabin4ef93452019-09-10 14:29:54 -07001494 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001495
Eric Laurentc209fe42020-06-05 18:11:23 -07001496 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001497 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001498 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001499 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001500 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001501 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001502 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001503 std::move(weakSecondaryOutputDescs),
1504 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001505 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001506
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001507 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1508 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001509
Eric Laurente83b55d2014-11-14 10:06:21 -08001510 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001511}
1512
Eric Laurentc529cf62020-04-17 18:19:10 -07001513status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1514 audio_session_t session,
1515 const audio_config_t *config,
1516 audio_output_flags_t flags,
1517 const DeviceVector &devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001518 audio_io_handle_t *output,
1519 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001520
1521 *output = AUDIO_IO_HANDLE_NONE;
1522
1523 // skip direct output selection if the request can obviously be attached to a mixed output
1524 // and not explicitly requested
1525 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1526 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1527 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1528 return NAME_NOT_FOUND;
1529 }
1530
1531 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1532 // This prevents creating an offloaded track and tearing it down immediately after start
1533 // when audioflinger detects there is an active non offloadable effect.
1534 // FIXME: We should check the audio session here but we do not have it in this context.
1535 // This may prevent offloading in rare situations where effects are left active by apps
1536 // in the background.
1537 sp<IOProfile> profile;
1538 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1539 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1540 profile = getProfileForOutput(
1541 devices, config->sample_rate, config->format, config->channel_mask,
1542 flags, true /* directOnly */);
1543 }
1544
1545 if (profile == nullptr) {
1546 return NAME_NOT_FOUND;
1547 }
1548
1549 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1550 for (size_t i = 0; i < mOutputs.size(); i++) {
1551 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1552 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1553 // reuse direct output if currently open by the same client
1554 // and configured with same parameters
1555 if ((config->sample_rate == desc->getSamplingRate()) &&
1556 (config->format == desc->getFormat()) &&
1557 (config->channel_mask == desc->getChannelMask()) &&
1558 (session == desc->mDirectClientSession)) {
1559 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301560 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001561 mOutputs.keyAt(i), session);
1562 *output = mOutputs.keyAt(i);
1563 return NO_ERROR;
1564 }
1565 }
1566 }
1567
1568 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001569 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301570 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1571 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001572 return NAME_NOT_FOUND;
1573 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1574 // MMAP gracefully handles lack of an exclusive track resource by mixing
1575 // above the audio framework. For AAudio to know that the limit is reached,
1576 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301577 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1578 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001579 return NAME_NOT_FOUND;
1580 } else {
1581 // Close outputs on this profile, if available, to free resources for this request
1582 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1583 const auto desc = mOutputs.valueAt(i);
1584 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301585 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1586 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001587 closeOutput(desc->mIoHandle);
1588 }
1589 }
1590 }
1591 }
1592
1593 // Unable to close streams to find free resources for this request
1594 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301595 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1596 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001597 return NAME_NOT_FOUND;
1598 }
1599
Atneya Nairb16666a2023-12-11 20:18:33 -08001600 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001601
Michael Chan6fb34492020-12-08 15:44:49 +11001602 // An MSD patch may be using the only output stream that can service this request. Release
1603 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001604 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001605
Eric Laurentf1f22e72021-07-13 14:04:14 +02001606 status_t status =
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001607 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1608 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001609
1610 // only accept an output with the requested parameters
1611 if (status != NO_ERROR ||
1612 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1613 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1614 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1615 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1616 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1617 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1618 config->channel_mask, outputDesc->getChannelMask());
1619 if (*output != AUDIO_IO_HANDLE_NONE) {
1620 outputDesc->close();
1621 }
1622 // fall back to mixer output if possible when the direct output could not be open
1623 if (audio_is_linear_pcm(config->format) &&
1624 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1625 return NAME_NOT_FOUND;
1626 }
1627 *output = AUDIO_IO_HANDLE_NONE;
1628 return BAD_VALUE;
1629 }
1630 outputDesc->mDirectOpenCount = 1;
1631 outputDesc->mDirectClientSession = session;
1632
1633 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001634 setOutputDevices(__func__, outputDesc,
1635 devices,
1636 true,
1637 0,
1638 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001639 mPreviousOutputs = mOutputs;
1640 ALOGV("%s returns new direct output %d", __func__, *output);
1641 mpClientInterface->onAudioPortListUpdate();
1642 return NO_ERROR;
1643}
1644
François Gaffie11d30102018-11-02 16:09:09 +01001645audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1646 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001647 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001648 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001649 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001650 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001651 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001652 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001653 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001654{
Andy Hungc88b0642018-04-27 15:42:35 -07001655 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001656
jiabine375d412019-02-26 12:54:53 -08001657 // Discard haptic channel mask when forcing muting haptic channels.
1658 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001659 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1660 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001661
Eric Laurente552edb2014-03-10 17:42:56 -07001662 // open a direct output if required by specified parameters
1663 //force direct flag if offload flag is set: offloading implies a direct output stream
1664 // and all common behaviors are driven by checking only the direct flag
1665 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001666 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1667 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001668 }
Nadav Bar766fb022018-01-07 12:18:03 +02001669 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1670 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001671 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001672
1673 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1674
Eric Laurente83b55d2014-11-14 10:06:21 -08001675 // only allow deep buffering for music stream type
1676 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001677 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001678 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001679 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001680 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1681 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001682 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001683 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001684 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001685 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001686 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001687 audio_is_linear_pcm(config->format) &&
1688 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001689 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001690 AUDIO_OUTPUT_FLAG_DIRECT);
1691 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001692 }
Eric Laurente552edb2014-03-10 17:42:56 -07001693
Carter Hsua3abb402021-10-26 11:11:20 +08001694 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1695 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1696 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1697 }
1698
Eric Laurentf9230d52024-01-26 18:49:09 +01001699 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001700 // was specified and offload or direct playback is not explicitly requested, and there is no
1701 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001702 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001703 if (mSpatializerOutput != nullptr &&
1704 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1705 prefMixerConfigInfo == nullptr &&
1706 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1707 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001708 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001709 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001710 }
1711
Eric Laurentc529cf62020-04-17 18:19:10 -07001712 audio_config_t directConfig = *config;
1713 directConfig.channel_mask = channelMask;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001714
1715 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1716 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001717 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001718 return output;
1719 }
1720
Eric Laurent14cbfca2016-03-17 09:42:16 -07001721 // A request for HW A/V sync cannot fallback to a mixed output because time
1722 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001723 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001724 return AUDIO_IO_HANDLE_NONE;
1725 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001726 // A request for Tuner cannot fallback to a mixed output
1727 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1728 return AUDIO_IO_HANDLE_NONE;
1729 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001730
Eric Laurente552edb2014-03-10 17:42:56 -07001731 // ignoring channel mask due to downmix capability in mixer
1732
1733 // open a non direct output
1734
1735 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001736 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001737 // get which output is suitable for the specified stream. The actual
1738 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001739 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001740 if (prefMixerConfigInfo != nullptr) {
1741 for (audio_io_handle_t outputHandle : outputs) {
1742 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1743 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1744 output = outputHandle;
1745 break;
1746 }
1747 }
1748 if (output == AUDIO_IO_HANDLE_NONE) {
1749 // No output open with the preferred profile. Open a new one.
1750 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1751 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1752 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1753 config.format = prefMixerConfigInfo->getConfigBase().format;
1754 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1755 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1756 &config, prefMixerConfigInfo->getFlags());
1757 if (preferredOutput == nullptr) {
1758 ALOGE("%s failed to open output with preferred mixer config", __func__);
1759 } else {
1760 output = preferredOutput->mIoHandle;
1761 }
1762 }
1763 } else {
1764 // at this stage we should ignore the DIRECT flag as no direct output could be
1765 // found earlier
1766 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001767 if (com::android::media::audioserver::
1768 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1769 // If the preferred mixer attributes is null, do not select the bit-perfect output
1770 // unless the bit-perfect output is the only output.
1771 // The bit-perfect output can exist while the passed in preferred mixer attributes
1772 // info is null when it is a high priority client. The high priority clients are
1773 // ringtone or alarm, which is not a bit-perfect use case.
1774 size_t i = 0;
1775 while (i < outputs.size() && outputs.size() > 1) {
1776 auto desc = mOutputs.valueFor(outputs[i]);
1777 // The output descriptor must not be null here.
1778 if (desc->isBitPerfect()) {
1779 outputs.removeItemsAt(i);
1780 } else {
1781 i += 1;
1782 }
1783 }
1784 }
jiabina84c3d32022-12-02 18:59:55 +00001785 output = selectOutput(
1786 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1787 }
Eric Laurente552edb2014-03-10 17:42:56 -07001788 }
François Gaffie11d30102018-11-02 16:09:09 +01001789 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001790 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001791 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001792
Eric Laurente552edb2014-03-10 17:42:56 -07001793 return output;
1794}
1795
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001796sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001797 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1798 mAvailableInputDevices);
1799 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1800}
1801
1802DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1803 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1804 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001805}
1806
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001807const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001808 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001809 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1810 if (msdModule != 0) {
1811 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1812 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1813 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1814 const struct audio_port_config *source = &patch->mPatch.sources[j];
1815 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1816 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001817 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001818 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001819 }
1820 }
1821 }
1822 return msdPatches;
1823}
1824
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001825bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1826 ssize_t index = mAudioPatches.indexOfKey(handle);
1827 if (index < 0) {
1828 return false;
1829 }
1830 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1831 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1832 if (msdModule == nullptr) {
1833 return false;
1834 }
1835 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1836 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1837 return true;
1838 }
1839 index = getMsdOutputPatches().indexOfKey(handle);
1840 if (index < 0) {
1841 return false;
1842 }
1843 return true;
1844}
1845
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001846status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1847 const InputProfileCollection &inputProfiles,
1848 const OutputProfileCollection &outputProfiles,
1849 const sp<DeviceDescriptor> &sourceDevice,
1850 const sp<DeviceDescriptor> &sinkDevice,
1851 AudioProfileVector& sourceProfiles,
1852 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001853 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001854 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001855 return NO_INIT;
1856 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001857 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001858 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001859 return NO_INIT;
1860 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001861 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001862 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1863 inProfile->supportsDevice(sourceDevice)) {
1864 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001865 }
1866 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001867 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001868 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001869 outProfile->supportsDevice(sinkDevice)) {
1870 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001871 }
1872 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001873 return NO_ERROR;
1874}
1875
1876status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1877 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1878 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1879{
Dean Wheatley16809da2022-12-09 14:55:46 +11001880 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1881 static const std::vector<audio_format_t> formatsOrder = {{
1882 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001883 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1884 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001885 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1886 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1887 // preferred).
1888 std::vector<audio_channel_mask_t> masks = {{
1889 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1890 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1891 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1892 // insert index masks (higher counts most preferred) as preferred over position masks
1893 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1894 masks.insert(
1895 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1896 }
1897 return masks;
1898 }();
1899
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001900 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001901 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1902 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001904 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1905 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001906 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 }
1908 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1909 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1910 sinkConfig->format = bestSinkConfig.format;
1911 // For encoded streams force direct flag to prevent downstream mixing.
1912 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1913 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001914 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1915 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001916 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001917 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1918 // raw and IEC61937 framed streams.
1919 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1920 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1921 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001922 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1923 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001924 sourceConfig->channel_mask =
1925 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1926 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1927 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001928 sourceConfig->format = bestSinkConfig.format;
1929 // Copy input stream directly without any processing (e.g. resampling).
1930 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1931 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1932 if (hwAvSync) {
1933 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1934 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1935 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1936 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1937 }
1938 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1939 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1940 sinkConfig->config_mask |= config_mask;
1941 sourceConfig->config_mask |= config_mask;
1942 return NO_ERROR;
1943}
1944
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001945PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1946 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001947{
1948 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001949 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1950 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1951 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1952 if (deviceModule == nullptr) {
1953 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1954 return patchBuilder;
1955 }
1956 const InputProfileCollection inputProfiles = msdIsSource ?
1957 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1958 const OutputProfileCollection outputProfiles = msdIsSource ?
1959 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1960
1961 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1962 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1963 device : getMsdAudioOutDevices().itemAt(0);
1964 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1965
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001966 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1967 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001968 AudioProfileVector sourceProfiles;
1969 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001970 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1971 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001972 for (auto hwAvSync : { true, false }) {
1973 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1974 sourceProfiles, sinkProfiles) != NO_ERROR) {
1975 continue;
1976 }
1977 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1978 &sinkConfig) == NO_ERROR) {
1979 // Found a matching config. Re-create PatchBuilder with this config.
1980 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1981 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001982 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001983 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001984 " supporting PCM format conversion.", __func__);
1985 return patchBuilder;
1986}
1987
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001988status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001989 DeviceVector devices;
1990 if (outputDevices != nullptr && outputDevices->size() > 0) {
1991 devices.add(*outputDevices);
1992 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001993 // Use media strategy for unspecified output device. This should only
1994 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1995 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001996 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001997 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001998 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001999 }
Michael Chan6fb34492020-12-08 15:44:49 +11002000 std::vector<PatchBuilder> patchesToCreate;
2001 for (auto i = 0u; i < devices.size(); ++i) {
2002 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002003 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002004 }
2005 // Retain only the MSD patches associated with outputDevices request.
2006 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002007 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002008 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2009 auto retainedPatch = false;
2010 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2011 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2012 patchesToRemove.removeItemsAt(i);
2013 retainedPatch = true;
2014 break;
2015 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002016 }
Michael Chan6fb34492020-12-08 15:44:49 +11002017 if (retainedPatch) {
2018 it = patchesToCreate.erase(it);
2019 continue;
2020 }
2021 ++it;
2022 }
2023 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2024 return NO_ERROR;
2025 }
2026 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2027 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002028 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002029 }
Michael Chan6fb34492020-12-08 15:44:49 +11002030 status_t status = NO_ERROR;
2031 for (const auto &p : patchesToCreate) {
2032 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2033 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2034 char message[256];
2035 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2036 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2037 currStatus == NO_ERROR ? "Success" : "Error",
2038 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2039 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2040 if (currStatus == NO_ERROR) {
2041 ALOGD("%s", message);
2042 } else {
2043 ALOGE("%s", message);
2044 if (status == NO_ERROR) {
2045 status = currStatus;
2046 }
2047 }
2048 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002049 return status;
2050}
2051
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002052void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2053 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002054 for (size_t i = 0; i < msdPatches.size(); i++) {
2055 const auto& patch = msdPatches[i];
2056 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2057 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2058 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2059 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2060 releaseAudioPatch(patch->getHandle(), mUidCached);
2061 break;
2062 }
2063 }
2064 }
2065}
2066
Dorin Drimus94d94412022-02-02 09:05:02 +01002067bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002068 DeviceVector devicesToCheck =
2069 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002070 AudioPatchCollection msdPatches = getMsdOutputPatches();
2071 for (size_t i = 0; i < msdPatches.size(); i++) {
2072 const auto& patch = msdPatches[i];
2073 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2074 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2075 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2076 const auto& foundDevice = devicesToCheck.getDevice(
2077 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2078 if (foundDevice != nullptr) {
2079 devicesToCheck.remove(foundDevice);
2080 if (devicesToCheck.isEmpty()) {
2081 return true;
2082 }
2083 }
2084 }
2085 }
2086 }
2087 return false;
2088}
2089
Eric Laurente0720872014-03-11 09:30:41 -07002090audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002091 audio_output_flags_t flags,
2092 audio_format_t format,
2093 audio_channel_mask_t channelMask,
2094 uint32_t samplingRate,
2095 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002096{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002097 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2098 "%s called with format %#x", __func__, format);
2099
jiabinebb6af42020-06-09 17:31:17 -07002100 // Return the output that haptic-generating attached to when 1) session id is specified,
2101 // 2) haptic-generating effect exists for given session id and 3) the output that
2102 // haptic-generating effect attached to is in given outputs.
2103 if (sessionId != AUDIO_SESSION_NONE) {
2104 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2105 sessionId, FX_IID_HAPTICGENERATOR);
2106 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2107 return hapticGeneratingOutput;
2108 }
2109 }
2110
Eric Laurent16c66dd2019-05-01 17:54:10 -07002111 // Flags disqualifying an output: the match must happen before calling selectOutput()
2112 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2113 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2114
2115 // Flags expressing a functional request: must be honored in priority over
2116 // other criteria
2117 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2118 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002119 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2120 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002121 // Flags expressing a performance request: have lower priority than serving
2122 // requested sampling rate or channel mask
2123 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2124 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2125 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2126
2127 const audio_output_flags_t functionalFlags =
2128 (audio_output_flags_t)(flags & kFunctionalFlags);
2129 const audio_output_flags_t performanceFlags =
2130 (audio_output_flags_t)(flags & kPerformanceFlags);
2131
2132 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2133
Eric Laurente552edb2014-03-10 17:42:56 -07002134 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002135 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002136 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002137 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002138 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002139 // with tiebreak preferring the minimum number of extra functional flags
2140 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002141 // 3: the output supporting the exact channel mask
2142 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002143 // 5: the output with the highest sampling rate if the requested sample rate is
2144 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002145 // 6: the output with the highest number of requested performance flags
2146 // 7: the output with the bit depth the closest to the requested one
2147 // 8: the primary output
2148 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002149
Eric Laurent16c66dd2019-05-01 17:54:10 -07002150 // matching criteria values in priority order for best matching output so far
2151 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002152
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002153 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002154 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2155 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2156 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002157
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002158 for (audio_io_handle_t output : outputs) {
2159 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002160 // matching criteria values in priority order for current output
2161 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002162
Eric Laurent16c66dd2019-05-01 17:54:10 -07002163 if (outputDesc->isDuplicated()) {
2164 continue;
2165 }
2166 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2167 continue;
2168 }
Eric Laurent8838a382014-09-08 16:44:28 -07002169
Eric Laurent16c66dd2019-05-01 17:54:10 -07002170 // If haptic channel is specified, use the haptic output if present.
2171 // When using haptic output, same audio format and sample rate are required.
2172 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002173 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002174 // skip if haptic channel specified but output does not support it, or output support haptic
2175 // but there is no haptic channel requested AND no orphan haptic effect exist
2176 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2177 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002178 continue;
2179 }
Shunkai Yao808da212024-04-05 22:50:56 +00002180 // In the case of audio-coupled-haptic playback, there is no format conversion and
2181 // resampling in the framework, same format/channel/sampleRate for client and the output
2182 // thread is required. In the case of HapticGenerator effect, do not require format
2183 // matching.
2184 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2185 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002186 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002187 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 }
2189
2190 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002191 const int matchingFunctionalFlags =
2192 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2193 const int totalFunctionalFlags =
2194 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2195 // Prefer matching functional flags, but subtract unnecessary functional flags.
2196 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002197
2198 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002199 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2200 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002201 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2202 channelCount <= outputChannelCount) {
2203 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002204 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2205 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002206 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002207 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002208 currentMatchCriteria[3] = outputChannelCount;
2209 }
2210
2211 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002212 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002213 int diff; // avoid unsigned integer overflow.
2214 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2215
2216 // prefer the closest output sampling rate greater than or equal to target
2217 // if none exists, prefer the closest output sampling rate less than target.
2218 //
2219 // criteria is offset to make non-negative.
2220 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002221 }
2222
2223 // performance flags match
2224 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2225
2226 // format match
2227 if (format != AUDIO_FORMAT_INVALID) {
2228 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002229 PolicyAudioPort::kFormatDistanceMax -
2230 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 }
2232
2233 // primary output match
2234 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2235
2236 // compare match criteria by priority then value
2237 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2238 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2239 bestMatchCriteria = currentMatchCriteria;
2240 bestOutput = output;
2241
2242 std::stringstream result;
2243 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2244 std::ostream_iterator<int>(result, " "));
2245 ALOGV("%s new bestOutput %d criteria %s",
2246 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002247 }
2248 }
2249
Eric Laurent16c66dd2019-05-01 17:54:10 -07002250 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002251}
2252
Eric Laurent8fc147b2018-07-22 19:13:55 -07002253status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002254{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002255 ALOGV("%s portId %d", __FUNCTION__, portId);
2256
2257 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2258 if (outputDesc == 0) {
2259 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002260 return BAD_VALUE;
2261 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002262 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002263
Eric Laurent8fc147b2018-07-22 19:13:55 -07002264 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002265 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002266
jiabin220eea12024-05-17 17:55:20 +00002267 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2268 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2269 && outputDesc->isBitPerfect()) {
2270 // Usually, APM selects bit-perfect output for high priority use cases only when
2271 // bit-perfect output is the only output that can be routed to the selected device.
2272 // However, here is no need to play high priority use cases such as ringtone and alarm
2273 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2274 // can attach to new output.
2275 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2276 __func__, client->stream());
2277 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2278 return DEAD_OBJECT;
2279 }
2280
Eric Laurent733ce942017-12-07 12:18:25 -08002281 status_t status = outputDesc->start();
2282 if (status != NO_ERROR) {
2283 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002284 }
2285
Eric Laurent97ac8712018-07-27 18:59:02 -07002286 uint32_t delayMs;
2287 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002288
2289 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002290 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002291 if (status == DEAD_OBJECT) {
2292 sp<SwAudioOutputDescriptor> desc =
2293 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2294 if (desc == nullptr) {
2295 // This is not common, it may indicate something wrong with the HAL.
2296 ALOGE("%s unable to open output with default config", __func__);
2297 return status;
2298 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002299 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002300 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002301 }
jiabina84c3d32022-12-02 18:59:55 +00002302
2303 // If the client is the first one active on preferred mixer parameters, reopen the output
2304 // if the current mixer parameters doesn't match the preferred one.
2305 if (outputDesc->devices().size() == 1) {
2306 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2307 outputDesc->devices()[0]->getId(), client->strategy());
2308 if (info != nullptr && info->getUid() == client->uid()) {
2309 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2310 info->getConfigBase(), info->getFlags())) {
2311 stopSource(outputDesc, client);
2312 outputDesc->stop();
2313 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2314 config.channel_mask = info->getConfigBase().channel_mask;
2315 config.sample_rate = info->getConfigBase().sample_rate;
2316 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002317 sp<SwAudioOutputDescriptor> desc =
2318 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2319 if (desc == nullptr) {
2320 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002321 }
jiabin220eea12024-05-17 17:55:20 +00002322 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002323 // Intentionally return error to let the client side resending request for
2324 // creating and starting.
2325 return DEAD_OBJECT;
2326 }
2327 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002328 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002329 // If it is first bit-perfect client, reroute all clients that will be routed to
2330 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2331 PortHandleVector clientsToInvalidate;
2332 for (size_t i = 0; i < mOutputs.size(); i++) {
2333 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002334 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002335 continue;
2336 }
2337 for (const auto& c : mOutputs[i]->getClientIterable()) {
2338 clientsToInvalidate.push_back(c->portId());
2339 }
2340 }
2341 if (!clientsToInvalidate.empty()) {
2342 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2343 __func__);
2344 mpClientInterface->invalidateTracks(clientsToInvalidate);
2345 }
2346 }
jiabina84c3d32022-12-02 18:59:55 +00002347 }
2348 }
2349
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002350 if (client->hasPreferredDevice()) {
2351 // playback activity with preferred device impacts routing occurred, inform upper layers
2352 mpClientInterface->onRoutingUpdated();
2353 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002354 if (delayMs != 0) {
2355 usleep(delayMs * 1000);
2356 }
2357
jiabin220eea12024-05-17 17:55:20 +00002358 if (status == NO_ERROR &&
2359 outputDesc->mPreferredAttrInfo != nullptr &&
2360 outputDesc->isBitPerfect() &&
2361 com::android::media::audioserver::
2362 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2363 // A new client is started on bit-perfect output, update all clients internal mute.
2364 updateClientsInternalMute(outputDesc);
2365 }
2366
Eric Laurentc75307b2015-03-17 15:29:32 -07002367 return status;
2368}
2369
Eric Laurent96d1dda2022-03-14 17:14:19 +01002370bool AudioPolicyManager::isLeUnicastActive() const {
2371 if (isInCall()) {
2372 return true;
2373 }
2374 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2375}
2376
2377bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2378 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2379 return false;
2380 }
2381 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2382 ALOGV("%s active %d", __func__, active);
2383 return active;
2384}
2385
Eric Laurent97ac8712018-07-27 18:59:02 -07002386status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2387 const sp<TrackClientDescriptor>& client,
2388 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002389{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002390 // cannot start playback of STREAM_TTS if any other output is being used
2391 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002392
2393 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002394 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002395 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002396 auto clientStrategy = client->strategy();
2397 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002398 if (stream == AUDIO_STREAM_TTS) {
2399 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002400 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002401 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002402 return INVALID_OPERATION;
2403 } else {
2404 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2405 }
2406 } else {
2407 // some playback other than beacon starts
2408 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2409 }
2410
Eric Laurent77305a62016-07-25 16:39:22 -07002411 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002412 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002413 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002414
François Gaffie11d30102018-11-02 16:09:09 +01002415 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002416 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002417 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002418 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002419 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002420 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002421 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002422 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002423 } else {
2424 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002425 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002426 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2427 AUDIO_FORMAT_DEFAULT);
2428 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2429 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002430 }
2431
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002432 // requiresMuteCheck is false when we can bypass mute strategy.
2433 // It covers a common case when there is no materially active audio
2434 // and muting would result in unnecessary delay and dropped audio.
2435 const uint32_t outputLatencyMs = outputDesc->latency();
2436 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002437 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002438
Eric Laurente552edb2014-03-10 17:42:56 -07002439 // increment usage count for this stream on the requested output:
2440 // NOTE that the usage count is the same for duplicated output and hardware output which is
2441 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002442 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002443
2444 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002445 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002446 // Preferred device may be exclusive, use only if no other active clients on this output
2447 devices = DeviceVector(
2448 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2449 } else {
2450 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2451 }
François Gaffie11d30102018-11-02 16:09:09 +01002452 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002453 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002454 }
2455 }
Eric Laurente552edb2014-03-10 17:42:56 -07002456
François Gaffiec005e562018-11-06 15:04:49 +01002457 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002458 selectOutputForMusicEffects();
2459 }
2460
François Gaffie1c878552018-11-22 16:53:21 +01002461 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002462 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002463 if (devices.isEmpty()) {
2464 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002465 }
François Gaffiec005e562018-11-06 15:04:49 +01002466 bool shouldWait =
2467 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2468 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2469 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002470 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002471 const bool needToCloseBitPerfectOutput =
2472 (com::android::media::audioserver::
2473 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2474 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2475 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002476 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002477 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002478 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002479 // An output has a shared device if
2480 // - managed by the same hw module
2481 // - supports the currently selected device
2482 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002483 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002484
Eric Laurent77305a62016-07-25 16:39:22 -07002485 // force a device change if any other output is:
2486 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002487 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002488 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002489 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002490 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002491 // change the device currently selected by the other output.
2492 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002493 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002494 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002495 force = true;
2496 }
2497 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002498 // a notification so that audio focus effect can propagate, or that a mute/unmute
2499 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002500 const uint32_t latencyMs = desc->latency();
2501 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2502
2503 if (shouldWait && isActive && (waitMs < latencyMs)) {
2504 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002505 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002506
2507 // Require mute check if another output is on a shared device
2508 // and currently active to have proper drain and avoid pops.
2509 // Note restoring AudioTracks onto this output needs to invoke
2510 // a volume ramp if there is no mute.
2511 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002512
2513 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2514 outputsToReopen.push_back(desc);
2515 }
Eric Laurente552edb2014-03-10 17:42:56 -07002516 }
2517 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002518
jiabin220eea12024-05-17 17:55:20 +00002519 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002520 // If the output is open with preferred mixer attributes, but the routed device is
2521 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2522 // changed.
2523 return DEAD_OBJECT;
2524 }
jiabin220eea12024-05-17 17:55:20 +00002525 for (auto& outputToReopen : outputsToReopen) {
2526 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2527 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002528 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302529 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2530 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002531
Eric Laurente552edb2014-03-10 17:42:56 -07002532 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002533 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002534 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002535 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002536 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002537 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002538 outputDesc->useHwGain() /*force*/)) {
2539 // request AudioService to reinitialize the volume curves asynchronously
2540 ALOGE("checkAndSetVolume failed, requesting volume range init");
2541 mpClientInterface->onVolumeRangeInitRequest();
2542 };
Eric Laurente552edb2014-03-10 17:42:56 -07002543
2544 // update the outputs if starting an output with a stream that can affect notification
2545 // routing
2546 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002547
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002548 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002549 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002550 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002551 }
Eric Laurentdc462862016-07-19 12:29:53 -07002552
2553 if (waitMs > muteWaitMs) {
2554 *delayMs = waitMs - muteWaitMs;
2555 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002556
2557 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2558 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2559 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2560 // change occurs after the MixerThread starts and causes a stream volume
2561 // glitch.
2562 //
2563 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002564 }
Eric Laurentdc462862016-07-19 12:29:53 -07002565
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002566 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002567 mEngine->getForceUse(
2568 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002569 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002570 }
2571
Eric Laurent97ac8712018-07-27 18:59:02 -07002572 // Automatically enable the remote submix input when output is started on a re routing mix
2573 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002574 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2575 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002576 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2577 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2578 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002579 "remote-submix",
2580 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002581 }
2582
Eric Laurent96d1dda2022-03-14 17:14:19 +01002583 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2584
Eric Laurente552edb2014-03-10 17:42:56 -07002585 return NO_ERROR;
2586}
2587
Eric Laurent96d1dda2022-03-14 17:14:19 +01002588void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2589 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2590 bool isUnicastActive = isLeUnicastActive();
2591
2592 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002593 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002594 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2595 for (size_t i = 0; i < mOutputs.size(); i++) {
2596 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2597 if (desc != ignoredOutput && desc->isActive()
2598 && ((isUnicastActive &&
2599 !desc->devices().
2600 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2601 || (wasUnicastActive &&
2602 !desc->devices().getDevicesFromTypes(
2603 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2604 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2605 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002606 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002607 // If the device is using preferred mixer attributes, the output need to reopen
2608 // with default configuration when the new selected devices are different from
2609 // current routing devices.
2610 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2611 continue;
2612 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302613 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002614 // re-apply device specific volume if not done by setOutputDevice()
2615 if (!force) {
2616 applyStreamVolumes(desc, newDevices.types(), delayMs);
2617 }
2618 }
2619 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002620 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002621 }
2622}
2623
Eric Laurent8fc147b2018-07-22 19:13:55 -07002624status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002625{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002626 ALOGV("%s portId %d", __FUNCTION__, portId);
2627
2628 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2629 if (outputDesc == 0) {
2630 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002631 return BAD_VALUE;
2632 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002633 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002634
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002635 if (client->hasPreferredDevice(true)) {
2636 // playback activity with preferred device impacts routing occurred, inform upper layers
2637 mpClientInterface->onRoutingUpdated();
2638 }
2639
Eric Laurent97ac8712018-07-27 18:59:02 -07002640 ALOGV("stopOutput() output %d, stream %d, session %d",
2641 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002642
Eric Laurent97ac8712018-07-27 18:59:02 -07002643 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002644
Eric Laurent733ce942017-12-07 12:18:25 -08002645 if (status == NO_ERROR ) {
2646 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002647 } else {
2648 return status;
2649 }
2650
2651 if (outputDesc->devices().size() == 1) {
2652 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2653 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002654 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002655 if (info != nullptr && info->getUid() == client->uid()) {
2656 info->decreaseActiveClient();
2657 if (info->getActiveClientCount() == 0) {
2658 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002659 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002660 }
2661 }
jiabin220eea12024-05-17 17:55:20 +00002662 if (com::android::media::audioserver::
2663 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2664 !outputReopened && outputDesc->isBitPerfect()) {
2665 // Only need to update the clients' internal mute when the output is bit-perfect and it
2666 // is not reopened.
2667 updateClientsInternalMute(outputDesc);
2668 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002669 }
2670 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002671}
2672
Eric Laurent97ac8712018-07-27 18:59:02 -07002673status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2674 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002675{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002676 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002677 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002678 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002679 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002680
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002681 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2682
François Gaffie1c878552018-11-22 16:53:21 +01002683 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2684 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002685 // Automatically disable the remote submix input when output is stopped on a
2686 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002687 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002688 if (isSingleDeviceType(
2689 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002690 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002691 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002692 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2693 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002694 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002695 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002696 }
2697 }
2698 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002699 if (client->hasPreferredDevice(true) &&
2700 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002701 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002702 forceDeviceUpdate = true;
2703 }
2704
Eric Laurente552edb2014-03-10 17:42:56 -07002705 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002706 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002707
Eric Laurente552edb2014-03-10 17:42:56 -07002708 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002709 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002710 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002711 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002712
2713 // If the routing does not change, if an output is routed on a device using HwGain
2714 // (aka setAudioPortConfig) and there are still active clients following different
2715 // volume group(s), force reapply volume
2716 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2717 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2718
Eric Laurente552edb2014-03-10 17:42:56 -07002719 // delay the device switch by twice the latency because stopOutput() is executed when
2720 // the track stop() command is received and at that time the audio track buffer can
2721 // still contain data that needs to be drained. The latency only covers the audio HAL
2722 // and kernel buffers. Also the latency does not always include additional delay in the
2723 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302724 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002725 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002726
2727 // force restoring the device selection on other active outputs if it differs from the
2728 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002729 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002730 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002731 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002732 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002733 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002734 desc->isActive() &&
2735 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002736 (newDevices != desc->devices())) {
2737 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2738 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002739
jiabin220eea12024-05-17 17:55:20 +00002740 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002741 // If the device is using preferred mixer attributes, the output need to
2742 // reopen with default configuration when the new selected devices are
2743 // different from current routing devices.
2744 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2745 continue;
2746 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302747 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002748
Eric Laurent57de36c2016-09-28 16:59:11 -07002749 // re-apply device specific volume if not done by setOutputDevice()
2750 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002751 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002752 }
Eric Laurente552edb2014-03-10 17:42:56 -07002753 }
2754 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002755 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002756 // update the outputs if stopping one with a stream that can affect notification routing
2757 handleNotificationRoutingForStream(stream);
2758 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002759
2760 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2761 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002762 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002763 }
2764
François Gaffiec005e562018-11-06 15:04:49 +01002765 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002766 selectOutputForMusicEffects();
2767 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002768
2769 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2770
Eric Laurente552edb2014-03-10 17:42:56 -07002771 return NO_ERROR;
2772 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002773 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002774 return INVALID_OPERATION;
2775 }
2776}
2777
jiabinbce0c1d2020-10-05 11:20:18 -07002778bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002779{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002780 ALOGV("%s portId %d", __FUNCTION__, portId);
2781
2782 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2783 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002784 // If an output descriptor is closed due to a device routing change,
2785 // then there are race conditions with releaseOutput from tracks
2786 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2787 // destroyed shortly thereafter.
2788 //
2789 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002790 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002791 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002792 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002793
2794 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002795
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302796 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2797 if (outputDesc->isClientActive(client)) {
2798 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2799 stopOutput(portId);
2800 }
2801
Eric Laurent8fc147b2018-07-22 19:13:55 -07002802 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2803 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002804 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002805 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002806 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002807 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002808 if (--outputDesc->mDirectOpenCount == 0) {
2809 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002810 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002811 }
2812 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302813
Andy Hung39efb7a2018-09-26 15:39:28 -07002814 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002815 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2816 // The output is pending reopened to query dynamic profiles and
2817 // there is no active clients
2818 closeOutput(outputDesc->mIoHandle);
2819 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2820 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2821 if (newOutputDesc == nullptr) {
2822 ALOGE("%s failed to open output", __func__);
2823 }
2824 return true;
2825 }
2826 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002827}
2828
Eric Laurentcaf7f482014-11-25 17:50:47 -08002829status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2830 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002831 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002832 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002833 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002834 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002835 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002836 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002837 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002838 audio_port_handle_t *portId,
2839 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002840{
François Gaffiec005e562018-11-06 15:04:49 +01002841 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002842 "flags %#x attributes=%s requested device ID %d",
2843 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2844 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002845
Eric Laurentad2e7b92017-09-14 20:06:42 -07002846 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002847 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002848 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002849 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002850 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002851 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002852 sp<RecordClientDescriptor> clientDesc;
2853 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002854 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002856
2857 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2858 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2859 return INVALID_OPERATION;
2860 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002861
Francois Gaffie716e1432019-01-14 16:58:59 +01002862 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2863 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002864 }
2865
Paul McLean466dc8e2015-04-17 13:15:36 -06002866 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002867 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002868 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002869
Eric Laurentad2e7b92017-09-14 20:06:42 -07002870 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2871 // possible
2872 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2873 *input != AUDIO_IO_HANDLE_NONE) {
2874 ssize_t index = mInputs.indexOfKey(*input);
2875 if (index < 0) {
2876 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2877 status = BAD_VALUE;
2878 goto error;
2879 }
2880 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881 RecordClientVector clients = inputDesc->getClientsForSession(session);
2882 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002883 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2884 status = BAD_VALUE;
2885 goto error;
2886 }
2887 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2888 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002889 // corresponds to a new client and is only permitted from the same UID.
2890 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002891 if (clients.size() > 1) {
2892 for (const auto& client : clients) {
2893 // The client map is ordered by key values (portId) and portIds are allocated
2894 // incrementaly. So the first client in this list is the one opened by audio flinger
2895 // when the mmap stream is created and should be ignored as it does not correspond
2896 // to an actual client
2897 if (client == *clients.cbegin()) {
2898 continue;
2899 }
2900 if (uid != client->uid() && !client->isSilenced()) {
2901 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2902 uid, client->portId(), client->uid());
2903 status = INVALID_OPERATION;
2904 goto error;
2905 }
Eric Laurent331679c2018-04-16 17:03:16 -07002906 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002907 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002908 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002909 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002910
Eric Laurentfecbceb2021-02-09 14:46:43 +01002911 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002912 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002913 }
2914
2915 *input = AUDIO_IO_HANDLE_NONE;
2916 *inputType = API_INPUT_INVALID;
2917
Francois Gaffie716e1432019-01-14 16:58:59 +01002918 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002919 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002920 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002921 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002922 ALOGW("%s could not find input mix for attr %s",
2923 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002924 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002925 }
jiabinc1de2df2019-05-07 14:26:40 -07002926 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2927 String8(attr->tags + strlen("addr=")),
2928 AUDIO_FORMAT_DEFAULT);
2929 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002930 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002931 __func__, attributes.source, attributes.tags);
2932 status = BAD_VALUE;
2933 goto error;
2934 }
2935
Kevin Rocard25f9b052019-02-27 15:08:54 -08002936 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2937 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2938 } else {
2939 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2940 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002941 if (virtualDeviceId) {
2942 *virtualDeviceId = policyMix->mVirtualDeviceId;
2943 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002944 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002945 if (explicitRoutingDevice != nullptr) {
2946 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002947 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002948 // Prevent from storing invalid requested device id in clients
2949 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002950 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002951 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2952 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002953 }
François Gaffie11d30102018-11-02 16:09:09 +01002954 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002955 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002956 status = BAD_VALUE;
2957 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002958 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002959 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2960 *inputType = API_INPUT_MIX_CAPTURE;
2961 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002962 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2963 // there is an external policy, but this input is attached to a mix of recorders,
2964 // meaning it receives audio injected into the framework, so the recorder doesn't
2965 // know about it and is therefore considered "legacy"
2966 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002967
2968 if (virtualDeviceId) {
2969 *virtualDeviceId = policyMix->mVirtualDeviceId;
2970 }
François Gaffie11d30102018-11-02 16:09:09 +01002971 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002972 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002973 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002974 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002975 } else {
2976 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002977 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002978
Eric Laurent599c7582015-12-07 18:05:55 -08002979 }
2980
François Gaffiec005e562018-11-06 15:04:49 +01002981 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002982 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002983 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002984 AudioProfileVector profiles;
2985 status_t ret = getProfilesForDevices(
2986 DeviceVector(device), profiles, flags, true /*isInput*/);
2987 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002988 const auto channels = profiles[0]->getChannels();
2989 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2990 config->channel_mask = *channels.begin();
2991 }
2992 const auto sampleRates = profiles[0]->getSampleRates();
2993 if (!sampleRates.empty() &&
2994 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2995 config->sample_rate = *sampleRates.begin();
2996 }
jiabinf1c73972022-04-14 16:28:52 -07002997 config->format = profiles[0]->getFormat();
2998 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002999 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003000 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003001
Marvin Ramine5a122d2023-12-07 13:57:59 +01003002
3003 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3004 *virtualDeviceId = policyMix->mVirtualDeviceId;
3005 }
3006
Eric Laurent8f42ea12018-08-08 09:08:25 -07003007exit:
3008
François Gaffiec005e562018-11-06 15:04:49 +01003009 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3010 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003011
Francois Gaffie716e1432019-01-14 16:58:59 +01003012 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003013 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003014 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003015
Mikhail Naganov2996f672019-04-18 12:29:59 -07003016 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003017 requestedDeviceId, attributes.source, flags,
3018 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003019 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003020 // Move (if found) effect for the client session to its input
3021 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003022 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003023
3024 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3025 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003026
Eric Laurent599c7582015-12-07 18:05:55 -08003027 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003028
3029error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003030 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003031}
3032
3033
François Gaffie11d30102018-11-02 16:09:09 +01003034audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003035 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003036 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003037 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003038 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003039 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003040{
3041 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003042 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003043 bool isSoundTrigger = false;
3044
François Gaffiec005e562018-11-06 15:04:49 +01003045 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003046 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3047 if (index >= 0) {
3048 input = mSoundTriggerSessions.valueFor(session);
3049 isSoundTrigger = true;
3050 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3051 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3052 } else {
3053 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003054 }
François Gaffiec005e562018-11-06 15:04:49 +01003055 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003056 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003057 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003058 }
3059
Carter Hsua3abb402021-10-26 11:11:20 +08003060 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3061 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3062 }
3063
Eric Laurentfe231122017-11-17 17:48:06 -08003064 // sampling rate and flags may be updated by getInputProfile
3065 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3066 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003067 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003068 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003069 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003070 // find a compatible input profile (not necessarily identical in parameters)
3071 sp<IOProfile> profile = getInputProfile(
3072 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3073 if (profile == nullptr) {
3074 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003075 }
jiabin2fd710d2022-05-02 23:20:22 +00003076
Glenn Kasten05ddca52016-02-11 08:17:12 -08003077 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003078 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003079 if (samplingRate == 0) {
3080 samplingRate = profileSamplingRate;
3081 }
Eric Laurente552edb2014-03-10 17:42:56 -07003082
Eric Laurent322b4d22015-04-03 15:57:54 -07003083 if (profile->getModuleHandle() == 0) {
3084 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003085 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003086 }
3087
Eric Laurentec376dc2021-04-08 20:41:22 +02003088 // Reuse an already opened input if a client with the same session ID already exists
3089 // on that input
3090 for (size_t i = 0; i < mInputs.size(); i++) {
3091 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3092 if (desc->mProfile != profile) {
3093 continue;
3094 }
3095 RecordClientVector clients = desc->clientsList();
3096 for (const auto &client : clients) {
3097 if (session == client->session()) {
3098 return desc->mIoHandle;
3099 }
3100 }
3101 }
3102
Eric Laurent3974e3b2017-12-07 17:58:43 -08003103 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003104 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003105 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003106 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003107 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003108 continue;
3109 }
3110 // if sound trigger, reuse input if used by other sound trigger on same session
3111 // else
3112 // reuse input if active client app is not in IDLE state
3113 //
3114 RecordClientVector clients = desc->clientsList();
3115 bool doClose = false;
3116 for (const auto& client : clients) {
3117 if (isSoundTrigger != client->isSoundTrigger()) {
3118 continue;
3119 }
3120 if (client->isSoundTrigger()) {
3121 if (session == client->session()) {
3122 return desc->mIoHandle;
3123 }
3124 continue;
3125 }
3126 if (client->active() && client->appState() != APP_STATE_IDLE) {
3127 return desc->mIoHandle;
3128 }
3129 doClose = true;
3130 }
3131 if (doClose) {
3132 closeInput(desc->mIoHandle);
3133 } else {
3134 i++;
3135 }
3136 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003137 }
3138
Eric Laurentfe231122017-11-17 17:48:06 -08003139 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003140
Eric Laurentfe231122017-11-17 17:48:06 -08003141 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3142 lConfig.sample_rate = profileSamplingRate;
3143 lConfig.channel_mask = profileChannelMask;
3144 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003145
François Gaffie11d30102018-11-02 16:09:09 +01003146 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003147
3148 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003149 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003150 (profileSamplingRate != lConfig.sample_rate) ||
3151 !audio_formats_match(profileFormat, lConfig.format) ||
3152 (profileChannelMask != lConfig.channel_mask)) {
3153 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003154 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003155 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003156 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003157 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003158 }
Eric Laurent599c7582015-12-07 18:05:55 -08003159 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003160 }
3161
Eric Laurentc722f302014-12-10 11:21:49 -08003162 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003163
Eric Laurent599c7582015-12-07 18:05:55 -08003164 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003165 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003166
Eric Laurent599c7582015-12-07 18:05:55 -08003167 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003168}
3169
Eric Laurent4eb58f12018-12-07 16:41:02 -08003170status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003171{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003172 ALOGV("%s portId %d", __FUNCTION__, portId);
3173
3174 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3175 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003176 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003177 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003178 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003179 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003180 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003181 if (client->active()) {
3182 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3183 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003184 }
3185
Eric Laurent8f42ea12018-08-08 09:08:25 -07003186 audio_session_t session = client->session();
3187
Eric Laurent4eb58f12018-12-07 16:41:02 -08003188 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003189
Eric Laurent4eb58f12018-12-07 16:41:02 -08003190 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003191
Eric Laurent4eb58f12018-12-07 16:41:02 -08003192 status_t status = inputDesc->start();
3193 if (status != NO_ERROR) {
3194 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003195 }
Eric Laurente552edb2014-03-10 17:42:56 -07003196
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003197 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003198 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003199 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003200
Eric Laurent8f42ea12018-08-08 09:08:25 -07003201 // indicate active capture to sound trigger service if starting capture from a mic on
3202 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003203 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003204 if (device != nullptr) {
3205 status = setInputDevice(input, device, true /* force */);
3206 } else {
3207 ALOGW("%s no new input device can be found for descriptor %d",
3208 __FUNCTION__, inputDesc->getId());
3209 status = BAD_VALUE;
3210 }
Eric Laurente552edb2014-03-10 17:42:56 -07003211
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003212 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003213 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003214 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003215 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003216 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3217 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003218 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003219 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003220
François Gaffie11d30102018-11-02 16:09:09 +01003221 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3222 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003223 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003224 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003225 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003226
Eric Laurent8f42ea12018-08-08 09:08:25 -07003227 // automatically enable the remote submix output when input is started if not
3228 // used by a policy mix of type MIX_TYPE_RECORDERS
3229 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003230 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003231 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003232 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003233 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003234 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3235 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003236 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003237 if (address != "") {
3238 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3239 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003240 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003241 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003242 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003243 } else if (status != NO_ERROR) {
3244 // Restore client activity state.
3245 inputDesc->setClientActive(client, false);
3246 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003247 }
3248
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003249 ALOGV("%s input %d source = %d status = %d exit",
3250 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003251
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003252 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003253}
3254
Eric Laurent8fc147b2018-07-22 19:13:55 -07003255status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003256{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003257 ALOGV("%s portId %d", __FUNCTION__, portId);
3258
3259 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3260 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003261 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003262 return BAD_VALUE;
3263 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003264 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003265 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003266 if (!client->active()) {
3267 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003268 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003269 }
Carter Hsue6139d52021-07-08 10:30:20 +08003270 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003271 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003272
Eric Laurent8f42ea12018-08-08 09:08:25 -07003273 inputDesc->stop();
3274 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003275 auto current_source = inputDesc->source();
3276 setInputDevice(input, getNewInputDevice(inputDesc),
3277 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003278 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003279 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003280 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003281 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003282 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3283 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003285 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003286
3287 // automatically disable the remote submix output when input is stopped if not
3288 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003289 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003290 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003291 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003292 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003293 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3294 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003295 }
3296 if (address != "") {
3297 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3298 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003299 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003300 }
3301 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003302 resetInputDevice(input);
3303
3304 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3305 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003306 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3307 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003308 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003309 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003310 }
3311 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003312 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003313 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003314}
3315
Eric Laurent8fc147b2018-07-22 19:13:55 -07003316void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003317{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003318 ALOGV("%s portId %d", __FUNCTION__, portId);
3319
3320 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3321 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003322 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003323 return;
3324 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003325 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003326 audio_io_handle_t input = inputDesc->mIoHandle;
3327
Eric Laurent8f42ea12018-08-08 09:08:25 -07003328 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003329
Andy Hung39efb7a2018-09-26 15:39:28 -07003330 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003331
3332 // If no more clients are present in this session, park effects to an orphan chain
3333 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3334 if (clientsOnSession.size() == 0) {
3335 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3336 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003337 if (inputDesc->getClientCount() > 0) {
3338 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003339 return;
3340 }
3341
Eric Laurent05b90f82014-08-27 15:32:29 -07003342 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003343 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003344 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003345}
3346
Eric Laurent8f42ea12018-08-08 09:08:25 -07003347void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003348{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003349 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003350
3351 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003352 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003353 }
3354}
3355
Eric Laurent8f42ea12018-08-08 09:08:25 -07003356void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3357{
3358 stopInput(portId);
3359 releaseInput(portId);
3360}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003361
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003362bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3363 if (input->clientsList().size() == 0
3364 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3365 return true;
3366 }
3367 for (const auto& client : input->clientsList()) {
3368 sp<DeviceDescriptor> device =
3369 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3370 client->session());
3371 if (!input->supportedDevices().contains(device)) {
3372 return true;
3373 }
3374 }
3375 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3376 return false;
3377}
3378
Eric Laurent0dd51852019-04-19 18:18:58 -07003379void AudioPolicyManager::checkCloseInputs() {
3380 // After connecting or disconnecting an input device, close input if:
3381 // - it has no client (was just opened to check profile) OR
3382 // - none of its supported devices are connected anymore OR
3383 // - one of its clients cannot be routed to one of its supported
3384 // devices anymore. Otherwise update device selection
3385 std::vector<audio_io_handle_t> inputsToClose;
3386 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003387 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003388 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003389 }
3390 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003391 for (const audio_io_handle_t handle : inputsToClose) {
3392 ALOGV("%s closing input %d", __func__, handle);
3393 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003394 }
Eric Laurentd4692962014-05-05 18:13:44 -07003395}
3396
Vlad Popa87e0e582024-05-20 18:49:20 -07003397status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3398 const char *address __unused,
3399 bool enabled,
3400 audio_stream_type_t streamToDriveAbs)
3401{
3402 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3403 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3404 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3405 toString(streamToDriveAbs).c_str());
3406 return BAD_VALUE;
3407 }
3408
3409 if (enabled) {
3410 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3411 } else {
3412 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3413 }
3414
3415 return NO_ERROR;
3416}
3417
François Gaffie251c7f02018-11-07 10:41:08 +01003418void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003419{
3420 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003421 if (indexMin < 0 || indexMax < 0) {
3422 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3423 return;
3424 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003425 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003426
3427 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003428 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3429 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003430 continue;
3431 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003432 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003433 }
Eric Laurente552edb2014-03-10 17:42:56 -07003434}
3435
Eric Laurente0720872014-03-11 09:30:41 -07003436status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003437 int index,
3438 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003439{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003440 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003441 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3442 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3443 return NO_ERROR;
3444 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303445 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3446 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003447 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003448}
3449
Eric Laurente0720872014-03-11 09:30:41 -07003450status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003451 int *index,
3452 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003453{
François Gaffiec005e562018-11-06 15:04:49 +01003454 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3455 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003456 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003457 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003458 deviceTypes = mEngine->getOutputDevicesForStream(
3459 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003460 }
jiabin9a3361e2019-10-01 09:38:30 -07003461 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003462}
3463
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003464status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003465 int index,
3466 audio_devices_t device)
3467{
3468 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003469 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3470 if (group == VOLUME_GROUP_NONE) {
3471 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003472 return BAD_VALUE;
3473 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003474 ALOGV("%s: group %d matching with %s index %d",
3475 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003476 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003477 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003478 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003479 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3480 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3481 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3482 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003483 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3484
3485 status = setVolumeCurveIndex(index, device, curves);
3486 if (status != NO_ERROR) {
3487 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3488 return status;
3489 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003490
jiabin9a3361e2019-10-01 09:38:30 -07003491 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003492 auto curCurvAttrs = curves.getAttributes();
3493 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3494 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003495 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003496 } else if (!curves.getStreamTypes().empty()) {
3497 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003498 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003499 } else {
3500 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3501 return BAD_VALUE;
3502 }
jiabin9a3361e2019-10-01 09:38:30 -07003503 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3504 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003505
François Gaffiecfe17322018-11-07 13:41:29 +01003506 // update volume on all outputs and streams matching the following:
3507 // - The requested stream (or a stream matching for volume control) is active on the output
3508 // - The device (or devices) selected by the engine for this stream includes
3509 // the requested device
3510 // - For non default requested device, currently selected device on the output is either the
3511 // requested device or one of the devices selected by the engine for this stream
3512 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3513 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003514 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003515 for (size_t i = 0; i < mOutputs.size(); i++) {
3516 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003517 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003518
jiabin9a3361e2019-10-01 09:38:30 -07003519 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3520 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003521 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003522
3523 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003524 continue;
3525 }
3526 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3527 curDevices.find(device) == curDevices.end()) {
3528 continue;
3529 }
3530 bool applyVolume = false;
3531 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3532 curSrcDevices.insert(device);
3533 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003534 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3535 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003536 } else {
3537 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3538 }
3539 if (!applyVolume) {
3540 continue; // next output
3541 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003542 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3543 // If a higher priority strategy is active, and the output is routed to a device with a
3544 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003545 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003546 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003547 // If the volume source is active with higher priority source, ensure at least Sw Muted
3548 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003549 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3550 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3551 false /*preferredDevice*/);
3552 if (activeClients.empty()) {
3553 continue;
3554 }
3555 bool isPreempted = false;
3556 bool isHigherPriority = productStrategy < strategy;
3557 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003558 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003559 ALOGV("%s: Strategy=%d (\nrequester:\n"
3560 " group %d, volumeGroup=%d attributes=%s)\n"
3561 " higher priority source active:\n"
3562 " volumeGroup=%d attributes=%s) \n"
3563 " on output %zu, bailing out", __func__, productStrategy,
3564 group, group, toString(attributes).c_str(),
3565 client->volumeSource(), toString(client->attributes()).c_str(), i);
3566 applyVolume = false;
3567 isPreempted = true;
3568 break;
3569 }
3570 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003571 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003572 applyVolume = true;
3573 }
3574 }
3575 if (isPreempted || applyVolume) {
3576 break;
3577 }
3578 }
3579 if (!applyVolume) {
3580 continue; // next output
3581 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003582 }
François Gaffieed91f582020-01-31 10:35:37 +01003583 //FIXME: workaround for truncated touch sounds
3584 // delayed volume change for system stream to be removed when the problem is
3585 // handled by system UI
3586 status_t volStatus = checkAndSetVolume(
3587 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003588 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003589 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3590 if (volStatus != NO_ERROR) {
3591 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003592 }
3593 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003594
3595 // update voice volume if the an active call route exists
3596 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3597 && (curSrcDevices.find(
3598 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3599 != curSrcDevices.end())) {
3600 bool isVoiceVolSrc;
3601 bool isBtScoVolSrc;
3602 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3603 isVoiceVolSrc, isBtScoVolSrc, __func__)
3604 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003605 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3606 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3607 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003608 }
3609 }
3610
François Gaffiecfe17322018-11-07 13:41:29 +01003611 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3612 return status;
3613}
3614
François Gaffieaaac0fd2018-11-22 17:56:39 +01003615status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003616 audio_devices_t device,
3617 IVolumeCurves &volumeCurves)
3618{
3619 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3620 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003621 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3622 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003623 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303624 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3625 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003626 return BAD_VALUE;
3627 }
3628 if (!audio_is_output_device(device)) {
3629 return BAD_VALUE;
3630 }
3631
3632 // Force max volume if stream cannot be muted
3633 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3634
François Gaffieaaac0fd2018-11-22 17:56:39 +01003635 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003636 volumeCurves.addCurrentVolumeIndex(device, index);
3637 return NO_ERROR;
3638}
3639
3640status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3641 int &index,
3642 audio_devices_t device)
3643{
3644 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3645 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003646 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003647 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003648 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003649 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003650 }
jiabin9a3361e2019-10-01 09:38:30 -07003651 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003652}
3653
3654status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3655 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003656 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003657{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003658 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003659 return BAD_VALUE;
3660 }
jiabin9a3361e2019-10-01 09:38:30 -07003661 index = curves.getVolumeIndex(deviceTypes);
3662 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003663 return NO_ERROR;
3664}
3665
3666status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3667 int &index)
3668{
3669 index = getVolumeCurves(attr).getVolumeIndexMin();
3670 return NO_ERROR;
3671}
3672
3673status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3674 int &index)
3675{
3676 index = getVolumeCurves(attr).getVolumeIndexMax();
3677 return NO_ERROR;
3678}
3679
Eric Laurent36829f92017-04-07 19:04:42 -07003680audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003681{
3682 // select one output among several suitable for global effects.
3683 // The priority is as follows:
3684 // 1: An offloaded output. If the effect ends up not being offloadable,
3685 // AudioFlinger will invalidate the track and the offloaded output
3686 // will be closed causing the effect to be moved to a PCM output.
3687 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003688 // 3: The primary output
3689 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003690
François Gaffiec005e562018-11-06 15:04:49 +01003691 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3692 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003693 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003694
Eric Laurent36829f92017-04-07 19:04:42 -07003695 if (outputs.size() == 0) {
3696 return AUDIO_IO_HANDLE_NONE;
3697 }
Eric Laurente552edb2014-03-10 17:42:56 -07003698
Eric Laurent36829f92017-04-07 19:04:42 -07003699 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3700 bool activeOnly = true;
3701
3702 while (output == AUDIO_IO_HANDLE_NONE) {
3703 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3704 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3705 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3706
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003707 for (audio_io_handle_t output : outputs) {
3708 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003709 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003710 continue;
3711 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003712 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3713 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003714 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003715 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003716 }
3717 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003718 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003719 }
3720 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003721 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003722 }
3723 }
3724 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3725 output = outputOffloaded;
3726 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3727 output = outputDeepBuffer;
3728 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3729 output = outputPrimary;
3730 } else {
3731 output = outputs[0];
3732 }
3733 activeOnly = false;
3734 }
3735
3736 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003737 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3738 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003739 mMusicEffectOutput = output;
3740 }
3741
3742 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003743 return output;
3744}
3745
Eric Laurent36829f92017-04-07 19:04:42 -07003746audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3747{
3748 return selectOutputForMusicEffects();
3749}
3750
Eric Laurente0720872014-03-11 09:30:41 -07003751status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003752 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003753 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003754 int session,
3755 int id)
3756{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003757 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003758 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003759 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003760 index = mInputs.indexOfKey(io);
3761 if (index < 0) {
3762 ALOGW("registerEffect() unknown io %d", io);
3763 return INVALID_OPERATION;
3764 }
Eric Laurente552edb2014-03-10 17:42:56 -07003765 }
3766 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003767 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3768 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3769 || strategy == PRODUCT_STRATEGY_NONE));
3770 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003771}
3772
Eric Laurentc241b0d2018-11-28 09:08:49 -08003773status_t AudioPolicyManager::unregisterEffect(int id)
3774{
3775 if (mEffects.getEffect(id) == nullptr) {
3776 return INVALID_OPERATION;
3777 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003778 if (mEffects.isEffectEnabled(id)) {
3779 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3780 setEffectEnabled(id, false);
3781 }
3782 return mEffects.unregisterEffect(id);
3783}
3784
3785status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3786{
3787 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3788 if (effect == nullptr) {
3789 return INVALID_OPERATION;
3790 }
3791
3792 status_t status = mEffects.setEffectEnabled(id, enabled);
3793 if (status == NO_ERROR) {
3794 mInputs.trackEffectEnabled(effect, enabled);
3795 }
3796 return status;
3797}
3798
Eric Laurent6c796322019-04-09 14:13:17 -07003799
3800status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3801{
3802 mEffects.moveEffects(ids, io);
3803 return NO_ERROR;
3804}
3805
Eric Laurentc75307b2015-03-17 15:29:32 -07003806bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3807{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003808 auto vs = toVolumeSource(stream, false);
3809 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003810}
3811
3812bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3813{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003814 auto vs = toVolumeSource(stream, false);
3815 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003816}
3817
Eric Laurente0720872014-03-11 09:30:41 -07003818bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003819{
3820 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003821 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003822 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003823 return true;
3824 }
3825 }
3826 return false;
3827}
3828
Eric Laurent275e8e92014-11-30 15:14:47 -08003829// Register a list of custom mixes with their attributes and format.
3830// When a mix is registered, corresponding input and output profiles are
3831// added to the remote submix hw module. The profile contains only the
3832// parameters (sampling rate, format...) specified by the mix.
3833// The corresponding input remote submix device is also connected.
3834//
3835// When a remote submix device is connected, the address is checked to select the
3836// appropriate profile and the corresponding input or output stream is opened.
3837//
3838// When capture starts, getInputForAttr() will:
3839// - 1 look for a mix matching the address passed in attribtutes tags if any
3840// - 2 if none found, getDeviceForInputSource() will:
3841// - 2.1 look for a mix matching the attributes source
3842// - 2.2 if none found, default to device selection by policy rules
3843// At this time, the corresponding output remote submix device is also connected
3844// and active playback use cases can be transferred to this mix if needed when reconnecting
3845// after AudioTracks are invalidated
3846//
3847// When playback starts, getOutputForAttr() will:
3848// - 1 look for a mix matching the address passed in attribtutes tags if any
3849// - 2 if none found, look for a mix matching the attributes usage
3850// - 3 if none found, default to device and output selection by policy rules.
3851
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003852status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003853{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003854 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3855 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003856 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003857 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003858 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003859 // examine each mix's route type
3860 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003861 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003862 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3863 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3864 ALOGE("Unsupported Policy Mix %zu of %zu: "
3865 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3866 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003867 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003868 break;
3869 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003870 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3871 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003872 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003873 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3874 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003875 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003876 rSubmixModule = mHwModules.getModuleFromName(
3877 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3878 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003879 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003880 i);
3881 res = INVALID_OPERATION;
3882 break;
3883 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003884 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003885
Eric Laurent97ac8712018-07-27 18:59:02 -07003886 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003887 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003888 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003889 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003890 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3891 } else {
3892 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3893 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003894 }
François Gaffie036e1e92015-03-19 10:16:24 +01003895
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003896 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003897 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003898 res = INVALID_OPERATION;
3899 break;
3900 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003901 audio_config_t outputConfig = mix.mFormat;
3902 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003903 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3904 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003905 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3906 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003907 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003908 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3909 audio_is_linear_pcm(outputConfig.format)
3910 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003911 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003912 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3913 audio_is_linear_pcm(inputConfig.format)
3914 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003915
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003916 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003917 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003918 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003919 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003920 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003921 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003922 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003923 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3924 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003925 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003926 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003927 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003928
3929 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3930 mix.mDeviceType, mix.mDeviceAddress,
3931 String8(), AUDIO_FORMAT_DEFAULT);
3932 if (device == nullptr) {
3933 res = INVALID_OPERATION;
3934 break;
3935 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003936
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003937 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003938 // First try to find an already opened output supporting the device
3939 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003940 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003941
Eric Laurentc529cf62020-04-17 18:19:10 -07003942 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003943 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003944 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003945 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003946 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003947 } else {
3948 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003949 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003950 }
3951 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003952 // If no output found, try to find a direct output profile supporting the device
3953 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3954 sp<HwModule> module = mHwModules[i];
3955 for (size_t j = 0;
3956 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3957 j++) {
3958 sp<IOProfile> profile = module->getOutputProfiles()[j];
3959 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3960 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3961 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003962 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003963 res = INVALID_OPERATION;
3964 } else {
3965 foundOutput = true;
3966 }
3967 }
3968 }
3969 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003970 if (res != NO_ERROR) {
3971 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003972 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003973 res = INVALID_OPERATION;
3974 break;
3975 } else if (!foundOutput) {
3976 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003977 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003978 res = INVALID_OPERATION;
3979 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003980 } else {
3981 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003982 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003983 }
Eric Laurentc722f302014-12-10 11:21:49 -08003984 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003985 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003986 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003987 if (audio_flags::audio_mix_ownership()) {
3988 // Only unregister mixes that were actually registered to not accidentally unregister
3989 // mixes that already existed previously.
3990 unregisterPolicyMixes(registeredMixes);
3991 registeredMixes.clear();
3992 } else {
3993 unregisterPolicyMixes(mixes);
3994 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003995 } else if (checkOutputs) {
3996 checkForDeviceAndOutputChanges();
3997 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003998 }
3999 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004000}
4001
4002status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4003{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004004 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004005 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004006 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004007 sp<HwModule> rSubmixModule;
4008 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004009 for (const auto& mix : mixes) {
4010 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004011
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004012 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004013 rSubmixModule = mHwModules.getModuleFromName(
4014 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4015 if (rSubmixModule == 0) {
4016 res = INVALID_OPERATION;
4017 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004018 }
4019 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004020
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004021 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004022
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004023 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004024 res = INVALID_OPERATION;
4025 continue;
4026 }
4027
Marvin Ramin0783e202024-03-05 12:45:50 +01004028 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004029 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004030 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4031 status_t currentRes =
4032 setDeviceConnectionStateInt(device,
4033 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4034 address.c_str(),
4035 "remote-submix",
4036 AUDIO_FORMAT_DEFAULT);
4037 if (!audio_flags::audio_mix_ownership()) {
4038 res = currentRes;
4039 }
4040 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004041 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004042 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004043 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004044 }
4045 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004046 }
jiabin5740f082019-08-19 15:08:30 -07004047 rSubmixModule->removeOutputProfile(address.c_str());
4048 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004049
Kevin Rocard153f92d2018-12-18 18:33:28 -08004050 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004051 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004052 res = INVALID_OPERATION;
4053 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004054 } else {
4055 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004056 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004057 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004058 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004059
4060 if (res == NO_ERROR && checkOutputs) {
4061 checkForDeviceAndOutputChanges();
4062 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004063 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004064 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004065}
4066
Marvin Raminbdefaf02023-11-01 09:10:32 +01004067status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4068 if (!audio_flags::audio_mix_test_api()) {
4069 return INVALID_OPERATION;
4070 }
4071
4072 _aidl_return.clear();
4073 _aidl_return.reserve(mPolicyMixes.size());
4074 for (const auto &policyMix: mPolicyMixes) {
4075 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4076 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4077 policyMix->mCbFlags);
4078 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004079 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004080 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004081 }
4082
Vlad Popaa5d73f32024-03-08 16:05:38 -08004083 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004084 return OK;
4085}
4086
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004087status_t AudioPolicyManager::updatePolicyMix(
4088 const AudioMix& mix,
4089 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4090 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4091 if (res == NO_ERROR) {
4092 checkForDeviceAndOutputChanges();
4093 updateCallAndOutputRouting();
4094 }
4095 return res;
4096}
4097
Mikhail Naganov100f0122018-11-29 11:22:16 -08004098void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4099{
4100 size_t i = 0;
4101 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4102 for (const auto& fmt : mManualSurroundFormats) {
4103 if (i++ != 0) dst->append(", ");
4104 std::string sfmt;
4105 FormatConverter::toString(fmt, sfmt);
4106 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4107 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4108 }
4109}
4110
Eric Laurentc529cf62020-04-17 18:19:10 -07004111// Returns true if all devices types match the predicate and are supported by one HW module
4112bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004113 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004114 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004115 const char *context,
4116 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004117 for (size_t i = 0; i < devices.size(); i++) {
4118 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004119 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004120 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004121 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004122 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004123 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004124 return false;
4125 }
4126 }
4127 return true;
4128}
4129
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004130void AudioPolicyManager::changeOutputDevicesMuteState(
4131 const AudioDeviceTypeAddrVector& devices) {
4132 ALOGVV("%s() num devices %zu", __func__, devices.size());
4133
4134 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4135 getSoftwareOutputsForDevices(devices);
4136
4137 for (size_t i = 0; i < outputs.size(); i++) {
4138 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4139 DeviceVector prevDevices = outputDesc->devices();
4140 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4141 }
4142}
4143
4144std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4145 const AudioDeviceTypeAddrVector& devices) const
4146{
4147 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4148 DeviceVector deviceDescriptors;
4149 for (size_t j = 0; j < devices.size(); j++) {
4150 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4151 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4152 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4153 ALOGE("%s: device type %#x address %s not supported or not an output device",
4154 __func__, devices[j].mType, devices[j].getAddress());
4155 continue;
4156 }
4157 deviceDescriptors.add(desc);
4158 }
4159 for (size_t i = 0; i < mOutputs.size(); i++) {
4160 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4161 continue;
4162 }
4163 outputs.push_back(mOutputs.valueAt(i));
4164 }
4165 return outputs;
4166}
4167
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004168status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004169 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004170 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004171 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4172 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004173 }
4174 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004175 if (res != NO_ERROR) {
4176 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4177 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004178 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004179
4180 checkForDeviceAndOutputChanges();
4181 updateCallAndOutputRouting();
4182
4183 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004184}
4185
4186status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4187 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004188 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4189 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004190 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004191 __FUNCTION__, uid);
4192 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004193 }
4194
Eric Laurentc529cf62020-04-17 18:19:10 -07004195 checkForDeviceAndOutputChanges();
4196 updateCallAndOutputRouting();
4197
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004198 return res;
4199}
4200
Eric Laurent2517af32020-11-25 15:31:27 +01004201
jiabin0a488932020-08-07 17:32:40 -07004202status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4203 device_role_t role,
4204 const AudioDeviceTypeAddrVector &devices) {
4205 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4206 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004207
Eric Laurentc529cf62020-04-17 18:19:10 -07004208 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004209 return BAD_VALUE;
4210 }
jiabin0a488932020-08-07 17:32:40 -07004211 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004212 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004213 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4214 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004215 return status;
4216 }
4217
4218 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004219
4220 bool forceVolumeReeval = false;
4221 // FIXME: workaround for truncated touch sounds
4222 // to be removed when the problem is handled by system UI
4223 uint32_t delayMs = 0;
4224 if (strategy == mCommunnicationStrategy) {
4225 forceVolumeReeval = true;
4226 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4227 updateInputRouting();
4228 }
4229 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004230
4231 return NO_ERROR;
4232}
4233
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004234void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4235 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004236{
4237 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004238 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004239 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004240 // Only apply special touch sound delay once
4241 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004242 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004243 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004244 for (size_t i = 0; i < mOutputs.size(); i++) {
4245 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4246 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004247 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4248 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004249 // As done in setDeviceConnectionState, we could also fix default device issue by
4250 // preventing the force re-routing in case of default dev that distinguishes on address.
4251 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004252 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004253 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004254 // If the device is using preferred mixer attributes, the output need to reopen
4255 // with default configuration when the new selected devices are different from
4256 // current routing devices.
4257 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4258 continue;
4259 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304260
4261 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4262 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004263 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004264 // Only apply special touch sound delay once
4265 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004266 }
4267 if (forceVolumeReeval && !newDevices.isEmpty()) {
4268 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4269 }
4270 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004271 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004272 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004273}
4274
Eric Laurent2517af32020-11-25 15:31:27 +01004275void AudioPolicyManager::updateInputRouting() {
4276 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304277 // Skip for hotword recording as the input device switch
4278 // is handled within sound trigger HAL
4279 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4280 continue;
4281 }
Eric Laurent2517af32020-11-25 15:31:27 +01004282 auto newDevice = getNewInputDevice(activeDesc);
4283 // Force new input selection if the new device can not be reached via current input
4284 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4285 setInputDevice(activeDesc->mIoHandle, newDevice);
4286 } else {
4287 closeInput(activeDesc->mIoHandle);
4288 }
4289 }
4290}
4291
Paul Wang5d7cdb52022-11-22 09:45:06 +00004292status_t
4293AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4294 device_role_t role,
4295 const AudioDeviceTypeAddrVector &devices) {
4296 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4297 dumpAudioDeviceTypeAddrVector(devices).c_str());
4298
Eric Laurent78fedbf2023-03-09 14:40:44 +01004299 if (!areAllDevicesSupported(
4300 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004301 return BAD_VALUE;
4302 }
4303 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4304 if (status != NO_ERROR) {
4305 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4306 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4307 return status;
4308 }
4309
4310 checkForDeviceAndOutputChanges();
4311
4312 bool forceVolumeReeval = false;
4313 // TODO(b/263479999): workaround for truncated touch sounds
4314 // to be removed when the problem is handled by system UI
4315 uint32_t delayMs = 0;
4316 if (strategy == mCommunnicationStrategy) {
4317 forceVolumeReeval = true;
4318 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4319 updateInputRouting();
4320 }
4321 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4322
4323 return NO_ERROR;
4324}
4325
4326status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4327 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004328{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004329 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004330
Paul Wang5d7cdb52022-11-22 09:45:06 +00004331 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004332 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004333 ALOGW_IF(status != NAME_NOT_FOUND,
4334 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004335 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004336 return status;
4337 }
4338
4339 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004340
4341 bool forceVolumeReeval = false;
4342 // FIXME: 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);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004351
4352 return NO_ERROR;
4353}
4354
jiabin0a488932020-08-07 17:32:40 -07004355status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4356 device_role_t role,
4357 AudioDeviceTypeAddrVector &devices) {
4358 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004359}
4360
Jiabin Huang3b98d322020-09-03 17:54:16 +00004361status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4362 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4363 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4364 dumpAudioDeviceTypeAddrVector(devices).c_str());
4365
Mikhail Naganov55773032020-10-01 15:08:13 -07004366 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004367 return BAD_VALUE;
4368 }
4369 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4370 ALOGW_IF(status != NO_ERROR,
4371 "Engine could not set preferred devices %s for audio source %d role %d",
4372 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4373
4374 return status;
4375}
4376
4377status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4378 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4379 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4380 dumpAudioDeviceTypeAddrVector(devices).c_str());
4381
Mikhail Naganov55773032020-10-01 15:08:13 -07004382 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004383 return BAD_VALUE;
4384 }
4385 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4386 ALOGW_IF(status != NO_ERROR,
4387 "Engine could not add preferred devices %s for audio source %d role %d",
4388 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4389
Eric Laurent2517af32020-11-25 15:31:27 +01004390 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004391 return status;
4392}
4393
4394status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4395 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4396{
4397 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4398 dumpAudioDeviceTypeAddrVector(devices).c_str());
4399
Eric Laurent78fedbf2023-03-09 14:40:44 +01004400 if (!areAllDevicesSupported(
4401 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004402 return BAD_VALUE;
4403 }
4404
4405 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4406 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004407 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004408 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004409 if (status == NO_ERROR) {
4410 updateInputRouting();
4411 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004412 return status;
4413}
4414
4415status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4416 device_role_t role) {
4417 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4418
4419 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004420 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004421 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004422 if (status == NO_ERROR) {
4423 updateInputRouting();
4424 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004425 return status;
4426}
4427
4428status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4429 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4430 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4431}
4432
Oscar Azucena90e77632019-11-27 17:12:28 -08004433status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004434 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004435 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004436 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4437 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004438 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004439 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4440 if (status != NO_ERROR) {
4441 ALOGE("%s() could not set device affinity for userId %d",
4442 __FUNCTION__, userId);
4443 return status;
4444 }
4445
4446 // reevaluate outputs for all devices
4447 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004448 changeOutputDevicesMuteState(devices);
4449 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4450 true /* skipDelays */);
4451 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004452
4453 return NO_ERROR;
4454}
4455
4456status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004457 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004458 AudioDeviceTypeAddrVector devices;
4459 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004460 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4461 if (status != NO_ERROR) {
4462 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4463 __FUNCTION__, userId);
4464 return status;
4465 }
4466
4467 // reevaluate outputs for all devices
4468 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004469 changeOutputDevicesMuteState(devices);
4470 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4471 true /* skipDelays */);
4472 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004473
4474 return NO_ERROR;
4475}
4476
Andy Hungc29d82b2018-10-05 12:23:17 -07004477void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004478{
Andy Hungc29d82b2018-10-05 12:23:17 -07004479 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004480 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004481 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004482 std::string stateLiteral;
4483 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004484 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004485 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4486 "communications", "media", "record", "dock", "system",
4487 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4488 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4489 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004490 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4491 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4492 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4493 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4494 dst->append(" (MANUAL: ");
4495 dumpManualSurroundFormats(dst);
4496 dst->append(")");
4497 }
4498 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004499 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004500 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4501 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004502 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004503 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004504
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004505 dst->append("\n");
4506 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4507 dst->append("\n");
4508 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004509 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004510 mOutputs.dump(dst);
4511 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004512 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004513 mAudioPatches.dump(dst);
4514 mPolicyMixes.dump(dst);
4515 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004516
Kevin Rocardb99cc752019-03-21 20:52:24 -07004517 dst->appendFormat(" AllowedCapturePolicies:\n");
4518 for (auto& policy : mAllowedCapturePolicies) {
4519 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4520 }
4521
jiabina84c3d32022-12-02 18:59:55 +00004522 dst->appendFormat(" Preferred mixer audio configuration:\n");
4523 for (const auto it : mPreferredMixerAttrInfos) {
4524 dst->appendFormat(" - device port id: %d\n", it.first);
4525 for (const auto preferredMixerInfoIt : it.second) {
4526 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4527 preferredMixerInfoIt.second->dump(dst);
4528 }
4529 }
4530
François Gaffiec005e562018-11-06 15:04:49 +01004531 dst->appendFormat("\nPolicy Engine dump:\n");
4532 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004533
4534 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4535 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4536 dst->appendFormat(" - device type: %s, driving stream %d\n",
4537 dumpDeviceTypes({it.first}).c_str(),
4538 mEngine->getVolumeGroupForAttributes(it.second));
4539 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004540}
4541
4542status_t AudioPolicyManager::dump(int fd)
4543{
4544 String8 result;
4545 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004546 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004547 return NO_ERROR;
4548}
4549
Kevin Rocardb99cc752019-03-21 20:52:24 -07004550status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4551{
4552 mAllowedCapturePolicies[uid] = capturePolicy;
4553 return NO_ERROR;
4554}
4555
Eric Laurente552edb2014-03-10 17:42:56 -07004556// This function checks for the parameters which can be offloaded.
4557// This can be enhanced depending on the capability of the DSP and policy
4558// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004559audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004560{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004561 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004562 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004563 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004564 offloadInfo.format,
4565 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4566 offloadInfo.has_video);
4567
jiabin2b9d5a12021-12-10 01:06:29 +00004568 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004569 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004570 }
4571
4572 // See if there is a profile to support this.
4573 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004574 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004575 offloadInfo.sample_rate,
4576 offloadInfo.format,
4577 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004578 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4579 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004580 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4581 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4582 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004583 if (profile == nullptr) {
4584 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4585 }
4586 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4587 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4588 }
4589 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004590}
4591
Michael Chana94fbb22018-04-24 14:31:19 +10004592bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4593 const audio_attributes_t& attributes) {
4594 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004595 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004596 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4597 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004598 config.sample_rate,
4599 config.format,
4600 config.channel_mask,
4601 output_flags,
4602 true /* directOnly */);
4603 ALOGV("%s() profile %sfound with name: %s, "
4604 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4605 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004606 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004607 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004608
4609 // also try the MSD module if compatible profile not found
4610 if (profile == nullptr) {
4611 profile = getMsdProfileForOutput(outputDevices,
4612 config.sample_rate,
4613 config.format,
4614 config.channel_mask,
4615 output_flags,
4616 true /* directOnly */);
4617 ALOGV("%s() MSD profile %sfound with name: %s, "
4618 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4619 __FUNCTION__, profile != 0 ? "" : "NOT ",
4620 (profile != 0 ? profile->getTagName().c_str() : "null"),
4621 config.sample_rate, config.format, config.channel_mask, output_flags);
4622 }
4623 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004624}
4625
jiabin2b9d5a12021-12-10 01:06:29 +00004626bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4627 bool durationIgnored) {
4628 if (mMasterMono) {
4629 return false; // no offloading if mono is set.
4630 }
4631
4632 // Check if offload has been disabled
4633 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4634 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4635 return false;
4636 }
4637
4638 // Check if stream type is music, then only allow offload as of now.
4639 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4640 {
4641 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4642 return false;
4643 }
4644
4645 //TODO: enable audio offloading with video when ready
4646 const bool allowOffloadWithVideo =
4647 property_get_bool("audio.offload.video", false /* default_value */);
4648 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4649 ALOGV("%s: has_video == true, returning false", __func__);
4650 return false;
4651 }
4652
4653 //If duration is less than minimum value defined in property, return false
4654 const int min_duration_secs = property_get_int32(
4655 "audio.offload.min.duration.secs", -1 /* default_value */);
4656 if (!durationIgnored) {
4657 if (min_duration_secs >= 0) {
4658 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4659 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4660 __func__, min_duration_secs);
4661 return false;
4662 }
4663 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4664 ALOGV("%s: Offload denied by duration < default min(=%u)",
4665 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4666 return false;
4667 }
4668 }
4669
4670 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4671 // creating an offloaded track and tearing it down immediately after start when audioflinger
4672 // detects there is an active non offloadable effect.
4673 // FIXME: We should check the audio session here but we do not have it in this context.
4674 // This may prevent offloading in rare situations where effects are left active by apps
4675 // in the background.
4676 if (mEffects.isNonOffloadableEffectEnabled()) {
4677 return false;
4678 }
4679
4680 return true;
4681}
4682
4683audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4684 const audio_config_t *config) {
4685 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4686 offloadInfo.format = config->format;
4687 offloadInfo.sample_rate = config->sample_rate;
4688 offloadInfo.channel_mask = config->channel_mask;
4689 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4690 offloadInfo.has_video = false;
4691 offloadInfo.is_streaming = false;
4692 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4693
4694 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4695 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4696 audio_flags_to_audio_output_flags(attr->flags, &flags);
4697 // only retain flags that will drive compressed offload or passthrough
4698 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4699 if (offloadPossible) {
4700 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4701 }
4702 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4703
Dorin Drimusfae3c642022-03-17 18:36:30 +01004704 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004705 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004706 DeviceVector outputDevices = engineOutputDevices;
4707 // the MSD module checks for different conditions and output devices
4708 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4709 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4710 continue;
4711 }
4712 outputDevices = getMsdAudioOutDevices();
4713 }
jiabin2b9d5a12021-12-10 01:06:29 +00004714 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004715 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004716 config->sample_rate, nullptr /*updatedSamplingRate*/,
4717 config->format, nullptr /*updatedFormat*/,
4718 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004719 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004720 continue;
4721 }
4722 // reject profiles not corresponding to a device currently available
4723 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4724 continue;
4725 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004726 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4727 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004728 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004729 != AUDIO_DIRECT_NOT_SUPPORTED) {
4730 // Already reports offload gapless supported. No need to report offload support.
4731 continue;
4732 }
4733 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4734 != AUDIO_OUTPUT_FLAG_NONE) {
4735 // If offload gapless is reported, no need to report offload support.
4736 directMode = (audio_direct_mode_t) ((directMode &
4737 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4738 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4739 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004740 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004741 }
4742 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004743 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004744 }
4745 }
4746 }
4747 return directMode;
4748}
4749
Dorin Drimusf2196d82022-01-03 12:11:18 +01004750status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4751 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004752 if (mEffects.isNonOffloadableEffectEnabled()) {
4753 return OK;
4754 }
jiabinf1c73972022-04-14 16:28:52 -07004755 DeviceVector devices;
4756 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004757 if (status != OK) {
4758 return status;
4759 }
4760 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4761 if (devices.empty()) {
4762 return OK; // no output devices for the attributes
4763 }
jiabinf1c73972022-04-14 16:28:52 -07004764 return getProfilesForDevices(devices, audioProfilesVector,
4765 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004766}
4767
jiabina84c3d32022-12-02 18:59:55 +00004768status_t AudioPolicyManager::getSupportedMixerAttributes(
4769 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4770 ALOGV("%s, portId=%d", __func__, portId);
4771 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4772 if (deviceDescriptor == nullptr) {
4773 ALOGE("%s the requested device is currently unavailable", __func__);
4774 return BAD_VALUE;
4775 }
jiabin96daffc2023-05-11 17:51:55 +00004776 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4777 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4778 deviceDescriptor->type());
4779 return BAD_VALUE;
4780 }
jiabina84c3d32022-12-02 18:59:55 +00004781 for (const auto& hwModule : mHwModules) {
4782 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4783 if (curProfile->supportsDevice(deviceDescriptor)) {
4784 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4785 }
4786 }
4787 }
4788 return NO_ERROR;
4789}
4790
4791status_t AudioPolicyManager::setPreferredMixerAttributes(
4792 const audio_attributes_t *attr,
4793 audio_port_handle_t portId,
4794 uid_t uid,
4795 const audio_mixer_attributes_t *mixerAttributes) {
4796 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4797 "mixerBehavior=%d}, uid=%d, portId=%u",
4798 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4799 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4800 mixerAttributes->mixer_behavior, uid, portId);
4801 if (attr->usage != AUDIO_USAGE_MEDIA) {
4802 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4803 return BAD_VALUE;
4804 }
4805 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4806 if (deviceDescriptor == nullptr) {
4807 ALOGE("%s the requested device is currently unavailable", __func__);
4808 return BAD_VALUE;
4809 }
4810 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4811 ALOGE("%s(%d), type=%d, is not a usb output device",
4812 __func__, portId, deviceDescriptor->type());
4813 return BAD_VALUE;
4814 }
4815
4816 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4817 audio_flags_to_audio_output_flags(attr->flags, &flags);
4818 flags = (audio_output_flags_t) (flags |
4819 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4820 sp<IOProfile> profile = nullptr;
4821 DeviceVector devices(deviceDescriptor);
4822 for (const auto& hwModule : mHwModules) {
4823 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4824 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004825 && curProfile->getCompatibilityScore(
4826 devices,
4827 mixerAttributes->config.sample_rate,
4828 nullptr /*updatedSamplingRate*/,
4829 mixerAttributes->config.format,
4830 nullptr /*updatedFormat*/,
4831 mixerAttributes->config.channel_mask,
4832 nullptr /*updatedChannelMask*/,
4833 flags,
4834 false /*exactMatchRequiredForInputFlags*/)
4835 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004836 profile = curProfile;
4837 break;
4838 }
4839 }
4840 }
4841 if (profile == nullptr) {
4842 ALOGE("%s, there is no compatible profile found", __func__);
4843 return BAD_VALUE;
4844 }
4845
4846 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4847 sp<PreferredMixerAttributesInfo>::make(
4848 uid, portId, profile, flags, *mixerAttributes);
4849 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4850 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4851
4852 // If 1) there is any client from the preferred mixer configuration owner that is currently
4853 // active and matches the strategy and 2) current output is on the preferred device and the
4854 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4855 // configuration.
4856 std::vector<audio_io_handle_t> outputsToReopen;
4857 for (size_t i = 0; i < mOutputs.size(); i++) {
4858 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004859 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4860 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004861 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004862 } else {
4863 for (const auto &client: output->getActiveClients()) {
4864 if (client->uid() == uid && client->strategy() == strategy) {
4865 client->setIsInvalid();
4866 outputsToReopen.push_back(output->mIoHandle);
4867 }
jiabina84c3d32022-12-02 18:59:55 +00004868 }
4869 }
4870 }
4871 }
4872 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4873 config.sample_rate = mixerAttributes->config.sample_rate;
4874 config.channel_mask = mixerAttributes->config.channel_mask;
4875 config.format = mixerAttributes->config.format;
4876 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004877 sp<SwAudioOutputDescriptor> desc =
4878 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4879 if (desc == nullptr) {
4880 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4881 continue;
4882 }
jiabin220eea12024-05-17 17:55:20 +00004883 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004884 }
4885
4886 return NO_ERROR;
4887}
4888
4889sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004890 audio_port_handle_t devicePortId,
4891 product_strategy_t strategy,
4892 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004893 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4894 if (it == mPreferredMixerAttrInfos.end()) {
4895 return nullptr;
4896 }
jiabind9a58d32023-06-01 17:57:30 +00004897 if (activeBitPerfectPreferred) {
4898 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004899 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004900 return info;
4901 }
4902 }
jiabina84c3d32022-12-02 18:59:55 +00004903 }
jiabind9a58d32023-06-01 17:57:30 +00004904 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4905 return strategyMatchedMixerAttrInfoIt == it->second.end()
4906 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004907}
4908
4909status_t AudioPolicyManager::getPreferredMixerAttributes(
4910 const audio_attributes_t *attr,
4911 audio_port_handle_t portId,
4912 audio_mixer_attributes_t* mixerAttributes) {
4913 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4914 portId, mEngine->getProductStrategyForAttributes(*attr));
4915 if (info == nullptr) {
4916 return NAME_NOT_FOUND;
4917 }
4918 *mixerAttributes = info->getMixerAttributes();
4919 return NO_ERROR;
4920}
4921
4922status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4923 audio_port_handle_t portId,
4924 uid_t uid) {
4925 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4926 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4927 if (preferredMixerAttrInfo == nullptr) {
4928 return NAME_NOT_FOUND;
4929 }
4930 if (preferredMixerAttrInfo->getUid() != uid) {
4931 ALOGE("%s, requested uid=%d, owned uid=%d",
4932 __func__, uid, preferredMixerAttrInfo->getUid());
4933 return PERMISSION_DENIED;
4934 }
4935 mPreferredMixerAttrInfos[portId].erase(strategy);
4936 if (mPreferredMixerAttrInfos[portId].empty()) {
4937 mPreferredMixerAttrInfos.erase(portId);
4938 }
4939
4940 // Reconfig existing output
4941 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4942 for (size_t i = 0; i < mOutputs.size(); i++) {
4943 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4944 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4945 }
4946 }
4947 for (const auto output : potentialOutputsToReopen) {
4948 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4949 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4950 preferredMixerAttrInfo->getFlags())) {
4951 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4952 }
4953 }
4954 return NO_ERROR;
4955}
4956
Eric Laurent6a94d692014-05-20 11:18:06 -07004957status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4958 audio_port_type_t type,
4959 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004960 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 unsigned int *generation)
4962{
jiabin19cdba52020-11-24 11:28:58 -08004963 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4964 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 return BAD_VALUE;
4966 }
4967 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004968 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004969 *num_ports = 0;
4970 }
4971
4972 size_t portsWritten = 0;
4973 size_t portsMax = *num_ports;
4974 *num_ports = 0;
4975 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004976 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4977 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004978 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004979 for (const auto& dev : mAvailableOutputDevices) {
4980 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004981 continue;
4982 }
4983 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004984 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004985 }
4986 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004987 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 }
4989 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004990 for (const auto& dev : mAvailableInputDevices) {
4991 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004992 continue;
4993 }
4994 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004995 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004996 }
4997 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 }
5000 }
5001 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5002 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5003 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5004 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5005 }
5006 *num_ports += mInputs.size();
5007 }
5008 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005009 size_t numOutputs = 0;
5010 for (size_t i = 0; i < mOutputs.size(); i++) {
5011 if (!mOutputs[i]->isDuplicated()) {
5012 numOutputs++;
5013 if (portsWritten < portsMax) {
5014 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5015 }
5016 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 }
Eric Laurent84c70242014-06-23 08:46:27 -07005018 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005019 }
5020 }
jiabina84c3d32022-12-02 18:59:55 +00005021
Eric Laurent6a94d692014-05-20 11:18:06 -07005022 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005023 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 return NO_ERROR;
5025}
5026
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005027status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5028 std::vector<media::AudioPortFw>* _aidl_return) {
5029 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5030 audio_port_v7 port;
5031 dev->toAudioPort(&port);
5032 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5033 _aidl_return->push_back(std::move(aidlPort));
5034 return OK;
5035 };
5036
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005037 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005038 for (const auto& dev : module->getDeclaredDevices()) {
5039 if (role == media::AudioPortRole::NONE ||
5040 ((role == media::AudioPortRole::SOURCE)
5041 == audio_is_input_device(dev->type()))) {
5042 RETURN_STATUS_IF_ERROR(pushPort(dev));
5043 }
5044 }
5045 }
5046 return OK;
5047}
5048
jiabin19cdba52020-11-24 11:28:58 -08005049status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005050{
Eric Laurent99fcae42018-05-17 16:59:18 -07005051 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5052 return BAD_VALUE;
5053 }
5054 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5055 if (dev != 0) {
5056 dev->toAudioPort(port);
5057 return NO_ERROR;
5058 }
5059 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5060 if (dev != 0) {
5061 dev->toAudioPort(port);
5062 return NO_ERROR;
5063 }
5064 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5065 if (out != 0) {
5066 out->toAudioPort(port);
5067 return NO_ERROR;
5068 }
5069 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5070 if (in != 0) {
5071 in->toAudioPort(port);
5072 return NO_ERROR;
5073 }
5074 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005075}
5076
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005077status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5078 audio_patch_handle_t *handle,
5079 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005080{
François Gaffieafd4cea2019-11-18 15:50:22 +01005081 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005082 if (handle == NULL || patch == NULL) {
5083 return BAD_VALUE;
5084 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005085 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005086 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005087 return BAD_VALUE;
5088 }
5089 // only one source per audio patch supported for now
5090 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005091 return INVALID_OPERATION;
5092 }
Eric Laurent874c42872014-08-08 15:13:39 -07005093 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005094 return INVALID_OPERATION;
5095 }
Eric Laurent874c42872014-08-08 15:13:39 -07005096 for (size_t i = 0; i < patch->num_sinks; i++) {
5097 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5098 return INVALID_OPERATION;
5099 }
5100 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005101
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005102 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5103 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5104 if (srcDevice == nullptr || sinkDevice == nullptr) {
5105 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5106 return BAD_VALUE;
5107 }
5108 ALOGV("%s between source %s and sink %s", __func__,
5109 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5110 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5111 // Default attributes, default volume priority, not to infer with non raw audio patches.
5112 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5113 const struct audio_port_config *source = &patch->sources[0];
5114 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005115 new SourceClientDescriptor(
5116 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5117 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005118 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005119 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005120
5121 status_t status =
5122 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5123
5124 if (status != NO_ERROR) {
5125 return INVALID_OPERATION;
5126 }
5127 mAudioSources.add(portId, sourceDesc);
5128 return NO_ERROR;
5129}
5130
5131status_t AudioPolicyManager::connectAudioSourceToSink(
5132 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5133 const struct audio_patch *patch,
5134 audio_patch_handle_t &handle,
5135 uid_t uid, uint32_t delayMs)
5136{
5137 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5138 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5139 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5140 return INVALID_OPERATION;
5141 }
5142 sourceDesc->connect(handle, sinkDevice);
5143 if (isMsdPatch(handle)) {
5144 return NO_ERROR;
5145 }
5146 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5147 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5148 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5149 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5150 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5151 goto FailurePatchAdded;
5152 }
5153 status = swOutput->start();
5154 if (status != NO_ERROR) {
5155 goto FailureSourceAdded;
5156 }
5157 swOutput->addClient(sourceDesc);
5158 status = startSource(swOutput, sourceDesc, &delayMs);
5159 if (status != NO_ERROR) {
5160 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5161 goto FailureSourceActive;
5162 }
5163 if (delayMs != 0) {
5164 usleep(delayMs * 1000);
5165 }
5166 return NO_ERROR;
5167
5168FailureSourceActive:
5169 swOutput->stop();
5170 releaseOutput(sourceDesc->portId());
5171FailureSourceAdded:
5172 sourceDesc->setSwOutput(nullptr);
5173FailurePatchAdded:
5174 releaseAudioPatchInternal(handle);
5175 return INVALID_OPERATION;
5176}
5177
5178status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5179 audio_patch_handle_t *handle,
5180 uid_t uid, uint32_t delayMs,
5181 const sp<SourceClientDescriptor>& sourceDesc)
5182{
5183 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 sp<AudioPatch> patchDesc;
5185 ssize_t index = mAudioPatches.indexOfKey(*handle);
5186
François Gaffieafd4cea2019-11-18 15:50:22 +01005187 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5188 patch->sources[0].role,
5189 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005190#if LOG_NDEBUG == 0
5191 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005192 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5193 patch->sinks[i].role,
5194 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005195 }
5196#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005197
5198 if (index >= 0) {
5199 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005200 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5201 __func__, mUidCached, patchDesc->getUid(), uid);
5202 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005203 return INVALID_OPERATION;
5204 }
5205 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005206 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 }
5208
5209 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005210 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005211 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005212 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 return BAD_VALUE;
5214 }
Eric Laurent84c70242014-06-23 08:46:27 -07005215 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5216 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 if (patchDesc != 0) {
5218 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005219 ALOGV("%s source id differs for patch current id %d new id %d",
5220 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005221 return BAD_VALUE;
5222 }
5223 }
Eric Laurent874c42872014-08-08 15:13:39 -07005224 DeviceVector devices;
5225 for (size_t i = 0; i < patch->num_sinks; i++) {
5226 // Only support mix to devices connection
5227 // TODO add support for mix to mix connection
5228 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005229 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005230 return INVALID_OPERATION;
5231 }
5232 sp<DeviceDescriptor> devDesc =
5233 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5234 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005235 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005236 return BAD_VALUE;
5237 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005238
jiabin66acc432024-02-06 00:57:36 +00005239 if (outputDesc->mProfile->getCompatibilityScore(
5240 DeviceVector(devDesc),
5241 patch->sources[0].sample_rate,
5242 nullptr, // updatedSamplingRate
5243 patch->sources[0].format,
5244 nullptr, // updatedFormat
5245 patch->sources[0].channel_mask,
5246 nullptr, // updatedChannelMask
5247 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005248 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005249 return INVALID_OPERATION;
5250 }
5251 devices.add(devDesc);
5252 }
5253 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005254 return INVALID_OPERATION;
5255 }
Eric Laurent874c42872014-08-08 15:13:39 -07005256
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005258 ALOGV("%s setting device %s on output %d",
5259 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305260 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 index = mAudioPatches.indexOfKey(*handle);
5262 if (index >= 0) {
5263 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005264 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005265 }
5266 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005267 patchDesc->setUid(uid);
5268 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005270 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 return INVALID_OPERATION;
5272 }
5273 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5274 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5275 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005276 // only one sink supported when connecting an input device to a mix
5277 if (patch->num_sinks > 1) {
5278 return INVALID_OPERATION;
5279 }
François Gaffie53615e22015-03-19 09:24:12 +01005280 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005281 if (inputDesc == NULL) {
5282 return BAD_VALUE;
5283 }
5284 if (patchDesc != 0) {
5285 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5286 return BAD_VALUE;
5287 }
5288 }
François Gaffie11d30102018-11-02 16:09:09 +01005289 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005290 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005291 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 return BAD_VALUE;
5293 }
5294
jiabin66acc432024-02-06 00:57:36 +00005295 if (inputDesc->mProfile->getCompatibilityScore(
5296 DeviceVector(device),
5297 patch->sinks[0].sample_rate,
5298 nullptr, /*updatedSampleRate*/
5299 patch->sinks[0].format,
5300 nullptr, /*updatedFormat*/
5301 patch->sinks[0].channel_mask,
5302 nullptr, /*updatedChannelMask*/
5303 // FIXME for the parameter type,
5304 // and the NONE
5305 (audio_output_flags_t)
5306 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005307 return INVALID_OPERATION;
5308 }
5309 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005310 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005311 device->toString().c_str(), inputDesc->mIoHandle);
5312 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005313 index = mAudioPatches.indexOfKey(*handle);
5314 if (index >= 0) {
5315 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005316 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005317 }
5318 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005319 patchDesc->setUid(uid);
5320 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005322 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 return INVALID_OPERATION;
5324 }
5325 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5326 // device to device connection
5327 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005328 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005329 return BAD_VALUE;
5330 }
5331 }
François Gaffie11d30102018-11-02 16:09:09 +01005332 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005333 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005334 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005335 return BAD_VALUE;
5336 }
Eric Laurent874c42872014-08-08 15:13:39 -07005337
Eric Laurent6a94d692014-05-20 11:18:06 -07005338 //update source and sink with our own data as the data passed in the patch may
5339 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005340 PatchBuilder patchBuilder;
5341 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005342
5343 // if first sink is to MSD, establish single MSD patch
5344 if (getMsdAudioOutDevices().contains(
5345 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5346 ALOGV("%s patching to MSD", __FUNCTION__);
5347 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5348 goto installPatch;
5349 }
5350
François Gaffieafd4cea2019-11-18 15:50:22 +01005351 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5352 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005353
Eric Laurent874c42872014-08-08 15:13:39 -07005354 for (size_t i = 0; i < patch->num_sinks; i++) {
5355 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005356 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005357 return INVALID_OPERATION;
5358 }
François Gaffie11d30102018-11-02 16:09:09 +01005359 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005360 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005361 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005362 return BAD_VALUE;
5363 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005364 audio_port_config sinkPortConfig = {};
5365 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5366 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005367
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005368 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5369 // volume management purpose (tracking activity)
5370 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5371 // in config XML to reach the sink so that is can be declared as available.
5372 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005373 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005374 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005375 // take care of dynamic routing for SwOutput selection,
5376 audio_attributes_t attributes = sourceDesc->attributes();
5377 audio_stream_type_t stream = sourceDesc->stream();
5378 audio_attributes_t resultAttr;
5379 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5380 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005381 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5382 config.channel_mask =
5383 (audio_channel_mask_get_representation(sourceMask)
5384 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5385 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005386 config.format = sourceDesc->config().format;
5387 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5388 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5389 bool isRequestedDeviceForExclusiveUse = false;
5390 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005391 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005392 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005393 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5394 &stream, sourceDesc->uid(), &config, &flags,
5395 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005396 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005397 if (output == AUDIO_IO_HANDLE_NONE) {
5398 ALOGV("%s no output for device %s",
5399 __FUNCTION__, sinkDevice->toString().c_str());
5400 return INVALID_OPERATION;
5401 }
5402 outputDesc = mOutputs.valueFor(output);
5403 if (outputDesc->isDuplicated()) {
5404 ALOGE("%s output is duplicated", __func__);
5405 return INVALID_OPERATION;
5406 }
François Gaffie7e39df22022-04-26 12:48:49 +02005407 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5408 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005409 } else {
5410 // Same for "raw patches" aka created from createAudioPatch API
5411 SortedVector<audio_io_handle_t> outputs =
5412 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5413 // if the sink device is reachable via an opened output stream, request to
5414 // go via this output stream by adding a second source to the patch
5415 // description
5416 output = selectOutput(outputs);
5417 if (output == AUDIO_IO_HANDLE_NONE) {
5418 ALOGE("%s no output available for internal patch sink", __func__);
5419 return INVALID_OPERATION;
5420 }
5421 outputDesc = mOutputs.valueFor(output);
5422 if (outputDesc->isDuplicated()) {
5423 ALOGV("%s output for device %s is duplicated",
5424 __func__, sinkDevice->toString().c_str());
5425 return INVALID_OPERATION;
5426 }
François Gaffie7e39df22022-04-26 12:48:49 +02005427 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005428 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005429 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005430 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005431 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005432 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005433 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5434 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005435 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5436 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005437 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005438 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005439 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005440 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005441 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005442 return INVALID_OPERATION;
5443 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005444 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005445 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005446 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005447 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005448 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005449 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005450 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005451 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5452 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005453 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005454 }
Eric Laurent83b88082014-06-20 18:31:16 -07005455 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005456 }
5457 // TODO: check from routing capabilities in config file and other conflicting patches
5458
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005459installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005460 status_t status = installPatch(
5461 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005462 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005463 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005464 return INVALID_OPERATION;
5465 }
5466 } else {
5467 return BAD_VALUE;
5468 }
5469 } else {
5470 return BAD_VALUE;
5471 }
5472 return NO_ERROR;
5473}
5474
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005475status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005476{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005477 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005478 ssize_t index = mAudioPatches.indexOfKey(handle);
5479
5480 if (index < 0) {
5481 return BAD_VALUE;
5482 }
5483 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005484 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5485 __func__, mUidCached, patchDesc->getUid(), uid);
5486 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005487 return INVALID_OPERATION;
5488 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005489 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5490 for (size_t i = 0; i < mAudioSources.size(); i++) {
5491 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5492 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5493 portId = sourceDesc->portId();
5494 break;
5495 }
5496 }
5497 return portId != AUDIO_PORT_HANDLE_NONE ?
5498 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005499}
Eric Laurent6a94d692014-05-20 11:18:06 -07005500
François Gaffieafd4cea2019-11-18 15:50:22 +01005501status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005502 uint32_t delayMs,
5503 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005504{
5505 ALOGV("%s patch %d", __func__, handle);
5506 if (mAudioPatches.indexOfKey(handle) < 0) {
5507 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5508 return BAD_VALUE;
5509 }
5510 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005511 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005512 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005513 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005514 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005515 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005516 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005517 return BAD_VALUE;
5518 }
5519
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305520 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005521 getNewOutputDevices(outputDesc, true /*fromCache*/),
5522 true,
5523 0,
5524 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005525 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5526 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005527 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005528 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005529 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005530 return BAD_VALUE;
5531 }
5532 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005533 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005534 true,
5535 NULL);
5536 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005537 status_t status =
5538 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5539 ALOGV("%s patch panel returned %d patchHandle %d",
5540 __func__, status, patchDesc->getAfHandle());
5541 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005542 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005543 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005544 // SW or HW Bridge
5545 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5546 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005547 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005548 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5549 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5550 outputDesc = sourceDesc->swOutput().promote();
5551 }
5552 if (outputDesc == nullptr) {
5553 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5554 // releaseOutput has already called closeOutput in case of direct output
5555 return NO_ERROR;
5556 }
François Gaffie7e39df22022-04-26 12:48:49 +02005557 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005558 // While using a HwBridge, force reconsidering device only if not reusing an existing
5559 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005560 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005561 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5562 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5563 // Reconsider device only for cases:
5564 // 1 / Active Output
5565 // 2 / Inactive Output previously hosting HwBridge
5566 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5567 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5568 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305569 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005570 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5571 outputDesc->devices(),
5572 force,
5573 0,
5574 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005575 } else {
5576 return BAD_VALUE;
5577 }
5578 } else {
5579 return BAD_VALUE;
5580 }
5581 return NO_ERROR;
5582}
5583
5584status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5585 struct audio_patch *patches,
5586 unsigned int *generation)
5587{
François Gaffie53615e22015-03-19 09:24:12 +01005588 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005589 return BAD_VALUE;
5590 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005591 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005592 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005593}
5594
Eric Laurente1715a42014-05-20 11:30:42 -07005595status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005596{
Eric Laurente1715a42014-05-20 11:30:42 -07005597 ALOGV("setAudioPortConfig()");
5598
5599 if (config == NULL) {
5600 return BAD_VALUE;
5601 }
5602 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5603 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005604 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5605 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005606 }
5607
Eric Laurenta121f902014-06-03 13:32:54 -07005608 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005609 if (config->type == AUDIO_PORT_TYPE_MIX) {
5610 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005611 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005612 if (outputDesc == NULL) {
5613 return BAD_VALUE;
5614 }
Eric Laurent84c70242014-06-23 08:46:27 -07005615 ALOG_ASSERT(!outputDesc->isDuplicated(),
5616 "setAudioPortConfig() called on duplicated output %d",
5617 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005618 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005619 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005620 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005621 if (inputDesc == NULL) {
5622 return BAD_VALUE;
5623 }
Eric Laurenta121f902014-06-03 13:32:54 -07005624 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005625 } else {
5626 return BAD_VALUE;
5627 }
5628 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5629 sp<DeviceDescriptor> deviceDesc;
5630 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5631 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5632 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5633 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5634 } else {
5635 return BAD_VALUE;
5636 }
5637 if (deviceDesc == NULL) {
5638 return BAD_VALUE;
5639 }
Eric Laurenta121f902014-06-03 13:32:54 -07005640 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005641 } else {
5642 return BAD_VALUE;
5643 }
5644
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005645 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005646 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5647 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005648 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005649 audioPortConfig->toAudioPortConfig(&newConfig, config);
5650 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005651 }
Eric Laurenta121f902014-06-03 13:32:54 -07005652 if (status != NO_ERROR) {
5653 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005654 }
Eric Laurente1715a42014-05-20 11:30:42 -07005655
5656 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005657}
5658
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005659void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5660{
Eric Laurentd60560a2015-04-10 11:31:20 -07005661 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005662 clearAudioPatches(uid);
5663 clearSessionRoutes(uid);
5664}
5665
Eric Laurent6a94d692014-05-20 11:18:06 -07005666void AudioPolicyManager::clearAudioPatches(uid_t uid)
5667{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005668 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005669 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005670 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005671 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005672 }
5673 }
5674}
5675
François Gaffiec005e562018-11-06 15:04:49 +01005676void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005677{
François Gaffiec005e562018-11-06 15:04:49 +01005678 // Take the first attributes following the product strategy as it is used to retrieve the routed
5679 // device. All attributes wihin a strategy follows the same "routing strategy"
5680 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5681 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005682 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005683 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005684 for (size_t j = 0; j < mOutputs.size(); j++) {
5685 if (mOutputs.keyAt(j) == ouptutToSkip) {
5686 continue;
5687 }
5688 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005689 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005690 continue;
5691 }
5692 // If the default device for this strategy is on another output mix,
5693 // invalidate all tracks in this strategy to force re connection.
5694 // Otherwise select new device on the output mix.
5695 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005696 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005697 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005698 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005699 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005700 // If the device is using preferred mixer attributes, the output need to reopen
5701 // with default configuration when the new selected devices are different from
5702 // current routing devices.
5703 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5704 continue;
5705 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305706 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005707 }
5708 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005709 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005710}
5711
5712void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5713{
5714 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005715 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005716 for (size_t i = 0; i < mOutputs.size(); i++) {
5717 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005718 for (const auto& client : outputDesc->getClientIterable()) {
5719 if (client->hasPreferredDevice() && client->uid() == uid) {
5720 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005721 auto clientStrategy = client->strategy();
5722 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5723 end(affectedStrategies)) {
5724 continue;
5725 }
5726 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005727 }
5728 }
5729 }
5730 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005731 for (const auto& strategy : affectedStrategies) {
5732 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005733 }
5734
5735 // remove input routes associated with this uid
5736 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005737 for (size_t i = 0; i < mInputs.size(); i++) {
5738 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005739 for (const auto& client : inputDesc->getClientIterable()) {
5740 if (client->hasPreferredDevice() && client->uid() == uid) {
5741 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5742 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005743 }
5744 }
5745 }
5746 // reroute inputs if necessary
5747 SortedVector<audio_io_handle_t> inputsToClose;
5748 for (size_t i = 0; i < mInputs.size(); i++) {
5749 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005750 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005751 inputsToClose.add(inputDesc->mIoHandle);
5752 }
5753 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005754 for (const auto& input : inputsToClose) {
5755 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005756 }
5757}
5758
Eric Laurentd60560a2015-04-10 11:31:20 -07005759void AudioPolicyManager::clearAudioSources(uid_t uid)
5760{
5761 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005762 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5763 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005764 stopAudioSource(mAudioSources.keyAt(i));
5765 }
5766 }
5767}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005768
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005769status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5770 audio_io_handle_t *ioHandle,
5771 audio_devices_t *device)
5772{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005773 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5774 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005775 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005776 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5777 if (deviceDesc == nullptr) {
5778 return INVALID_OPERATION;
5779 }
5780 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005781
François Gaffiedf372692015-03-19 10:43:27 +01005782 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005783}
5784
Eric Laurentd60560a2015-04-10 11:31:20 -07005785status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005786 const audio_attributes_t *attributes,
5787 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005788 uid_t uid) {
5789 return startAudioSourceInternal(source, attributes, portId, uid,
David Li48b6a832024-07-01 13:14:10 +00005790 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurent963dbcc2024-06-20 12:34:15 +00005791}
5792
5793status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5794 const audio_attributes_t *attributes,
5795 audio_port_handle_t *portId,
David Li48b6a832024-07-01 13:14:10 +00005796 uid_t uid, bool internal, bool isCallRx,
5797 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005798{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005799 ALOGV("%s", __FUNCTION__);
5800 *portId = AUDIO_PORT_HANDLE_NONE;
5801
5802 if (source == NULL || attributes == NULL || portId == NULL) {
5803 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5804 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005805 return BAD_VALUE;
5806 }
5807
Eric Laurentd60560a2015-04-10 11:31:20 -07005808 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5809 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005810 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5811 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005812 return INVALID_OPERATION;
5813 }
5814
François Gaffie11d30102018-11-02 16:09:09 +01005815 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005816 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005817 String8(source->ext.device.address),
5818 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005819 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005820 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005821 return BAD_VALUE;
5822 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005823
jiabin4ef93452019-09-10 14:29:54 -07005824 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005825
François Gaffieaaac0fd2018-11-22 17:56:39 +01005826 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005827 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005828 mEngine->getStreamTypeForAttributes(*attributes),
5829 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005830 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005831
David Li48b6a832024-07-01 13:14:10 +00005832 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005833 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005834 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005835 }
5836 return status;
5837}
5838
David Li48b6a832024-07-01 13:14:10 +00005839status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5840 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005841{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005842 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005843
5844 // make sure we only have one patch per source.
5845 disconnectAudioSource(sourceDesc);
5846
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005847 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005848 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5849 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5850 sourceDesc->srcDevice()->type(),
5851 String8(sourceDesc->srcDevice()->address().c_str()),
5852 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005853 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005854 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005855 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005856 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005857 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5858 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5859 return INVALID_OPERATION;
5860 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005861 PatchBuilder patchBuilder;
5862 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5863 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005864
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005865 return connectAudioSourceToSink(
David Li48b6a832024-07-01 13:14:10 +00005866 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005867}
5868
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005869status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005870{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005871 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5872 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005873 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005874 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005875 return BAD_VALUE;
5876 }
5877 status_t status = disconnectAudioSource(sourceDesc);
5878
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005879 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005880 return status;
5881}
5882
Andy Hung2ddee192015-12-18 17:34:44 -08005883status_t AudioPolicyManager::setMasterMono(bool mono)
5884{
5885 if (mMasterMono == mono) {
5886 return NO_ERROR;
5887 }
5888 mMasterMono = mono;
5889 // if enabling mono we close all offloaded devices, which will invalidate the
5890 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5891 // for recreating the new AudioTrack as non-offloaded PCM.
5892 //
5893 // If disabling mono, we leave all tracks as is: we don't know which clients
5894 // and tracks are able to be recreated as offloaded. The next "song" should
5895 // play back offloaded.
5896 if (mMasterMono) {
5897 Vector<audio_io_handle_t> offloaded;
5898 for (size_t i = 0; i < mOutputs.size(); ++i) {
5899 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5900 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5901 offloaded.push(desc->mIoHandle);
5902 }
5903 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005904 for (const auto& handle : offloaded) {
5905 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005906 }
5907 }
5908 // update master mono for all remaining outputs
5909 for (size_t i = 0; i < mOutputs.size(); ++i) {
5910 updateMono(mOutputs.keyAt(i));
5911 }
5912 return NO_ERROR;
5913}
5914
5915status_t AudioPolicyManager::getMasterMono(bool *mono)
5916{
5917 *mono = mMasterMono;
5918 return NO_ERROR;
5919}
5920
Eric Laurentac9cef52017-06-09 15:46:26 -07005921float AudioPolicyManager::getStreamVolumeDB(
5922 audio_stream_type_t stream, int index, audio_devices_t device)
5923{
jiabin9a3361e2019-10-01 09:38:30 -07005924 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005925}
5926
jiabin81772902018-04-02 17:52:27 -07005927status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5928 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005929 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005930{
Kriti Dang6537def2021-03-02 13:46:59 +01005931 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5932 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005933 return BAD_VALUE;
5934 }
Kriti Dang6537def2021-03-02 13:46:59 +01005935 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5936 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005937
5938 size_t formatsWritten = 0;
5939 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005940
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005941 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005942 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5943 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005944 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005945 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005946 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005947 bool formatEnabled = true;
5948 switch (forceUse) {
5949 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005950 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005951 break;
5952 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5953 formatEnabled = false;
5954 break;
5955 default: // AUTO or ALWAYS => true
5956 break;
jiabin81772902018-04-02 17:52:27 -07005957 }
5958 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5959 }
jiabin81772902018-04-02 17:52:27 -07005960 }
5961 return NO_ERROR;
5962}
5963
Kriti Dang6537def2021-03-02 13:46:59 +01005964status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5965 audio_format_t *surroundFormats) {
5966 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5967 return BAD_VALUE;
5968 }
5969 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5970 __func__, *numSurroundFormats, surroundFormats);
5971
5972 size_t formatsWritten = 0;
5973 size_t formatsMax = *numSurroundFormats;
5974 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5975
5976 // Return formats from all device profiles that have already been resolved by
5977 // checkOutputsForDevice().
5978 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5979 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5980 audio_devices_t deviceType = device->type();
5981 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5982 // returns formats reported by HDMI devices.
5983 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5984 continue;
5985 }
5986 // Formats reported by sink devices
5987 std::unordered_set<audio_format_t> formatset;
5988 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5989 formatset.insert(it->second.begin(), it->second.end());
5990 }
5991
5992 // Formats hard-coded in the in policy configuration file (if any).
5993 FormatVector encodedFormats = device->encodedFormats();
5994 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5995 // Filter the formats which are supported by the vendor hardware.
5996 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005997 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005998 formats.insert(*it);
5999 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006000 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006001 if (pair.second.count(*it) != 0) {
6002 formats.insert(pair.first);
6003 break;
6004 }
6005 }
6006 }
6007 }
6008 }
6009 *numSurroundFormats = formats.size();
6010 for (const auto& format: formats) {
6011 if (formatsWritten < formatsMax) {
6012 surroundFormats[formatsWritten++] = format;
6013 }
6014 }
6015 return NO_ERROR;
6016}
6017
jiabin81772902018-04-02 17:52:27 -07006018status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6019{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006020 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006021 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6022 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006023 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006024 return BAD_VALUE;
6025 }
6026
Mikhail Naganov100f0122018-11-29 11:22:16 -08006027 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6028 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006029 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006030 return INVALID_OPERATION;
6031 }
6032
Mikhail Naganov100f0122018-11-29 11:22:16 -08006033 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006034 return NO_ERROR;
6035 }
6036
Mikhail Naganov100f0122018-11-29 11:22:16 -08006037 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006038 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006039 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006040 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006041 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006042 }
6043 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006044 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006045 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006046 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006047 }
6048 }
6049
6050 sp<SwAudioOutputDescriptor> outputDesc;
6051 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006052 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6053 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006054 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6055 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006056 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006057 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006058 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6059 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6060 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006061 name.c_str(),
6062 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006063 if (status != NO_ERROR) {
6064 continue;
6065 }
6066 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6067 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6068 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006069 name.c_str(),
6070 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006071 profileUpdated |= (status == NO_ERROR);
6072 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006073 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006074 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006075 AUDIO_DEVICE_IN_HDMI);
6076 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6077 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006078 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006079 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006080 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6081 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6082 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006083 name.c_str(),
6084 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006085 if (status != NO_ERROR) {
6086 continue;
6087 }
6088 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6089 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
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 profileUpdated |= (status == NO_ERROR);
6094 }
6095
jiabin81772902018-04-02 17:52:27 -07006096 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006097 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006098 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006099 }
6100
6101 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6102}
6103
Eric Laurent5ada82e2019-08-29 17:53:54 -07006104void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006105{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006106 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006107 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006108 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006109 }
6110}
6111
jiabin6012f912018-11-02 17:06:30 -07006112bool AudioPolicyManager::isHapticPlaybackSupported()
6113{
6114 for (const auto& hwModule : mHwModules) {
6115 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6116 for (const auto &outProfile : outputProfiles) {
6117 struct audio_port audioPort;
6118 outProfile->toAudioPort(&audioPort);
6119 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6120 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6121 return true;
6122 }
6123 }
6124 }
6125 }
6126 return false;
6127}
6128
Carter Hsu325a8eb2022-01-19 19:56:51 +08006129bool AudioPolicyManager::isUltrasoundSupported()
6130{
6131 bool hasUltrasoundOutput = false;
6132 bool hasUltrasoundInput = false;
6133 for (const auto& hwModule : mHwModules) {
6134 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6135 if (!hasUltrasoundOutput) {
6136 for (const auto &outProfile : outputProfiles) {
6137 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6138 hasUltrasoundOutput = true;
6139 break;
6140 }
6141 }
6142 }
6143
6144 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6145 if (!hasUltrasoundInput) {
6146 for (const auto &inputProfile : inputProfiles) {
6147 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6148 hasUltrasoundInput = true;
6149 break;
6150 }
6151 }
6152 }
6153
6154 if (hasUltrasoundOutput && hasUltrasoundInput)
6155 return true;
6156 }
6157 return false;
6158}
6159
Atneya Nair698f5ef2022-12-15 16:15:09 -08006160bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6161{
6162 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6163 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6164 for (const auto& hwModule : mHwModules) {
6165 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6166 for (const auto &inputProfile : inputProfiles) {
6167 if ((inputProfile->getFlags() & mask) == mask) {
6168 return true;
6169 }
6170 }
6171 }
6172 return false;
6173}
6174
Eric Laurent8340e672019-11-06 11:01:08 -08006175bool AudioPolicyManager::isCallScreenModeSupported()
6176{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006177 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006178}
6179
6180
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006181status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006182{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006183 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006184 if (!sourceDesc->isConnected()) {
6185 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6186 return NO_ERROR;
6187 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006188 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6189 if (swOutput != 0) {
6190 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006191 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006192 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006193 }
jiabinbce0c1d2020-10-05 11:20:18 -07006194 if (releaseOutput(sourceDesc->portId())) {
6195 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6196 // no need to release audio patch here but just return NO_ERROR.
6197 return NO_ERROR;
6198 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006199 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006200 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006201 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006202 // close Hwoutput and remove from mHwOutputs
6203 } else {
6204 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6205 }
6206 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006207 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006208 sourceDesc->disconnect();
6209 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006210}
6211
François Gaffiec005e562018-11-06 15:04:49 +01006212sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6213 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006214{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006215 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006216 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006217 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006218 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006219 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6220 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006221 source = sourceDesc;
6222 break;
6223 }
6224 }
6225 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006226}
6227
Eric Laurentb4f42a92022-01-17 17:37:31 +01006228bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006229 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006230 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006231{
6232 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6233 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006234 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006235 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006236 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6237 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6238 return false;
6239 }
6240 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6241 return false;
6242 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006243 }
6244
Eric Laurentd332bc82023-08-04 11:45:23 +02006245 // The caller can have the audio config criteria ignored by either passing a null ptr or
6246 // the AUDIO_CONFIG_INITIALIZER value.
6247 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006248 // some positional channel masks and PCM format and for stereo if low latency performance
6249 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006250
6251 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006252 static const bool stereo_spatialization_enabled =
6253 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006254 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006255 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006256 ? audio_channel_mask_contains_stereo(config->channel_mask)
6257 : audio_is_channel_mask_spatialized(config->channel_mask);
6258 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006259 return false;
6260 }
6261 if (!audio_is_linear_pcm(config->format)) {
6262 return false;
6263 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006264 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6265 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6266 return false;
6267 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006268 }
6269
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006270 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006271 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006272 if (profile == nullptr) {
6273 return false;
6274 }
6275
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006276 return true;
6277}
6278
Shunkai Yao57b93392024-04-26 04:12:21 +00006279// The Spatializer output is compatible with Haptic use cases if:
6280// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6281// with client if client haptic channel bits were set, or
6282// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6283// including the haptic bits or creating the HapticGenerator effect for same session.
6284bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6285 const audio_config_t* config, audio_session_t sessionId) const {
6286 const auto clientHapticChannel =
6287 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6288 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6289 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6290
6291 if (threadOutputHapticChannel) {
6292 // check format and sampleRate match if client haptic channel mask exist
6293 if (clientHapticChannel) {
6294 return mSpatializerOutput->getFormat() == config->format &&
6295 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6296 }
6297 return true;
6298 } else {
6299 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6300 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6301 // HapticGenerator effect for this session) are not supported.
6302 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006303 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006304 }
6305}
6306
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006307void AudioPolicyManager::checkVirtualizerClientRoutes() {
6308 std::set<audio_stream_type_t> streamsToInvalidate;
6309 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006310 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6311 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006312 audio_attributes_t attr = client->attributes();
6313 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6314 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6315 audio_config_base_t clientConfig = client->config();
6316 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006317 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006318 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006319 streamsToInvalidate.insert(client->stream());
6320 }
6321 }
6322 }
6323
jiabinc44b3462022-12-08 12:52:31 -08006324 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006325}
6326
Eric Laurente191d1b2022-04-15 11:59:25 +02006327
6328bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6329 const sp<SwAudioOutputDescriptor>& outputDesc) {
6330 if (outputDesc->isDuplicated()) {
6331 return false;
6332 }
6333 DeviceVector devices = outputDesc->supportedDevices();
6334 for (size_t i = 0; i < mOutputs.size(); i++) {
6335 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6336 if (desc == outputDesc || desc->isDuplicated()) {
6337 continue;
6338 }
6339 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6340 if (!sharedDevices.isEmpty()
6341 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6342 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6343 return false;
6344 }
6345 }
6346 return true;
6347}
6348
6349
Eric Laurentfa0f6742021-08-17 18:39:44 +02006350status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006351 const audio_attributes_t *attr,
6352 audio_io_handle_t *output) {
6353 *output = AUDIO_IO_HANDLE_NONE;
6354
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006355 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6356 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6357 audio_config_t *configPtr = nullptr;
6358 audio_config_t config;
6359 if (mixerConfig != nullptr) {
6360 config = audio_config_initializer(mixerConfig);
6361 configPtr = &config;
6362 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006363 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006364 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006365 return BAD_VALUE;
6366 }
6367
6368 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006369 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006370 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006371 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006372 return BAD_VALUE;
6373 }
6374
Eric Laurente191d1b2022-04-15 11:59:25 +02006375 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006376 for (size_t i = 0; i < mOutputs.size(); i++) {
6377 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006378 if (!desc->isDuplicated()
6379 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6380 spatializerOutputs.push_back(desc);
6381 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006382 }
6383 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006384 mSpatializerOutput.clear();
6385 bool outputsChanged = false;
6386 for (const auto& desc : spatializerOutputs) {
6387 if (desc->mProfile == profile
6388 && (configPtr == nullptr
6389 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6390 mSpatializerOutput = desc;
6391 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6392 } else {
6393 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6394 " and devices %s", __func__, desc->mIoHandle,
6395 configPtr != nullptr ? configPtr->channel_mask : 0,
6396 devices.toString().c_str());
6397 closeOutput(desc->mIoHandle);
6398 outputsChanged = true;
6399 }
Eric Laurent39095982021-08-24 18:29:27 +02006400 }
6401
Eric Laurente191d1b2022-04-15 11:59:25 +02006402 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006403 sp<SwAudioOutputDescriptor> desc =
6404 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006405 if (desc != nullptr) {
6406 mSpatializerOutput = desc;
6407 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006408 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006409 }
6410
6411 checkVirtualizerClientRoutes();
6412
Eric Laurente191d1b2022-04-15 11:59:25 +02006413 if (outputsChanged) {
6414 mPreviousOutputs = mOutputs;
6415 mpClientInterface->onAudioPortListUpdate();
6416 }
6417
6418 if (mSpatializerOutput == nullptr) {
6419 ALOGV("%s could not open spatializer output with requested config", __func__);
6420 return BAD_VALUE;
6421 }
Eric Laurent39095982021-08-24 18:29:27 +02006422 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006423 ALOGV("%s returning new spatializer output %d", __func__, *output);
6424 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006425}
6426
Eric Laurentfa0f6742021-08-17 18:39:44 +02006427status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6428 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006429 return INVALID_OPERATION;
6430 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006431 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006432 return BAD_VALUE;
6433 }
Eric Laurent39095982021-08-24 18:29:27 +02006434
Eric Laurente191d1b2022-04-15 11:59:25 +02006435 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6436 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6437 closeOutput(mSpatializerOutput->mIoHandle);
6438 //from now on mSpatializerOutput is null
6439 checkVirtualizerClientRoutes();
6440 }
Eric Laurent39095982021-08-24 18:29:27 +02006441
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006442 return NO_ERROR;
6443}
6444
Eric Laurente552edb2014-03-10 17:42:56 -07006445// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006446// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006447// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006448uint32_t AudioPolicyManager::nextAudioPortGeneration()
6449{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006450 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006451}
6452
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006453AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006454 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006455 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006456 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006457 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006458 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006459 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006460 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006461 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006462 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006463 mAudioPortGeneration(1),
6464 mBeaconMuteRefCount(0),
6465 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006466 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006467 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006468 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006469 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006470{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006471}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006472
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006473status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006474 if (mEngine == nullptr) {
6475 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006476 }
6477 mEngine->setObserver(this);
6478 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006479 if (status != NO_ERROR) {
6480 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6481 return status;
6482 }
François Gaffie2110e042015-03-24 08:41:51 +01006483
jiabin29230182023-04-04 21:02:36 +00006484 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6485 // at the end of this function.
6486 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006487 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6488 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6489
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006490 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006491 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006492 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006493
Eric Laurent3a4311c2014-03-17 12:00:47 -07006494 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006495 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6496 defaultOutputDevice == nullptr ||
6497 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6498 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6499 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006500 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006501 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006502 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006503
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006504 // Silence ALOGV statements
6505 property_set("log.tag." LOG_TAG, "D");
6506
Eric Laurente552edb2014-03-10 17:42:56 -07006507 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006508 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006509}
6510
Eric Laurente0720872014-03-11 09:30:41 -07006511AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006512{
Eric Laurente552edb2014-03-10 17:42:56 -07006513 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006514 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006515 }
6516 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006517 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006518 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006519 mAvailableOutputDevices.clear();
6520 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006521 mOutputs.clear();
6522 mInputs.clear();
6523 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006524 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006525 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006526}
6527
Eric Laurente0720872014-03-11 09:30:41 -07006528status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006529{
Eric Laurent87ffa392015-05-22 10:32:38 -07006530 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006531}
6532
Eric Laurente552edb2014-03-10 17:42:56 -07006533// ---
6534
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006535void AudioPolicyManager::onNewAudioModulesAvailable()
6536{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006537 DeviceVector newDevices;
6538 onNewAudioModulesAvailableInt(&newDevices);
6539 if (!newDevices.empty()) {
6540 nextAudioPortGeneration();
6541 mpClientInterface->onAudioPortListUpdate();
6542 }
6543}
6544
6545void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6546{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006547 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006548 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6549 continue;
6550 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006551 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006552 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6553 handle != AUDIO_MODULE_HANDLE_NONE) {
6554 hwModule->setHandle(handle);
6555 } else {
6556 ALOGW("could not load HW module %s", hwModule->getName());
6557 continue;
6558 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006559 }
6560 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006561 // open all output streams needed to access attached devices.
6562 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006563 // This also validates mAvailableOutputDevices list
6564 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6565 if (!outProfile->canOpenNewIo()) {
6566 ALOGE("Invalid Output profile max open count %u for profile %s",
6567 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6568 continue;
6569 }
6570 if (!outProfile->hasSupportedDevices()) {
6571 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6572 continue;
6573 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006574 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6575 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006576 mTtsOutputAvailable = true;
6577 }
6578
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006579 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006580 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006581 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006582 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6583 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006584 } else {
6585 // choose first device present in profile's SupportedDevices also part of
6586 // mAvailableOutputDevices.
6587 if (availProfileDevices.isEmpty()) {
6588 continue;
6589 }
6590 supportedDevice = availProfileDevices.itemAt(0);
6591 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006592 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006593 continue;
6594 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306595
6596 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6597 && availProfileDevices.areAllDevicesAttached()) {
6598 ALOGV("%s skip opening output for mmap profile %s", __func__,
6599 outProfile->getTagName().c_str());
6600 continue;
6601 }
6602
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006603 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6604 mpClientInterface);
6605 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006606 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006607 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6608 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006609 AUDIO_STREAM_DEFAULT,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006610 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006611 if (status != NO_ERROR) {
6612 ALOGW("Cannot open output stream for devices %s on hw module %s",
6613 supportedDevice->toString().c_str(), hwModule->getName());
6614 continue;
6615 }
6616 for (const auto &device : availProfileDevices) {
6617 // give a valid ID to an attached device once confirmed it is reachable
6618 if (!device->isAttached()) {
6619 device->attach(hwModule);
6620 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006621 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006622 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006623 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6624 }
6625 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006626 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006627 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6628 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006629 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006630 }
Eric Laurent39095982021-08-24 18:29:27 +02006631 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006632 outputDesc->close();
6633 } else {
6634 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306635 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006636 DeviceVector(supportedDevice),
6637 true,
6638 0,
6639 NULL);
6640 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006641 }
6642 // open input streams needed to access attached devices to validate
6643 // mAvailableInputDevices list
6644 for (const auto& inProfile : hwModule->getInputProfiles()) {
6645 if (!inProfile->canOpenNewIo()) {
6646 ALOGE("Invalid Input profile max open count %u for profile %s",
6647 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6648 continue;
6649 }
6650 if (!inProfile->hasSupportedDevices()) {
6651 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6652 continue;
6653 }
6654 // chose first device present in profile's SupportedDevices also part of
6655 // available input devices
6656 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006657 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006658 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006659 ALOGV("%s: Input device list is empty! for profile %s",
6660 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006661 continue;
6662 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306663
6664 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6665 && availProfileDevices.areAllDevicesAttached()) {
6666 ALOGV("%s skip opening input for mmap profile %s", __func__,
6667 inProfile->getTagName().c_str());
6668 continue;
6669 }
6670
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006671 sp<AudioInputDescriptor> inputDesc =
6672 new AudioInputDescriptor(inProfile, mpClientInterface);
6673
6674 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6675 status_t status = inputDesc->open(nullptr,
6676 availProfileDevices.itemAt(0),
6677 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006678 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006679 &input);
6680 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306681 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6682 __func__, availProfileDevices.toString().c_str(),
6683 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006684 continue;
6685 }
6686 for (const auto &device : availProfileDevices) {
6687 // give a valid ID to an attached device once confirmed it is reachable
6688 if (!device->isAttached()) {
6689 device->attach(hwModule);
6690 device->importAudioPortAndPickAudioProfile(inProfile, true);
6691 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006692 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006693 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6694 }
6695 }
6696 inputDesc->close();
6697 }
6698 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006699
6700 // Check if spatializer outputs can be closed until used.
6701 // mOutputs vector never contains duplicated outputs at this point.
6702 std::vector<audio_io_handle_t> outputsClosed;
6703 for (size_t i = 0; i < mOutputs.size(); i++) {
6704 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6705 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6706 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6707 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006708 nextAudioPortGeneration();
6709 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6710 if (index >= 0) {
6711 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6712 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6713 patchDesc->getAfHandle(), 0);
6714 mAudioPatches.removeItemsAt(index);
6715 mpClientInterface->onAudioPatchListUpdate();
6716 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006717 desc->close();
6718 }
6719 }
6720 for (auto output : outputsClosed) {
6721 removeOutput(output);
6722 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006723}
6724
Eric Laurent98e38192018-02-15 18:31:53 -08006725void AudioPolicyManager::addOutput(audio_io_handle_t output,
6726 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006727{
Eric Laurent1c333e22014-05-20 10:48:17 -07006728 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006729 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006730 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006731 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006732 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006733}
6734
François Gaffie53615e22015-03-19 09:24:12 +01006735void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6736{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006737 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6738 ALOGV("%s: removing primary output", __func__);
6739 mPrimaryOutput = nullptr;
6740 }
François Gaffie53615e22015-03-19 09:24:12 +01006741 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006742 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006743}
6744
Eric Laurent98e38192018-02-15 18:31:53 -08006745void AudioPolicyManager::addInput(audio_io_handle_t input,
6746 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006747{
Eric Laurent1c333e22014-05-20 10:48:17 -07006748 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006749 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006750}
Eric Laurente552edb2014-03-10 17:42:56 -07006751
François Gaffie11d30102018-11-02 16:09:09 +01006752status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006753 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006754 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006755{
François Gaffie11d30102018-11-02 16:09:09 +01006756 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006757 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006758 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006759
François Gaffie11d30102018-11-02 16:09:09 +01006760 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006761 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006762 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006763 }
Eric Laurente552edb2014-03-10 17:42:56 -07006764
Eric Laurent3b73df72014-03-11 09:06:29 -07006765 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006766 // first call getAudioPort to get the supported attributes from the HAL
6767 struct audio_port_v7 port = {};
6768 device->toAudioPort(&port);
6769 status_t status = mpClientInterface->getAudioPort(&port);
6770 if (status == NO_ERROR) {
6771 device->importAudioPort(port);
6772 }
6773
6774 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006775 for (size_t i = 0; i < mOutputs.size(); i++) {
6776 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006777 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006778 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006779 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6780 mOutputs.keyAt(i), device->toString().c_str());
6781 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006782 }
6783 }
6784 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006785 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006786 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006787 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6788 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006789 if (profile->supportsDevice(device)) {
6790 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306791 ALOGV("%s(): adding profile %s from module %s",
6792 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006793 }
6794 }
6795 }
6796
Eric Laurent7b279bb2015-12-14 10:18:23 -08006797 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006798
Eric Laurente552edb2014-03-10 17:42:56 -07006799 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006800 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006801 return BAD_VALUE;
6802 }
6803
6804 // open outputs for matching profiles if needed. Direct outputs are also opened to
6805 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6806 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006807 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006808
6809 // nothing to do if one output is already opened for this profile
6810 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006811 for (j = 0; j < outputs.size(); j++) {
6812 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006813 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006814 // matching profile: save the sample rates, format and channel masks supported
6815 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006816 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006817 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006818 }
Eric Laurente552edb2014-03-10 17:42:56 -07006819 break;
6820 }
6821 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006822 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006823 continue;
6824 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306825 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6826 ALOGV("%s skip opening output for mmap profile %s",
6827 __func__, profile->getTagName().c_str());
6828 continue;
6829 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006830 if (!profile->canOpenNewIo()) {
6831 ALOGW("Max Output number %u already opened for this profile %s",
6832 profile->maxOpenCount, profile->getTagName().c_str());
6833 continue;
6834 }
6835
Eric Laurent83efe1c2017-07-09 16:51:08 -07006836 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006837 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006838 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6839 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006840 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006841 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006842 profiles.removeAt(profile_index);
6843 profile_index--;
6844 } else {
6845 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006846 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006847 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006848 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6849 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006850 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006851 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006852
François Gaffie11d30102018-11-02 16:09:09 +01006853 if (device_distinguishes_on_address(deviceType)) {
6854 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6855 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306856 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6857 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006858 }
Eric Laurente552edb2014-03-10 17:42:56 -07006859 ALOGV("checkOutputsForDevice(): adding output %d", output);
6860 }
6861 }
6862
6863 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006864 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006865 return BAD_VALUE;
6866 }
Eric Laurentd4692962014-05-05 18:13:44 -07006867 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006868 // check if one opened output is not needed any more after disconnecting one device
6869 for (size_t i = 0; i < mOutputs.size(); i++) {
6870 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006871 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006872 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006873 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006874 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006875 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006876 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006877 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6878 mOutputs.keyAt(i));
6879 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006880 }
Eric Laurente552edb2014-03-10 17:42:56 -07006881 }
6882 }
Eric Laurentd4692962014-05-05 18:13:44 -07006883 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006884 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006885 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6886 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006887 if (!profile->supportsDevice(device)) {
6888 continue;
6889 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306890 ALOGV("%s(): clearing direct output profile %s on module %s",
6891 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006892 profile->clearAudioProfiles();
6893 if (!profile->hasDynamicAudioProfile()) {
6894 continue;
6895 }
6896 // When a device is disconnected, if there is an IOProfile that contains dynamic
6897 // profiles and supports the disconnected device, call getAudioPort to repopulate
6898 // the capabilities of the devices that is supported by the IOProfile.
6899 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6900 if (supportedDevice == device ||
6901 !mAvailableOutputDevices.contains(supportedDevice)) {
6902 continue;
6903 }
6904 struct audio_port_v7 port;
6905 supportedDevice->toAudioPort(&port);
6906 status_t status = mpClientInterface->getAudioPort(&port);
6907 if (status == NO_ERROR) {
6908 supportedDevice->importAudioPort(port);
6909 }
Eric Laurente552edb2014-03-10 17:42:56 -07006910 }
6911 }
6912 }
6913 }
6914 return NO_ERROR;
6915}
6916
François Gaffie11d30102018-11-02 16:09:09 +01006917status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006918 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006919{
François Gaffie11d30102018-11-02 16:09:09 +01006920 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006921 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006922 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006923 }
6924
Eric Laurentd4692962014-05-05 18:13:44 -07006925 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006926 sp<AudioInputDescriptor> desc;
6927
jiabinbf5f4262023-04-12 21:48:34 +00006928 // first call getAudioPort to get the supported attributes from the HAL
6929 struct audio_port_v7 port = {};
6930 device->toAudioPort(&port);
6931 status_t status = mpClientInterface->getAudioPort(&port);
6932 if (status == NO_ERROR) {
6933 device->importAudioPort(port);
6934 }
6935
Eric Laurent0dd51852019-04-19 18:18:58 -07006936 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006937 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006938 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006939 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006940 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006941 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006942 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006943
François Gaffie11d30102018-11-02 16:09:09 +01006944 if (profile->supportsDevice(device)) {
6945 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306946 ALOGV("%s : adding profile %s from module %s", __func__,
6947 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006948 }
6949 }
6950 }
6951
Eric Laurent0dd51852019-04-19 18:18:58 -07006952 if (profiles.isEmpty()) {
6953 ALOGW("%s: No input profile available for device %s",
6954 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006955 return BAD_VALUE;
6956 }
6957
6958 // open inputs for matching profiles if needed. Direct inputs are also opened to
6959 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6960 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6961
Eric Laurent1c333e22014-05-20 10:48:17 -07006962 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006963
Eric Laurentd4692962014-05-05 18:13:44 -07006964 // nothing to do if one input is already opened for this profile
6965 size_t input_index;
6966 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6967 desc = mInputs.valueAt(input_index);
6968 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006969 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006970 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006971 }
Eric Laurentd4692962014-05-05 18:13:44 -07006972 break;
6973 }
6974 }
6975 if (input_index != mInputs.size()) {
6976 continue;
6977 }
6978
Jaideep Sharma44824a22024-06-18 16:32:34 +05306979 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6980 ALOGV("%s skip opening input for mmap profile %s",
6981 __func__, profile->getTagName().c_str());
6982 continue;
6983 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006984 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306985 ALOGW("%s Max Input number %u already opened for this profile %s",
6986 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08006987 continue;
6988 }
6989
Eric Laurentfe231122017-11-17 17:48:06 -08006990 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006991 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306992 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00006993 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
6994 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006995
Eric Laurentcf2c0212014-07-25 16:20:43 -07006996 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006997 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006998 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006999 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007000 mpClientInterface->setParameters(input, String8(param));
7001 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007002 }
jiabin12537fc2023-10-12 17:56:08 +00007003 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007004 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307005 ALOGW("%s direct input missing param for profile %s", __func__,
7006 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007007 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007008 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007009 }
7010
Eric Laurent0dd51852019-04-19 18:18:58 -07007011 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007012 addInput(input, desc);
7013 }
7014 } // endif input != 0
7015
Eric Laurentcf2c0212014-07-25 16:20:43 -07007016 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307017 ALOGW("%s could not open input for device %s on profile %s", __func__,
7018 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007019 profiles.removeAt(profile_index);
7020 profile_index--;
7021 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007022 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007023 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007024 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307025 ALOGV("%s: adding input %d for profile %s", __func__,
7026 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007027
7028 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307029 ALOGV("%s: closing input %d for profile %s", __func__,
7030 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007031 closeInput(input);
7032 }
Eric Laurentd4692962014-05-05 18:13:44 -07007033 }
7034 } // end scan profiles
7035
7036 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007037 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007038 return BAD_VALUE;
7039 }
7040 } else {
7041 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007042 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007043 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007044 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007045 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007046 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007047 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007048 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307049 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7050 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007051 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007052 }
7053 }
7054 }
7055 } // end disconnect
7056
7057 return NO_ERROR;
7058}
7059
7060
Eric Laurente0720872014-03-11 09:30:41 -07007061void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007062{
7063 ALOGV("closeOutput(%d)", output);
7064
François Gaffie1c878552018-11-22 16:53:21 +01007065 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7066 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007067 ALOGW("closeOutput() unknown output %d", output);
7068 return;
7069 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007070 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007071 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007072
Eric Laurente552edb2014-03-10 17:42:56 -07007073 // look for duplicated outputs connected to the output being removed.
7074 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007075 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7076 if (dupOutput->isDuplicated() &&
7077 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7078 sp<SwAudioOutputDescriptor> remainingOutput =
7079 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007080 // As all active tracks on duplicated output will be deleted,
7081 // and as they were also referenced on the other output, the reference
7082 // count for their stream type must be adjusted accordingly on
7083 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007084 const bool wasActive = remainingOutput->isActive();
7085 // Note: no-op on the closing output where all clients has already been set inactive
7086 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007087 // stop() will be a no op if the output is still active but is needed in case all
7088 // active streams refcounts where cleared above
7089 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007090 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007091 }
Eric Laurente552edb2014-03-10 17:42:56 -07007092 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7093 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7094
7095 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007096 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007097 }
7098 }
7099
Eric Laurent05b90f82014-08-27 15:32:29 -07007100 nextAudioPortGeneration();
7101
François Gaffie1c878552018-11-22 16:53:21 +01007102 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007103 if (index >= 0) {
7104 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007105 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7106 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007107 mAudioPatches.removeItemsAt(index);
7108 mpClientInterface->onAudioPatchListUpdate();
7109 }
7110
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007111 if (closingOutputWasActive) {
7112 closingOutput->stop();
7113 }
François Gaffie1c878552018-11-22 16:53:21 +01007114 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007115 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007116 for (const auto device : closingOutput->devices()) {
7117 device->setPreferredConfig(nullptr);
7118 }
7119 }
Eric Laurente552edb2014-03-10 17:42:56 -07007120
François Gaffie53615e22015-03-19 09:24:12 +01007121 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007122 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007123 if (closingOutput == mSpatializerOutput) {
7124 mSpatializerOutput.clear();
7125 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007126
7127 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7128 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007129 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007130 bool directOutputOpen = false;
7131 for (size_t i = 0; i < mOutputs.size(); i++) {
7132 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7133 directOutputOpen = true;
7134 break;
7135 }
7136 }
7137 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007138 ALOGV("no direct outputs open, reset MSD patches");
7139 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7140 // how output devices for patching are resolved. Avoid by caching and reusing the
7141 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7142 // devices to patch to. This may be complicated by the fact that devices may become
7143 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007144 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007145 }
7146 }
jiabin220eea12024-05-17 17:55:20 +00007147
7148 if (closingOutput->mPreferredAttrInfo != nullptr) {
7149 closingOutput->mPreferredAttrInfo->resetActiveClient();
7150 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007151}
7152
7153void AudioPolicyManager::closeInput(audio_io_handle_t input)
7154{
7155 ALOGV("closeInput(%d)", input);
7156
7157 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7158 if (inputDesc == NULL) {
7159 ALOGW("closeInput() unknown input %d", input);
7160 return;
7161 }
7162
Eric Laurent6a94d692014-05-20 11:18:06 -07007163 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007164
François Gaffie11d30102018-11-02 16:09:09 +01007165 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007166 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007167 if (index >= 0) {
7168 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007169 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7170 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007171 mAudioPatches.removeItemsAt(index);
7172 mpClientInterface->onAudioPatchListUpdate();
7173 }
7174
François Gaffie6ebbce02023-07-19 13:27:53 +02007175 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007176 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007177 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007178
François Gaffie11d30102018-11-02 16:09:09 +01007179 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7180 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007181 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007182 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007183 }
Eric Laurente552edb2014-03-10 17:42:56 -07007184}
7185
François Gaffie11d30102018-11-02 16:09:09 +01007186SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7187 const DeviceVector &devices,
7188 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007189{
7190 SortedVector<audio_io_handle_t> outputs;
7191
François Gaffie11d30102018-11-02 16:09:09 +01007192 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007193 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007194 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007195 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007196 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007197 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007198 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007199 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007200 outputs.add(openOutputs.keyAt(i));
7201 }
7202 }
7203 return outputs;
7204}
7205
Mikhail Naganov37977152018-07-11 15:54:44 -07007206void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7207{
7208 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7209 // output is suspended before any tracks are moved to it
7210 checkA2dpSuspend();
7211 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007212 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007213 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007214 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007215 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007216 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7217 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7218 // configuration changes will ultimately be rerouted correctly. We can still avoid
7219 // unnecessary rerouting by caching and reusing the arguments to
7220 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7221 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007222 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007223 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007224 // an event that changed routing likely occurred, inform upper layers
7225 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007226}
7227
François Gaffiec005e562018-11-06 15:04:49 +01007228bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7229 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007230{
François Gaffiec005e562018-11-06 15:04:49 +01007231 return mEngine->getProductStrategyForAttributes(lAttr) ==
7232 mEngine->getProductStrategyForAttributes(rAttr);
7233}
7234
Francois Gaffieff1eb522020-05-06 18:37:04 +02007235void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7236{
7237 for (size_t i = 0; i < mAudioSources.size(); i++) {
7238 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7239 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007240 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007241 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007242 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007243 }
7244 }
7245}
7246
7247void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7248{
7249 for (size_t i = 0; i < mAudioSources.size(); i++) {
7250 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7251 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7252 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7253 disconnectAudioSource(sourceDesc);
7254 }
7255 }
7256}
7257
François Gaffiec005e562018-11-06 15:04:49 +01007258void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7259{
7260 auto psId = mEngine->getProductStrategyForAttributes(attr);
7261
7262 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7263 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007264
François Gaffie11d30102018-11-02 16:09:09 +01007265 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7266 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007267
Eric Laurentc209fe42020-06-05 18:11:23 -07007268 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007269 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007270 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007271 // take into account dynamic audio policies related changes: if a client is now associated
7272 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007273 // invalidate clients on outputs that do not support all the newly selected devices for the
7274 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007275 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007276 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007277 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007278 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007279 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007280
Eric Laurentc209fe42020-06-05 18:11:23 -07007281 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7282 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7283 continue;
7284 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007285 if (!desc->supportsAllDevices(newDevices)) {
7286 invalidatedOutputs.push_back(desc);
7287 break;
7288 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007289 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007290 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007291 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7292 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7293 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007294 if (status == OK) {
7295 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7296 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7297 maxLatency = desc->latency();
7298 }
7299 invalidatedOutputs.push_back(desc);
7300 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007301 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007302 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007303 }
7304 }
7305
Eric Laurent56ed8842022-11-15 16:04:41 +01007306 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007307 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7308 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007309 for (audio_io_handle_t srcOut : srcOutputs) {
7310 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007311 if (desc == nullptr) continue;
7312
7313 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007314 maxLatency = desc->latency();
7315 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007316
Eric Laurent56ed8842022-11-15 16:04:41 +01007317 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007318 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007319 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007320 // a client on a non direct outputs has necessarily a linear PCM format
7321 // so we can call selectOutput() safely
7322 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7323 client->flags(),
7324 client->config().format,
7325 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007326 client->config().sample_rate,
7327 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007328 if (newOutput != srcOut) {
7329 invalidate = true;
7330 break;
7331 }
7332 } else {
7333 sp<IOProfile> profile = getProfileForOutput(newDevices,
7334 client->config().sample_rate,
7335 client->config().format,
7336 client->config().channel_mask,
7337 client->flags(),
7338 true /* directOnly */);
7339 if (profile != desc->mProfile) {
7340 invalidate = true;
7341 break;
7342 }
7343 }
7344 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007345 // mute strategy while moving tracks from one output to another
7346 if (invalidate) {
7347 invalidatedOutputs.push_back(desc);
7348 if (desc->isStrategyActive(psId)) {
7349 setStrategyMute(psId, true, desc);
7350 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7351 newDevices.types());
7352 }
Eric Laurente552edb2014-03-10 17:42:56 -07007353 }
François Gaffiec005e562018-11-06 15:04:49 +01007354 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007355 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007356 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007357 }
Eric Laurente552edb2014-03-10 17:42:56 -07007358 }
7359
Eric Laurent56ed8842022-11-15 16:04:41 +01007360 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7361 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7362 std::to_string(srcOutputs[0]).c_str(),
7363 std::to_string(dstOutputs[0]).c_str());
7364
François Gaffiec005e562018-11-06 15:04:49 +01007365 // Move effects associated to this stream from previous output to new output
7366 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007367 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007368 }
François Gaffiec005e562018-11-06 15:04:49 +01007369 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007370 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007371 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007372 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007373 desc->setTracksInvalidatedStatusByStrategy(psId);
7374 }
Eric Laurente552edb2014-03-10 17:42:56 -07007375 }
7376 }
7377}
7378
Eric Laurente0720872014-03-11 09:30:41 -07007379void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007380{
François Gaffiec005e562018-11-06 15:04:49 +01007381 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7382 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7383 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007384 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007385 }
Eric Laurente552edb2014-03-10 17:42:56 -07007386}
7387
Kevin Rocard153f92d2018-12-18 18:33:28 -08007388void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007389 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007390 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007391 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007392 for (size_t i = 0; i < mOutputs.size(); i++) {
7393 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7394 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007395 sp<AudioPolicyMix> primaryMix;
7396 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007397 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007398 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7399 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7400 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007401 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7402 for (auto &secondaryMix : secondaryMixes) {
7403 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7404 if (outputDesc != nullptr &&
7405 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7406 secondaryDescs.push_back(outputDesc);
7407 }
7408 }
7409
jiabinc44b3462022-12-08 12:52:31 -08007410 if (status != OK &&
7411 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7412 // When it failed to query secondary output, only invalidate the client that is not
7413 // MMAP. The reason is that MMAP stream will not support secondary output.
7414 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007415 } else if (!std::equal(
7416 client->getSecondaryOutputs().begin(),
7417 client->getSecondaryOutputs().end(),
7418 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungced57302024-08-14 11:37:57 -07007419 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7420 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007421 // If the format is not PCM, the tracks should be invalidated to get correct
7422 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007423 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007424 } else {
7425 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7426 std::vector<audio_io_handle_t> secondaryOutputIds;
7427 for (const auto &secondaryDesc: secondaryDescs) {
7428 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7429 weakSecondaryDescs.push_back(secondaryDesc);
7430 }
7431 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7432 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007433 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007434 }
7435 }
7436 }
jiabin10a03f12021-05-07 23:46:28 +00007437 if (!trackSecondaryOutputs.empty()) {
7438 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7439 }
jiabinc44b3462022-12-08 12:52:31 -08007440 if (!clientsToInvalidate.empty()) {
7441 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7442 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007443 }
7444}
7445
Eric Laurent2517af32020-11-25 15:31:27 +01007446bool AudioPolicyManager::isScoRequestedForComm() const {
7447 AudioDeviceTypeAddrVector devices;
7448 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7449 for (const auto &device : devices) {
7450 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7451 return true;
7452 }
7453 }
7454 return false;
7455}
7456
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007457bool AudioPolicyManager::isHearingAidUsedForComm() const {
7458 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7459 true /*fromCache*/);
7460 for (const auto &device : devices) {
7461 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7462 return true;
7463 }
7464 }
7465 return false;
7466}
7467
7468
Eric Laurente0720872014-03-11 09:30:41 -07007469void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007470{
François Gaffie53615e22015-03-19 09:24:12 +01007471 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007472 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007473 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007474 return;
7475 }
7476
Eric Laurent3a4311c2014-03-17 12:00:47 -07007477 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007478 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7479 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007480 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007481
7482 // if suspended, restore A2DP output if:
7483 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007484 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007485 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007486 //
Eric Laurentf732e072016-08-03 19:30:28 -07007487 // if not suspended, suspend A2DP output if:
7488 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007489 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007490 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007491 //
7492 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007493 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007494 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007495 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007496 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007497
7498 mpClientInterface->restoreOutput(a2dpOutput);
7499 mA2dpSuspended = false;
7500 }
7501 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007502 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007503 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007504 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007505 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007506
7507 mpClientInterface->suspendOutput(a2dpOutput);
7508 mA2dpSuspended = true;
7509 }
7510 }
7511}
7512
François Gaffie11d30102018-11-02 16:09:09 +01007513DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7514 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007515{
François Gaffiedb1755b2023-09-01 11:50:35 +02007516 if (outputDesc == nullptr) {
7517 return DeviceVector{};
7518 }
François Gaffie11d30102018-11-02 16:09:09 +01007519
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007520 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007521 if (index >= 0) {
7522 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007523 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007524 ALOGV("%s device %s forced by patch %d", __func__,
7525 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7526 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007527 }
7528 }
7529
Dean Wheatley514b4312020-06-17 21:45:00 +10007530 // Do not retrieve engine device for outputs through MSD
7531 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7532 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7533 return outputDesc->devices();
7534 }
7535
Eric Laurent97ac8712018-07-27 18:59:02 -07007536 // Honor explicit routing requests only if no client using default routing is active on this
7537 // input: a specific app can not force routing for other apps by setting a preferred device.
7538 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007539 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007540 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007541 if (device != nullptr) {
7542 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007543 }
7544
François Gaffiea807ef92018-11-05 10:44:33 +01007545 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7546 // of setForceUse / Default Bus device here
7547 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7548 if (device != nullptr) {
7549 return DeviceVector(device);
7550 }
7551
François Gaffiedb1755b2023-09-01 11:50:35 +02007552 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007553 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7554 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307555 auto hasStreamActive = [&](auto stream) {
7556 return hasStream(streams, stream) && isStreamActive(stream, 0);
7557 };
Eric Laurent484e9272018-06-07 17:29:23 -07007558
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307559 auto doGetOutputDevicesForVoice = [&]() {
7560 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007561 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307562 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007563 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7564 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307565 };
7566
7567 // With low-latency playing on speaker, music on WFD, when the first low-latency
7568 // output is stopped, getNewOutputDevices checks for a product strategy
7569 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007570 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307571 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7572 // stream is associated to the output descriptor.
7573 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7574 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7575 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7576 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007577 // Retrieval of devices for voice DL is done on primary output profile, cannot
7578 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007579 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007580 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7581 break;
7582 }
Eric Laurente552edb2014-03-10 17:42:56 -07007583 }
François Gaffiec005e562018-11-06 15:04:49 +01007584 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007585 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007586}
7587
François Gaffie11d30102018-11-02 16:09:09 +01007588sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7589 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007590{
François Gaffie11d30102018-11-02 16:09:09 +01007591 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007592
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007593 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007594 if (index >= 0) {
7595 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007596 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007597 ALOGV("getNewInputDevice() device %s forced by patch %d",
7598 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7599 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007600 }
7601 }
7602
Eric Laurent97ac8712018-07-27 18:59:02 -07007603 // Honor explicit routing requests only if no client using default routing is active on this
7604 // input: a specific app can not force routing for other apps by setting a preferred device.
7605 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007606 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7607 if (device != nullptr) {
7608 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007609 }
7610
Eric Laurentdc95a252018-04-12 12:46:56 -07007611 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007612 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007613 audio_attributes_t attributes;
7614 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007615 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007616 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7617 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007618 attributes = topClient->attributes();
7619 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007620 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007621 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007622 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7623 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007624 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007625 }
7626
Francois Gaffie716e1432019-01-14 16:58:59 +01007627 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7628 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007629 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007630 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007631 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007632 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007633
Eric Laurente552edb2014-03-10 17:42:56 -07007634 return device;
7635}
7636
Eric Laurent794fde22016-03-11 09:50:45 -08007637bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7638 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007639 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007640}
7641
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007642status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007643 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007644 if (devices == nullptr) {
7645 return BAD_VALUE;
7646 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007647
Andy Hung6d23c0f2022-02-16 09:37:15 -08007648 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007649 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7650 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007651 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007652 for (const auto& device : curDevices) {
7653 devices->push_back(device->getDeviceTypeAddr());
7654 }
7655 return NO_ERROR;
7656}
7657
Eric Laurente0720872014-03-11 09:30:41 -07007658void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007659 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007660 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007661 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007662 updateDevicesAndOutputs();
7663 break;
7664 default:
7665 break;
7666 }
7667}
7668
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007669uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007670
7671 // skip beacon mute management if a dedicated TTS output is available
7672 if (mTtsOutputAvailable) {
7673 return 0;
7674 }
7675
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007676 switch(event) {
7677 case STARTING_OUTPUT:
7678 mBeaconMuteRefCount++;
7679 break;
7680 case STOPPING_OUTPUT:
7681 if (mBeaconMuteRefCount > 0) {
7682 mBeaconMuteRefCount--;
7683 }
7684 break;
7685 case STARTING_BEACON:
7686 mBeaconPlayingRefCount++;
7687 break;
7688 case STOPPING_BEACON:
7689 if (mBeaconPlayingRefCount > 0) {
7690 mBeaconPlayingRefCount--;
7691 }
7692 break;
7693 }
7694
7695 if (mBeaconMuteRefCount > 0) {
7696 // any playback causes beacon to be muted
7697 return setBeaconMute(true);
7698 } else {
7699 // no other playback: unmute when beacon starts playing, mute when it stops
7700 return setBeaconMute(mBeaconPlayingRefCount == 0);
7701 }
7702}
7703
7704uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7705 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7706 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7707 // keep track of muted state to avoid repeating mute/unmute operations
7708 if (mBeaconMuted != mute) {
7709 // mute/unmute AUDIO_STREAM_TTS on all outputs
7710 ALOGV("\t muting %d", mute);
7711 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007712 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7713 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7714 ALOGV("\t no tts volume source available");
7715 return 0;
7716 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007717 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007718 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007719 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007720 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007721 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007722 maxLatency = latency;
7723 }
7724 }
7725 mBeaconMuted = mute;
7726 return maxLatency;
7727 }
7728 return 0;
7729}
7730
Eric Laurente0720872014-03-11 09:30:41 -07007731void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007732{
François Gaffiec005e562018-11-06 15:04:49 +01007733 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007734 mPreviousOutputs = mOutputs;
7735}
7736
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007737uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007738 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007739 uint32_t delayMs)
7740{
7741 // mute/unmute strategies using an incompatible device combination
7742 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7743 // if unmuting, unmute only after the specified delay
7744 if (outputDesc->isDuplicated()) {
7745 return 0;
7746 }
7747
7748 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007749 DeviceVector devices = outputDesc->devices();
7750 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007751
François Gaffiec005e562018-11-06 15:04:49 +01007752 auto productStrategies = mEngine->getOrderedProductStrategies();
7753 for (const auto &productStrategy : productStrategies) {
7754 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7755 DeviceVector curDevices =
7756 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7757 curDevices = curDevices.filter(outputDesc->supportedDevices());
7758 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007759 bool doMute = false;
7760
François Gaffiec005e562018-11-06 15:04:49 +01007761 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007762 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007763 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7764 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007765 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007766 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007767 }
Eric Laurent99401132014-05-07 19:48:15 -07007768 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007769 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007770 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007771 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007772 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007773 continue;
7774 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307775 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007776 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7777 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7778 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007779 if (mute) {
7780 // FIXME: should not need to double latency if volume could be applied
7781 // immediately by the audioflinger mixer. We must account for the delay
7782 // between now and the next time the audioflinger thread for this output
7783 // will process a buffer (which corresponds to one buffer size,
7784 // usually 1/2 or 1/4 of the latency).
7785 if (muteWaitMs < desc->latency() * 2) {
7786 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007787 }
7788 }
7789 }
7790 }
7791 }
7792 }
7793
Eric Laurent99401132014-05-07 19:48:15 -07007794 // temporary mute output if device selection changes to avoid volume bursts due to
7795 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007796 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007797 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007798
Eric Laurentdc462862016-07-19 12:29:53 -07007799 if (muteWaitMs < tempMuteWaitMs) {
7800 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007801 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007802
7803 // If recommended duration is defined, replace temporary mute duration to avoid
7804 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7805 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7806 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7807 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7808 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7809
François Gaffieaaac0fd2018-11-22 17:56:39 +01007810 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7811 // make sure that we do not start the temporary mute period too early in case of
7812 // delayed device change
7813 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7814 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007815 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007816 }
7817 }
7818
Eric Laurente552edb2014-03-10 17:42:56 -07007819 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7820 if (muteWaitMs > delayMs) {
7821 muteWaitMs -= delayMs;
7822 usleep(muteWaitMs * 1000);
7823 return muteWaitMs;
7824 }
7825 return 0;
7826}
7827
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307828uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7829 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007830 const DeviceVector &devices,
7831 bool force,
7832 int delayMs,
7833 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007834 bool requiresMuteCheck, bool requiresVolumeCheck,
7835 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007836{
jiabin3ff8d7d2022-12-13 06:27:44 +00007837 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307838 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7839 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7840 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007841 uint32_t muteWaitMs;
7842
7843 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307844 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007845 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307846 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007847 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007848 return muteWaitMs;
7849 }
Eric Laurente552edb2014-03-10 17:42:56 -07007850
7851 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007852 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007853 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007854 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007855
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307856 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7857 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007858
7859 if (!filteredDevices.isEmpty()) {
7860 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007861 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007862
7863 // if the outputs are not materially active, there is no need to mute.
7864 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007865 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007866 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307867 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7868 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007869 muteWaitMs = 0;
7870 }
Eric Laurente552edb2014-03-10 17:42:56 -07007871
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007872 bool outputRouted = outputDesc->isRouted();
7873
Eric Laurent79ea9582020-06-11 18:49:24 -07007874 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7875 // output profile or if new device is not supported AND previous device(s) is(are) still
7876 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007877 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307878 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7879 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007880 // restore previous device after evaluating strategy mute state
7881 outputDesc->setDevices(prevDevices);
7882 return muteWaitMs;
7883 }
7884
Eric Laurente552edb2014-03-10 17:42:56 -07007885 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007886 // the requested device is AUDIO_DEVICE_NONE
7887 // OR the requested device is the same as current device
7888 // AND force is not specified
7889 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007890 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007891 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307892 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7893 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7894 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007895 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307896 ALOGV("%s %s setting same device on routed output, force apply volumes",
7897 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007898 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7899 }
Eric Laurente552edb2014-03-10 17:42:56 -07007900 return muteWaitMs;
7901 }
7902
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307903 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7904 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007905
Eric Laurente552edb2014-03-10 17:42:56 -07007906 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007907 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007908 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007909 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007910 PatchBuilder patchBuilder;
7911 patchBuilder.addSource(outputDesc);
7912 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7913 for (const auto &filteredDevice : filteredDevices) {
7914 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007915 }
7916
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007917 // Add half reported latency to delayMs when muteWaitMs is null in order
7918 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007919 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7920 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7921 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007922 }
Eric Laurente552edb2014-03-10 17:42:56 -07007923
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007924 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7925 if (!skipMuteDelay) {
7926 // update stream volumes according to new device
7927 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7928 }
Eric Laurente552edb2014-03-10 17:42:56 -07007929
7930 return muteWaitMs;
7931}
7932
Eric Laurentc75307b2015-03-17 15:29:32 -07007933status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007934 int delayMs,
7935 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007936{
Eric Laurent6a94d692014-05-20 11:18:06 -07007937 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007938 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7939 return INVALID_OPERATION;
7940 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007941 if (patchHandle) {
7942 index = mAudioPatches.indexOfKey(*patchHandle);
7943 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007944 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007945 }
7946 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007947 return INVALID_OPERATION;
7948 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007949 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007950 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007951 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007952 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007953 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007954 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007955 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007956 return status;
7957}
7958
7959status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007960 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007961 bool force,
7962 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007963{
7964 status_t status = NO_ERROR;
7965
Eric Laurent1f2f2232014-06-02 12:01:23 -07007966 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007967 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7968 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007969
François Gaffie11d30102018-11-02 16:09:09 +01007970 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007971 PatchBuilder patchBuilder;
7972 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007973 // AUDIO_SOURCE_HOTWORD is for internal use only:
7974 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007975 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7976 auto result = usecase;
7977 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7978 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7979 }
7980 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007981 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007982 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007983 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007984 }
7985 }
7986 return status;
7987}
7988
Eric Laurent6a94d692014-05-20 11:18:06 -07007989status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7990 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007991{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007992 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007993 ssize_t index;
7994 if (patchHandle) {
7995 index = mAudioPatches.indexOfKey(*patchHandle);
7996 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007997 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007998 }
7999 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008000 return INVALID_OPERATION;
8001 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008002 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008003 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008004 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008005 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008006 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008007 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008008 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008009 return status;
8010}
8011
François Gaffie11d30102018-11-02 16:09:09 +01008012sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008013 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008014 audio_format_t& format,
8015 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008016 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008017{
8018 // Choose an input profile based on the requested capture parameters: select the first available
8019 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008020 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008021
Atneya Nair0f0a8032022-12-12 16:20:12 -08008022 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8023 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8024 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8025
8026 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008027
jiabin2fd710d2022-05-02 23:20:22 +00008028 for (;;) {
8029 sp<IOProfile> firstInexact = nullptr;
8030 uint32_t updatedSamplingRate = 0;
8031 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8032 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8033 for (const auto& hwModule : mHwModules) {
8034 for (const auto& profile : hwModule->getInputProfiles()) {
8035 // profile->log();
8036 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008037 if (profile->getCompatibilityScore(
8038 DeviceVector(device),
8039 samplingRate,
8040 &updatedSamplingRate,
8041 format,
8042 &updatedFormat,
8043 channelMask,
8044 &updatedChannelMask,
8045 // FIXME ugly cast
8046 (audio_output_flags_t) flags,
8047 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8048 samplingRate = updatedSamplingRate;
8049 format = updatedFormat;
8050 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008051 return profile;
8052 }
jiabin66acc432024-02-06 00:57:36 +00008053 if (firstInexact == nullptr
8054 && profile->getCompatibilityScore(
8055 DeviceVector(device),
8056 samplingRate,
8057 &updatedSamplingRate,
8058 format,
8059 &updatedFormat,
8060 channelMask,
8061 &updatedChannelMask,
8062 // FIXME ugly cast
8063 (audio_output_flags_t) flags,
8064 false /*exactMatchRequiredForInputFlags*/)
8065 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008066 firstInexact = profile;
8067 }
8068 }
8069 }
8070
8071 if (firstInexact != nullptr) {
8072 samplingRate = updatedSamplingRate;
8073 format = updatedFormat;
8074 channelMask = updatedChannelMask;
8075 return firstInexact;
8076 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8077 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8078 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8079 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8080 flags = AUDIO_INPUT_FLAG_NONE;
8081 } else { // fail
8082 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8083 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8084 samplingRate, format, channelMask, oriFlags);
8085 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008086 }
8087 }
jiabin2fd710d2022-05-02 23:20:22 +00008088
8089 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008090}
8091
Vlad Popa87e0e582024-05-20 18:49:20 -07008092float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8093 VolumeSource volumeSource,
8094 int index,
8095 const DeviceTypeSet &deviceTypes)
8096{
8097 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8098 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8099 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8100
8101 if (com_android_media_audio_abs_volume_index_fix()) {
8102 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8103 mAbsoluteVolumeDrivingStreams.end()) {
8104 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8105 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8106 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8107 ALOGD("%s: no group matching with %s", __FUNCTION__,
8108 toString(attributesToDriveAbs).c_str());
8109 return volumeDb;
8110 }
8111
8112 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8113 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8114 if (vsToDriveAbs == volumeSource) {
8115 // attenuation is applied by the abs volume controller
8116 return volumeDbMax;
8117 } else {
8118 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8119 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8120 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8121 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8122 curvesAbs.getVolumeIndexMax());
8123 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8124 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8125 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8126 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8127 return newVolumeDb;
8128 }
8129 }
8130 return volumeDb;
8131 } else {
8132 return volumeDb;
8133 }
8134}
8135
François Gaffieaaac0fd2018-11-22 17:56:39 +01008136float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8137 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008138 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008139 const DeviceTypeSet& deviceTypes,
8140 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008141{
Vlad Popa87e0e582024-05-20 18:49:20 -07008142 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008143 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8144 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8145
8146 if (!computeInternalInteraction) {
8147 return volumeDb;
8148 }
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008149
8150 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8151 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8152 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8153 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008154 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8155 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8156 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8157 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8158 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008159 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008160 mOutputs.isActive(ringVolumeSrc, 0)) {
8161 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008162 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8163 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008164 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008165 }
8166
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008167 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008168 if ((volumeSource != callVolumeSrc && (isInCall() ||
8169 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008170 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008171 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8172 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008173 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8174 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8175 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008176 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008177 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008178 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008179 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008180 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8181 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008182 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008183 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8184 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8185 // programmatically muted.
8186 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8187 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8188 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008189 bool exemptFromCapping =
8190 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8191 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008192 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8193 volumeSource, volumeDb);
8194 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008195 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8196 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8197 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008198 }
8199 }
Eric Laurente552edb2014-03-10 17:42:56 -07008200 // if a headset is connected, apply the following rules to ring tones and notifications
8201 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008202 // - always attenuate notifications volume by 6dB
8203 // - attenuate ring tones volume by 6dB unless music is not playing and
8204 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008205 // - if music is playing, always limit the volume to current music volume,
8206 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008207 if (!Intersection(deviceTypes,
8208 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8209 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008210 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8211 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008212 ((volumeSource == alarmVolumeSrc ||
8213 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008214 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8215 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8216 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008217 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8218 curves.canBeMuted()) {
8219
Eric Laurente552edb2014-03-10 17:42:56 -07008220 // when the phone is ringing we must consider that music could have been paused just before
8221 // by the music application and behave as if music was active if the last music track was
8222 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008223 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8224 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008225 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008226 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008227 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8228 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008229 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008230 float musicVolDb = computeVolume(musicCurves,
8231 musicVolumeSrc,
8232 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008233 musicDevice,
8234 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008235 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8236 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8237 if (volumeDb > minVolDb) {
8238 volumeDb = minVolDb;
8239 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008240 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008241 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8242 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008243 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8244 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8245 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8246 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008247 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008248 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008249 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8250 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008251 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8252 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008253 }
8254 }
jiabin9a3361e2019-10-01 09:38:30 -07008255 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008256 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008257 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008258 }
8259 }
8260
François Gaffie43c73442018-11-08 08:21:55 +01008261 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008262}
8263
Eric Laurent3839bc02018-07-10 18:33:34 -07008264int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008265 VolumeSource fromVolumeSource,
8266 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008267{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008268 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008269 return srcIndex;
8270 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008271 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8272 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008273 float minSrc = (float)srcCurves.getVolumeIndexMin();
8274 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8275 float minDst = (float)dstCurves.getVolumeIndexMin();
8276 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008277
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008278 // preserve mute request or correct range
8279 if (srcIndex < minSrc) {
8280 if (srcIndex == 0) {
8281 return 0;
8282 }
8283 srcIndex = minSrc;
8284 } else if (srcIndex > maxSrc) {
8285 srcIndex = maxSrc;
8286 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008287 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8288}
8289
François Gaffieaaac0fd2018-11-22 17:56:39 +01008290status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8291 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008292 int index,
8293 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008294 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008295 int delayMs,
8296 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008297{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008298 // APM is single threaded, and single instance.
8299 static std::set<IVolumeCurves*> invalidCurvesReported;
8300
François Gaffieaaac0fd2018-11-22 17:56:39 +01008301 // do not change actual attributes volume if the attributes is muted
8302 if (outputDesc->isMuted(volumeSource)) {
8303 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8304 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008305 return NO_ERROR;
8306 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008307
Eric Laurent5baf07c2024-01-11 16:57:27 +00008308 bool isVoiceVolSrc;
8309 bool isBtScoVolSrc;
8310 if (!isVolumeConsistentForCalls(
8311 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008312 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008313 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008314 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008315 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008316
jiabin9a3361e2019-10-01 09:38:30 -07008317 if (deviceTypes.empty()) {
8318 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008319 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008320 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008321 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008322 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008323
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008324 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008325 if (!invalidCurvesReported.count(&curves)) {
8326 invalidCurvesReported.insert(&curves);
8327 String8 dump;
8328 curves.dump(&dump);
8329 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8330 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008331 return BAD_VALUE;
8332 }
8333
jiabin9a3361e2019-10-01 09:38:30 -07008334 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8335 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008336 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008337 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008338 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8339 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008340 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008341 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008342 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008343 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8344 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008345
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008346 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008347 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8348 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8349 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008350 }
Eric Laurente552edb2014-03-10 17:42:56 -07008351 return NO_ERROR;
8352}
8353
Eric Laurent5baf07c2024-01-11 16:57:27 +00008354void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008355 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008356 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008357 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008358 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008359 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008360 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8361 } else {
8362 voiceVolume = index == 0 ? 0.0 : 1.0;
8363 }
8364 if (voiceVolume != mLastVoiceVolume) {
8365 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8366 mLastVoiceVolume = voiceVolume;
8367 }
8368}
8369
8370bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8371 const DeviceTypeSet& deviceTypes,
8372 bool& isVoiceVolSrc,
8373 bool& isBtScoVolSrc,
8374 const char* caller) {
8375 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8376 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8377 const bool isScoRequested = isScoRequestedForComm();
8378 const bool isHAUsed = isHearingAidUsedForComm();
8379
8380 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8381 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8382
8383 if ((callVolSrc != btScoVolSrc) &&
8384 ((isVoiceVolSrc && isScoRequested) ||
8385 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8386 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8387 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8388 volumeSource, isScoRequested ? " " : " not ");
8389 return false;
8390 }
8391 return true;
8392}
8393
Eric Laurentc75307b2015-03-17 15:29:32 -07008394void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008395 const DeviceTypeSet& deviceTypes,
8396 int delayMs,
8397 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008398{
jiabincd510522020-01-22 09:40:55 -08008399 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008400 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8401 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8402 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008403 curves.getVolumeIndex(deviceTypes),
8404 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008405 }
8406}
8407
François Gaffiec005e562018-11-06 15:04:49 +01008408void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8409 bool on,
8410 const sp<AudioOutputDescriptor>& outputDesc,
8411 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008412 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008413{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008414 std::vector<VolumeSource> sourcesToMute;
8415 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8416 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8417 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008418 VolumeSource source = toVolumeSource(attributes, false);
8419 if ((source != VOLUME_SOURCE_NONE) &&
8420 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8421 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008422 sourcesToMute.push_back(source);
8423 }
Eric Laurente552edb2014-03-10 17:42:56 -07008424 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008425 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008426 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008427 }
8428
Eric Laurente552edb2014-03-10 17:42:56 -07008429}
8430
François Gaffieaaac0fd2018-11-22 17:56:39 +01008431void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8432 bool on,
8433 const sp<AudioOutputDescriptor>& outputDesc,
8434 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008435 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008436{
jiabin9a3361e2019-10-01 09:38:30 -07008437 if (deviceTypes.empty()) {
8438 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008439 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008440 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008441 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008442 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008443 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008444 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008445 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8446 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008447 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008448 }
8449 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008450 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8451 // ignored
8452 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008453 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008454 if (!outputDesc->isMuted(volumeSource)) {
8455 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008456 return;
8457 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008458 if (outputDesc->decMuteCount(volumeSource) == 0) {
8459 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008460 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008461 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008462 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008463 delayMs);
8464 }
8465 }
8466}
8467
François Gaffie53615e22015-03-19 09:24:12 +01008468bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8469{
François Gaffiec005e562018-11-06 15:04:49 +01008470 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008471 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8472 return true;
8473 }
8474
8475 // has known usage?
8476 switch (paa->usage) {
8477 case AUDIO_USAGE_UNKNOWN:
8478 case AUDIO_USAGE_MEDIA:
8479 case AUDIO_USAGE_VOICE_COMMUNICATION:
8480 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8481 case AUDIO_USAGE_ALARM:
8482 case AUDIO_USAGE_NOTIFICATION:
8483 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8484 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8485 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8486 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8487 case AUDIO_USAGE_NOTIFICATION_EVENT:
8488 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8489 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8490 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8491 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008492 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008493 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008494 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008495 case AUDIO_USAGE_EMERGENCY:
8496 case AUDIO_USAGE_SAFETY:
8497 case AUDIO_USAGE_VEHICLE_STATUS:
8498 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008499 break;
8500 default:
8501 return false;
8502 }
8503 return true;
8504}
8505
François Gaffie2110e042015-03-24 08:41:51 +01008506audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8507{
8508 return mEngine->getForceUse(usage);
8509}
8510
Eric Laurent96d1dda2022-03-14 17:14:19 +01008511bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008512 return isStateInCall(mEngine->getPhoneState());
8513}
8514
Eric Laurent96d1dda2022-03-14 17:14:19 +01008515bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008516 return is_state_in_call(state);
8517}
8518
Eric Laurentf9cccec2022-11-16 19:12:00 +01008519bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008520 audio_mode_t mode = mEngine->getPhoneState();
8521 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008522 || (mode == AUDIO_MODE_CALL_SCREEN)
8523 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008524}
8525
Eric Laurentf9cccec2022-11-16 19:12:00 +01008526bool AudioPolicyManager::isInCallOrScreening() const {
8527 audio_mode_t mode = mEngine->getPhoneState();
8528 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8529}
8530
Eric Laurentd60560a2015-04-10 11:31:20 -07008531void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8532{
8533 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008534 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008535 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008536 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008537 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008538 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008539 }
8540 }
8541
8542 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8543 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8544 bool release = false;
8545 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8546 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8547 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8548 source->ext.device.type == deviceDesc->type()) {
8549 release = true;
8550 }
8551 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008552 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008553 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8554 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8555 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008556 sink->ext.device.type == deviceDesc->type() &&
8557 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8558 || strncmp(sink->ext.device.address, address,
8559 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008560 release = true;
8561 }
8562 }
8563 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008564 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8565 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008566 }
8567 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008568
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008569 mInputs.clearSessionRoutesForDevice(deviceDesc);
8570
Francois Gaffie716e1432019-01-14 16:58:59 +01008571 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008572}
8573
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008574void AudioPolicyManager::modifySurroundFormats(
8575 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008576 std::unordered_set<audio_format_t> enforcedSurround(
8577 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008578 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008579 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008580 allSurround.insert(pair.first);
8581 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8582 }
Phil Burk09bc4612016-02-24 15:58:15 -08008583
8584 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8585 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008586 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008587 // This is the resulting set of formats depending on the surround mode:
8588 // 'all surround' = allSurround
8589 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8590 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8591 // 'manual surround' = mManualSurroundFormats
8592 // AUTO: formats v 'enforced surround'
8593 // ALWAYS: formats v 'all surround' v 'enforced surround'
8594 // NEVER: formats ^ 'non-surround'
8595 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008596
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008597 std::unordered_set<audio_format_t> formatSet;
8598 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8599 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008600 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008601 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008602 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008603 formatSet.insert(*formatIter);
8604 }
8605 }
8606 } else {
8607 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8608 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008609 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008610
jiabin81772902018-04-02 17:52:27 -07008611 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008612 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008613 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8614 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8615 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008616 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008617 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8618 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8619 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008620 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008621 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008622 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008623 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008624 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008625 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008626}
8627
jiabin06e4bab2019-07-29 10:13:34 -07008628void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8629 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008630 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8631 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8632
8633 // If NEVER, then remove support for channelMasks > stereo.
8634 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008635 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8636 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008637 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008638 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008639 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008640 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008641 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008642 }
8643 }
jiabin81772902018-04-02 17:52:27 -07008644 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8645 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8646 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008647 bool supports5dot1 = false;
8648 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008649 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008650 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8651 supports5dot1 = true;
8652 break;
8653 }
8654 }
8655 // If not then add 5.1 support.
8656 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008657 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008658 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008659 }
Phil Burk09bc4612016-02-24 15:58:15 -08008660 }
8661}
8662
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008663void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008664 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008665 const sp<IOProfile>& profile) {
8666 if (!profile->hasDynamicAudioProfile()) {
8667 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008668 }
François Gaffie112b0af2015-11-19 16:13:25 +01008669
jiabin12537fc2023-10-12 17:56:08 +00008670 audio_port_v7 devicePort;
8671 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008672
jiabin12537fc2023-10-12 17:56:08 +00008673 audio_port_v7 mixPort;
8674 profile->toAudioPort(&mixPort);
8675 mixPort.ext.mix.handle = ioHandle;
8676
8677 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8678 if (status != NO_ERROR) {
8679 ALOGE("%s failed to query the attributes of the mix port", __func__);
8680 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008681 }
jiabin12537fc2023-10-12 17:56:08 +00008682
8683 std::set<audio_format_t> supportedFormats;
8684 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8685 supportedFormats.insert(mixPort.audio_profiles[i].format);
8686 }
8687 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8688 mReportedFormatsMap[devDesc] = formats;
8689
8690 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8691 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8692 modifySurroundFormats(devDesc, &formats);
8693 size_t modifiedNumProfiles = 0;
8694 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8695 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8696 formats.end()) {
8697 // Skip the format that is not present after modifying surround formats.
8698 continue;
8699 }
8700 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8701 sizeof(struct audio_profile));
8702 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8703 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8704 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8705 modifySurroundChannelMasks(&channels);
8706 std::copy(channels.begin(), channels.end(),
8707 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8708 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8709 }
8710 mixPort.num_audio_profiles = modifiedNumProfiles;
8711 }
8712 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008713}
Eric Laurentd60560a2015-04-10 11:31:20 -07008714
Mikhail Naganovdc769682018-05-04 15:34:08 -07008715status_t AudioPolicyManager::installPatch(const char *caller,
8716 audio_patch_handle_t *patchHandle,
8717 AudioIODescriptorInterface *ioDescriptor,
8718 const struct audio_patch *patch,
8719 int delayMs)
8720{
8721 ssize_t index = mAudioPatches.indexOfKey(
8722 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8723 *patchHandle : ioDescriptor->getPatchHandle());
8724 sp<AudioPatch> patchDesc;
8725 status_t status = installPatch(
8726 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8727 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008728 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008729 }
8730 return status;
8731}
8732
8733status_t AudioPolicyManager::installPatch(const char *caller,
8734 ssize_t index,
8735 audio_patch_handle_t *patchHandle,
8736 const struct audio_patch *patch,
8737 int delayMs,
8738 uid_t uid,
8739 sp<AudioPatch> *patchDescPtr)
8740{
8741 sp<AudioPatch> patchDesc;
8742 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8743 if (index >= 0) {
8744 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008745 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008746 }
8747
8748 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8749 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8750 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8751 if (status == NO_ERROR) {
8752 if (index < 0) {
8753 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008754 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008755 } else {
8756 patchDesc->mPatch = *patch;
8757 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008758 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008759 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008760 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008761 }
8762 nextAudioPortGeneration();
8763 mpClientInterface->onAudioPatchListUpdate();
8764 }
8765 if (patchDescPtr) *patchDescPtr = patchDesc;
8766 return status;
8767}
8768
jiabinbce0c1d2020-10-05 11:20:18 -07008769bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8770{
8771 const TrackClientVector activeClients = output->getActiveClients();
8772 if (activeClients.empty()) {
8773 return true;
8774 }
8775 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8776 if (index < 0) {
8777 ALOGE("%s, no audio patch found while there are active clients on output %d",
8778 __func__, output->getId());
8779 return false;
8780 }
8781 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8782 DeviceVector routedDevices;
8783 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8784 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8785 patchDesc->mPatch.sinks[i].id);
8786 if (device == nullptr) {
8787 ALOGE("%s, no audio device found with id(%d)",
8788 __func__, patchDesc->mPatch.sinks[i].id);
8789 return false;
8790 }
8791 routedDevices.add(device);
8792 }
8793 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008794 if (client->isInvalid()) {
8795 // No need to take care about invalidated clients.
8796 continue;
8797 }
jiabinbce0c1d2020-10-05 11:20:18 -07008798 sp<DeviceDescriptor> preferredDevice =
8799 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8800 if (mEngine->getOutputDevicesForAttributes(
8801 client->attributes(), preferredDevice, false) == routedDevices) {
8802 return false;
8803 }
8804 }
8805 return true;
8806}
8807
8808sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008809 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008810 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8811 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008812{
8813 for (const auto& device : devices) {
8814 // TODO: This should be checking if the profile supports the device combo.
8815 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008816 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8817 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008818 return nullptr;
8819 }
8820 }
8821 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8822 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008823 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008824 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008825 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008826 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008827 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008828 return nullptr;
8829 }
jiabin14b50cc2023-12-13 19:01:52 +00008830 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8831 auto portConfig = desc->getConfig();
8832 for (const auto& device : devices) {
8833 device->setPreferredConfig(&portConfig);
8834 }
8835 }
jiabinbce0c1d2020-10-05 11:20:18 -07008836
8837 // Here is where the out_set_parameters() for card & device gets called
8838 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8839 const audio_devices_t deviceType = device->type();
8840 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008841 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008842 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8843 mpClientInterface->setParameters(output, String8(param));
8844 free(param);
8845 }
jiabin12537fc2023-10-12 17:56:08 +00008846 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008847 if (!profile->hasValidAudioProfile()) {
8848 ALOGW("%s() missing param", __func__);
8849 desc->close();
8850 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008851 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8852 // Reopen the output with the best audio profile picked by APM when the profile supports
8853 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008854 desc->close();
8855 output = AUDIO_IO_HANDLE_NONE;
8856 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8857 profile->pickAudioProfile(
8858 config.sample_rate, config.channel_mask, config.format);
8859 config.offload_info.sample_rate = config.sample_rate;
8860 config.offload_info.channel_mask = config.channel_mask;
8861 config.offload_info.format = config.format;
8862
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008863 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
8864 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008865 if (status != NO_ERROR) {
8866 return nullptr;
8867 }
8868 }
8869
8870 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008871 setOutputDevices(__func__, desc,
8872 devices,
8873 true,
8874 0,
8875 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008876 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8877 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8878
jiabinbce0c1d2020-10-05 11:20:18 -07008879 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8880 sp<AudioPolicyMix> policyMix;
8881 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8882 policyMix->setOutput(desc);
8883 desc->mPolicyMix = policyMix;
8884 } else {
8885 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008886 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008887 }
8888
baek.kim -61c20122022-07-27 10:05:32 +00008889 } else if (hasPrimaryOutput() && speaker != nullptr
8890 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008891 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8892 // no duplicated output for:
8893 // - direct outputs
8894 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008895 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008896 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8897
8898 //TODO: configure audio effect output stage here
8899
8900 // open a duplicating output thread for the new output and the primary output
8901 sp<SwAudioOutputDescriptor> dupOutputDesc =
8902 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8903 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8904 if (status == NO_ERROR) {
8905 // add duplicated output descriptor
8906 addOutput(duplicatedOutput, dupOutputDesc);
8907 } else {
8908 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8909 mPrimaryOutput->mIoHandle, output);
8910 desc->close();
8911 removeOutput(output);
8912 nextAudioPortGeneration();
8913 return nullptr;
8914 }
8915 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008916 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8917 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8918 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008919 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008920 }
jiabinbce0c1d2020-10-05 11:20:18 -07008921 return desc;
8922}
8923
jiabinf1c73972022-04-14 16:28:52 -07008924status_t AudioPolicyManager::getDevicesForAttributes(
8925 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8926 // Devices are determined in the following precedence:
8927 //
8928 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8929 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8930 //
8931 // If no such dynamic policy then
8932 // 2) Devices containing an active client using setPreferredDevice
8933 // with same strategy as the attributes.
8934 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8935 //
8936 // If no corresponding active client with setPreferredDevice then
8937 // 3) Devices associated with the strategy determined by the attributes
8938 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8939 //
8940 // See related getOutputForAttrInt().
8941
8942 // check dynamic policies but only for primary descriptors (secondary not used for audible
8943 // audio routing, only used for duplication for playback capture)
8944 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008945 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008946 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008947 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8948 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8949 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008950 if (status != OK) {
8951 return status;
8952 }
8953
8954 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8955 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8956 // as they are unaffected by device/stream volume
8957 // (per SwAudioOutputDescriptor::isFixedVolume()).
8958 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8959 ) {
8960 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8961 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8962 devices.add(deviceDesc);
8963 } else {
8964 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8965 // which selects setPreferredDevice if active. This means forVolume call
8966 // will take an active setPreferredDevice, if such exists.
8967
8968 devices = mEngine->getOutputDevicesForAttributes(
8969 attr, nullptr /* preferredDevice */, false /* fromCache */);
8970 }
8971
8972 if (forVolume) {
8973 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8974 // for single volume control in AudioService (such relationship should exist if
8975 // SPEAKER_SAFE is present).
8976 //
8977 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8978 DeviceVector speakerSafeDevices =
8979 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8980 if (!speakerSafeDevices.isEmpty()) {
8981 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8982 devices.remove(speakerSafeDevices);
8983 }
8984 }
8985
8986 return NO_ERROR;
8987}
8988
8989status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8990 AudioProfileVector& audioProfiles,
8991 uint32_t flags,
8992 bool isInput) {
8993 for (const auto& hwModule : mHwModules) {
8994 // the MSD module checks for different conditions
8995 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8996 continue;
8997 }
8998 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8999 : hwModule->getOutputProfiles();
9000 for (const auto& profile : ioProfiles) {
9001 if (!profile->areAllDevicesSupported(devices) ||
9002 !profile->isCompatibleProfileForFlags(
9003 flags, false /*exactMatchRequiredForInputFlags*/)) {
9004 continue;
9005 }
9006 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9007 }
9008 }
9009
9010 if (!isInput) {
9011 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9012 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9013 if (msdModule != nullptr) {
9014 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9015 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9016 for (const auto &profile: msdModule->getOutputProfiles()) {
9017 if (!profile->asAudioPort()->isDirectOutput()) {
9018 continue;
9019 }
9020 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9021 }
9022 } else {
9023 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9024 }
9025 }
9026 }
9027
9028 return NO_ERROR;
9029}
9030
jiabin3ff8d7d2022-12-13 06:27:44 +00009031sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9032 const audio_config_t *config,
9033 audio_output_flags_t flags,
9034 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009035 closeOutput(outputDesc->mIoHandle);
9036 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9037 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9038 if (preferredOutput == nullptr) {
9039 ALOGE("%s failed to reopen output device=%d, caller=%s",
9040 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009041 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009042 return preferredOutput;
9043}
9044
9045void AudioPolicyManager::reopenOutputsWithDevices(
9046 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9047 for (const auto& [output, devices] : outputsToReopen) {
9048 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9049 closeOutput(output);
9050 openOutputWithProfileAndDevice(desc->mProfile, devices);
9051 }
jiabina84c3d32022-12-02 18:59:55 +00009052}
9053
jiabinc44b3462022-12-08 12:52:31 -08009054PortHandleVector AudioPolicyManager::getClientsForStream(
9055 audio_stream_type_t streamType) const {
9056 PortHandleVector clients;
9057 for (size_t i = 0; i < mOutputs.size(); ++i) {
9058 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9059 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9060 }
9061 return clients;
9062}
9063
9064void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9065 PortHandleVector clients;
9066 for (auto stream : streams) {
9067 PortHandleVector clientsForStream = getClientsForStream(stream);
9068 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9069 }
9070 mpClientInterface->invalidateTracks(clients);
9071}
9072
jiabin220eea12024-05-17 17:55:20 +00009073void AudioPolicyManager::updateClientsInternalMute(
9074 const sp<android::SwAudioOutputDescriptor> &desc) {
9075 if (!desc->isBitPerfect() ||
9076 !com::android::media::audioserver::
9077 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9078 // This is only used for bit perfect output now.
9079 return;
9080 }
9081 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9082 bool bitPerfectClientInternalMute = false;
9083 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9084 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9085 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9086 bitPerfectClient = client;
9087 continue;
9088 }
9089 bool muted = false;
9090 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9091 // System sound is muted.
9092 muted = true;
9093 } else {
9094 bitPerfectClientInternalMute = true;
9095 }
9096 if (client->setInternalMute(muted)) {
9097 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9098 if (!result.ok()) {
9099 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9100 continue;
9101 }
9102 media::TrackInternalMuteInfo info;
9103 info.portId = result.value();
9104 info.muted = client->getInternalMute();
9105 clientsInternalMute.push_back(std::move(info));
9106 }
9107 }
9108 if (bitPerfectClient != nullptr &&
9109 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9110 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9111 if (result.ok()) {
9112 media::TrackInternalMuteInfo info;
9113 info.portId = result.value();
9114 info.muted = bitPerfectClient->getInternalMute();
9115 clientsInternalMute.push_back(std::move(info));
9116 } else {
9117 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9118 __func__, bitPerfectClient->portId());
9119 }
9120 }
9121 if (!clientsInternalMute.empty()) {
9122 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9123 status != NO_ERROR) {
9124 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9125 }
9126 }
9127}
9128
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009129} // namespace android