blob: b9c193ff6cf0935717d7b43c488909be839c7773 [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;
Mikhail Naganov285c1732024-09-05 17:26:50 -07001156 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001157 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1158 }
1159 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001160
François Gaffie11d30102018-11-02 16:09:09 +01001161 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1162 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001163 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001164}
1165
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001166status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1167 const audio_attributes_t *srcAttr,
1168 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001169{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001170 if (srcAttr != NULL) {
1171 if (!isValidAttributes(srcAttr)) {
1172 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1173 __func__,
1174 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1175 srcAttr->tags);
1176 return BAD_VALUE;
1177 }
1178 *dstAttr = *srcAttr;
1179 } else {
1180 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1181 ALOGE("%s: invalid stream type", __func__);
1182 return BAD_VALUE;
1183 }
François Gaffiec005e562018-11-06 15:04:49 +01001184 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001185 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001186
1187 // Only honor audibility enforced when required. The client will be
1188 // forced to reconnect if the forced usage changes.
1189 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001190 dstAttr->flags = static_cast<audio_flags_mask_t>(
1191 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001192 }
1193
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001194 return NO_ERROR;
1195}
1196
Kevin Rocard153f92d2018-12-18 18:33:28 -08001197status_t AudioPolicyManager::getOutputForAttrInt(
1198 audio_attributes_t *resultAttr,
1199 audio_io_handle_t *output,
1200 audio_session_t session,
1201 const audio_attributes_t *attr,
1202 audio_stream_type_t *stream,
1203 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001204 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001205 audio_output_flags_t *flags,
1206 audio_port_handle_t *selectedDeviceId,
1207 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001208 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001209 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001210 bool *isSpatialized,
1211 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001212{
François Gaffiec005e562018-11-06 15:04:49 +01001213 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001214 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001215 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001216 const sp<DeviceDescriptor> requestedDevice =
1217 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1218
Eric Laurent8a1095a2019-11-08 14:44:16 -08001219 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001220 *isSpatialized = false;
1221
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001222 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1223 if (status != NO_ERROR) {
1224 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001225 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001226 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001227 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001228 }
François Gaffiec005e562018-11-06 15:04:49 +01001229 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001230
François Gaffiec005e562018-11-06 15:04:49 +01001231 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1232 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001233
Oscar Azucena873d10f2023-01-12 18:34:42 -08001234 bool usePrimaryOutputFromPolicyMixes = false;
1235
Kevin Rocard153f92d2018-12-18 18:33:28 -08001236 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1237 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1238 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001239 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001240 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1241 .channel_mask = config->channel_mask,
1242 .format = config->format,
1243 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001244 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001245 mAvailableOutputDevices, requestedDevice, primaryMix,
1246 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001247 if (status != OK) {
1248 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001249 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001250
Kevin Rocard153f92d2018-12-18 18:33:28 -08001251 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001252 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungced57302024-08-14 11:37:57 -07001253 && (!audio_is_linear_pcm(config->format) ||
1254 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001255 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001256 return BAD_VALUE;
1257 }
1258 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001259 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001260 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1261 primaryMix->mDeviceAddress,
1262 AUDIO_FORMAT_DEFAULT);
1263 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001264 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001265 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1266 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001267 // if a direct output can be opened to deliver the track's multi-channel content to the
1268 // output rather than being downmixed by the primary output, then use this direct
1269 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1270 // mix.
1271 bool tryDirectForChannelMask = policyDesc != nullptr
1272 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1273 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001274 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001275 audio_io_handle_t newOutput;
1276 status = openDirectOutput(
1277 *stream, session, config,
1278 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001279 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001280 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001281 policyDesc = mOutputs.valueFor(newOutput);
1282 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001283 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001284 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001285 policyDesc = nullptr;
1286 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001287 }
1288 if (policyDesc != nullptr) {
1289 policyDesc->mPolicyMix = primaryMix;
1290 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001291 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1292 : AUDIO_PORT_HANDLE_NONE;
1293 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1294 // Remove direct flag as it is not on a direct output.
1295 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1296 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001297
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001298 ALOGV("getOutputForAttr() returns output %d", *output);
1299 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1300 *outputType = API_OUT_MIX_PLAYBACK;
1301 } else {
1302 *outputType = API_OUTPUT_LEGACY;
1303 }
1304 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001305 } else {
1306 if (policyMixDevice != nullptr) {
1307 ALOGE("%s, try to use primary mix but no output found", __func__);
1308 return INVALID_OPERATION;
1309 }
1310 // Fallback to default engine selection as the selected primary mix device is not
1311 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001312 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001313 }
François Gaffiec005e562018-11-06 15:04:49 +01001314 // Virtual sources must always be dynamicaly or explicitly routed
1315 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1316 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1317 return BAD_VALUE;
1318 }
1319 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1320 // in order to let the choice of the order to future vendor engine
1321 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001322
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001323 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001324 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001325 }
1326
Nadav Barb2f18162018-07-18 13:01:53 +03001327 // Set incall music only if device was explicitly set, and fallback to the device which is
1328 // chosen by the engine if not.
1329 // FIXME: provide a more generic approach which is not device specific and move this back
1330 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001331 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001332 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001333 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001334 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001335 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001336 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001337 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001338 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001339 }
1340 }
1341
François Gaffiec005e562018-11-06 15:04:49 +01001342 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1343 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1344 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001345
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001347 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001348 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001349 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001350 ALOGV("%s() Using MSD devices %s instead of devices %s",
1351 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001352 } else {
1353 *output = AUDIO_IO_HANDLE_NONE;
1354 }
1355 }
1356 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001357 sp<PreferredMixerAttributesInfo> info = nullptr;
1358 if (outputDevices.size() == 1) {
1359 info = getPreferredMixerAttributesInfo(
1360 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001361 mEngine->getProductStrategyForAttributes(*resultAttr),
1362 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001363 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1364 // and it is currently active.
1365 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001366 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001367 info = nullptr;
1368 }
jiabin220eea12024-05-17 17:55:20 +00001369 if (com::android::media::audioserver::
1370 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1371 if (info != nullptr && info->getUid() == uid &&
1372 info->configMatches(*config) &&
1373 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1374 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1375 [this, &outputDevices](audio_usage_t usage) {
1376 return mOutputs.isUsageActiveOnDevice(
1377 usage, outputDevices[0]); }))) {
1378 // Bit-perfect request is not allowed when the phone mode is not normal or
1379 // there is any higher priority user case active.
1380 return INVALID_OPERATION;
1381 }
1382 }
jiabina84c3d32022-12-02 18:59:55 +00001383 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001384 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001385 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001386 // The client will be active if the client is currently preferred mixer owner and the
1387 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001388 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001389 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001390 && info->getUid() == uid
1391 && *output != AUDIO_IO_HANDLE_NONE
1392 // When bit-perfect output is selected for the preferred mixer attributes owner,
1393 // only need to consider the config matches.
1394 && mOutputs.valueFor(*output)->isConfigurationMatched(
1395 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001396
1397 if (*isBitPerfect) {
1398 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1399 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001400 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001401 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001402 AudioProfileVector profiles;
1403 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1404 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001405 const auto channels = profiles[0]->getChannels();
1406 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1407 config->channel_mask = *channels.begin();
1408 }
1409 const auto sampleRates = profiles[0]->getSampleRates();
1410 if (!sampleRates.empty() &&
1411 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1412 config->sample_rate = *sampleRates.begin();
1413 }
jiabinf1c73972022-04-14 16:28:52 -07001414 config->format = profiles[0]->getFormat();
1415 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001416 return INVALID_OPERATION;
1417 }
Paul McLeanaa981192015-03-21 09:55:15 -07001418
François Gaffiec005e562018-11-06 15:04:49 +01001419 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001420 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001421 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001422 *selectedDeviceId = outputDevice->getId();
1423 break;
1424 }
1425 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001426
Eric Laurent8a1095a2019-11-08 14:44:16 -08001427 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1428 *outputType = API_OUTPUT_TELEPHONY_TX;
1429 } else {
1430 *outputType = API_OUTPUT_LEGACY;
1431 }
1432
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001433 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1434
1435 return NO_ERROR;
1436}
1437
1438status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1439 audio_io_handle_t *output,
1440 audio_session_t session,
1441 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001442 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001443 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001444 audio_output_flags_t *flags,
1445 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001446 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001447 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001448 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001449 bool *isSpatialized,
1450 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001451{
1452 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1453 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1454 return INVALID_OPERATION;
1455 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001456 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001457 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001458 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001459 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001460 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001461 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001462 const sp<DeviceDescriptor> requestedDevice =
1463 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1464
1465 // Prevent from storing invalid requested device id in clients
1466 const audio_port_handle_t sanitizedRequestedPortId =
1467 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1468 *selectedDeviceId = sanitizedRequestedPortId;
1469
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001470 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001471 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001472 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1473 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001474 if (status != NO_ERROR) {
1475 return status;
1476 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001477 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001478 if (secondaryOutputs != nullptr) {
1479 for (auto &secondaryMix : secondaryMixes) {
1480 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1481 if (outputDesc != nullptr &&
1482 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1483 secondaryOutputs->push_back(outputDesc->mIoHandle);
1484 weakSecondaryOutputDescs.push_back(outputDesc);
1485 }
1486 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001487 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001488
Eric Laurent8fc147b2018-07-22 19:13:55 -07001489 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001490 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001491 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001492 };
jiabin4ef93452019-09-10 14:29:54 -07001493 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001494
Eric Laurentc209fe42020-06-05 18:11:23 -07001495 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001496 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001497 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001498 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001499 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001500 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001501 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001502 std::move(weakSecondaryOutputDescs),
1503 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001504 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001505
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001506 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1507 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001508
Eric Laurente83b55d2014-11-14 10:06:21 -08001509 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001510}
1511
Eric Laurentc529cf62020-04-17 18:19:10 -07001512status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1513 audio_session_t session,
1514 const audio_config_t *config,
1515 audio_output_flags_t flags,
1516 const DeviceVector &devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001517 audio_io_handle_t *output,
1518 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001519
1520 *output = AUDIO_IO_HANDLE_NONE;
1521
1522 // skip direct output selection if the request can obviously be attached to a mixed output
1523 // and not explicitly requested
1524 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1525 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1526 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1527 return NAME_NOT_FOUND;
1528 }
1529
Mikhail Naganov285c1732024-09-05 17:26:50 -07001530 // Reject flag combinations that do not make sense. Note that the requested flags might not
1531 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1532 // combine the requested flags with its own flags, yielding an unsupported combination.
1533 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1534 return NAME_NOT_FOUND;
1535 }
1536
Eric Laurentc529cf62020-04-17 18:19:10 -07001537 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1538 // This prevents creating an offloaded track and tearing it down immediately after start
1539 // when audioflinger detects there is an active non offloadable effect.
1540 // FIXME: We should check the audio session here but we do not have it in this context.
1541 // This may prevent offloading in rare situations where effects are left active by apps
1542 // in the background.
1543 sp<IOProfile> profile;
1544 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1545 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1546 profile = getProfileForOutput(
1547 devices, config->sample_rate, config->format, config->channel_mask,
1548 flags, true /* directOnly */);
1549 }
1550
1551 if (profile == nullptr) {
1552 return NAME_NOT_FOUND;
1553 }
1554
1555 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1556 for (size_t i = 0; i < mOutputs.size(); i++) {
1557 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1558 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1559 // reuse direct output if currently open by the same client
1560 // and configured with same parameters
1561 if ((config->sample_rate == desc->getSamplingRate()) &&
1562 (config->format == desc->getFormat()) &&
1563 (config->channel_mask == desc->getChannelMask()) &&
1564 (session == desc->mDirectClientSession)) {
1565 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301566 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001567 mOutputs.keyAt(i), session);
1568 *output = mOutputs.keyAt(i);
1569 return NO_ERROR;
1570 }
1571 }
1572 }
1573
1574 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001575 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301576 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1577 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001578 return NAME_NOT_FOUND;
1579 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1580 // MMAP gracefully handles lack of an exclusive track resource by mixing
1581 // above the audio framework. For AAudio to know that the limit is reached,
1582 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301583 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1584 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001585 return NAME_NOT_FOUND;
1586 } else {
1587 // Close outputs on this profile, if available, to free resources for this request
1588 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1589 const auto desc = mOutputs.valueAt(i);
1590 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301591 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1592 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001593 closeOutput(desc->mIoHandle);
1594 }
1595 }
1596 }
1597 }
1598
1599 // Unable to close streams to find free resources for this request
1600 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301601 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1602 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001603 return NAME_NOT_FOUND;
1604 }
1605
Atneya Nairb16666a2023-12-11 20:18:33 -08001606 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001607
Michael Chan6fb34492020-12-08 15:44:49 +11001608 // An MSD patch may be using the only output stream that can service this request. Release
1609 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001610 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001611
Eric Laurentf1f22e72021-07-13 14:04:14 +02001612 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001613 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001614 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001615
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001616 // only accept an output with the requested parameters, unless the format can be IEC61937
1617 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1618 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1619 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1620 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001621 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001622 (!ignoreRequestedParametersCheck &&
1623 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1624 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1625 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001626 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1627 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1628 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1629 config->channel_mask, outputDesc->getChannelMask());
1630 if (*output != AUDIO_IO_HANDLE_NONE) {
1631 outputDesc->close();
1632 }
1633 // fall back to mixer output if possible when the direct output could not be open
1634 if (audio_is_linear_pcm(config->format) &&
1635 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1636 return NAME_NOT_FOUND;
1637 }
1638 *output = AUDIO_IO_HANDLE_NONE;
1639 return BAD_VALUE;
1640 }
1641 outputDesc->mDirectOpenCount = 1;
1642 outputDesc->mDirectClientSession = session;
1643
1644 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001645 setOutputDevices(__func__, outputDesc,
1646 devices,
1647 true,
1648 0,
1649 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001650 mPreviousOutputs = mOutputs;
1651 ALOGV("%s returns new direct output %d", __func__, *output);
1652 mpClientInterface->onAudioPortListUpdate();
1653 return NO_ERROR;
1654}
1655
François Gaffie11d30102018-11-02 16:09:09 +01001656audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1657 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001658 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001659 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001660 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001661 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001662 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001663 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001664 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001665{
Andy Hungc88b0642018-04-27 15:42:35 -07001666 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001667
jiabine375d412019-02-26 12:54:53 -08001668 // Discard haptic channel mask when forcing muting haptic channels.
1669 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001670 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1671 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001672
Eric Laurente552edb2014-03-10 17:42:56 -07001673 // open a direct output if required by specified parameters
1674 //force direct flag if offload flag is set: offloading implies a direct output stream
1675 // and all common behaviors are driven by checking only the direct flag
1676 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001677 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1678 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001679 }
Nadav Bar766fb022018-01-07 12:18:03 +02001680 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1681 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001682 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001683
1684 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1685
Eric Laurente83b55d2014-11-14 10:06:21 -08001686 // only allow deep buffering for music stream type
1687 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001688 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001689 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov285c1732024-09-05 17:26:50 -07001690 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001691 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001692 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001693 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001694 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001695 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001696 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001697 audio_is_linear_pcm(config->format) &&
1698 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001699 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001700 AUDIO_OUTPUT_FLAG_DIRECT);
1701 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001702 }
Eric Laurente552edb2014-03-10 17:42:56 -07001703
Carter Hsua3abb402021-10-26 11:11:20 +08001704 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1705 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1706 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1707 }
1708
Eric Laurentf9230d52024-01-26 18:49:09 +01001709 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001710 // was specified and offload or direct playback is not explicitly requested, and there is no
1711 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001712 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001713 if (mSpatializerOutput != nullptr &&
1714 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1715 prefMixerConfigInfo == nullptr &&
1716 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1717 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001718 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001719 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001720 }
1721
Eric Laurentc529cf62020-04-17 18:19:10 -07001722 audio_config_t directConfig = *config;
1723 directConfig.channel_mask = channelMask;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001724
1725 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1726 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001727 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001728 return output;
1729 }
1730
Eric Laurent14cbfca2016-03-17 09:42:16 -07001731 // A request for HW A/V sync cannot fallback to a mixed output because time
1732 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001733 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001734 return AUDIO_IO_HANDLE_NONE;
1735 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001736 // A request for Tuner cannot fallback to a mixed output
1737 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1738 return AUDIO_IO_HANDLE_NONE;
1739 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001740
Eric Laurente552edb2014-03-10 17:42:56 -07001741 // ignoring channel mask due to downmix capability in mixer
1742
1743 // open a non direct output
1744
1745 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001746 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001747 // get which output is suitable for the specified stream. The actual
1748 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001749 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001750 if (prefMixerConfigInfo != nullptr) {
1751 for (audio_io_handle_t outputHandle : outputs) {
1752 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1753 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1754 output = outputHandle;
1755 break;
1756 }
1757 }
1758 if (output == AUDIO_IO_HANDLE_NONE) {
1759 // No output open with the preferred profile. Open a new one.
1760 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1761 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1762 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1763 config.format = prefMixerConfigInfo->getConfigBase().format;
1764 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1765 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1766 &config, prefMixerConfigInfo->getFlags());
1767 if (preferredOutput == nullptr) {
1768 ALOGE("%s failed to open output with preferred mixer config", __func__);
1769 } else {
1770 output = preferredOutput->mIoHandle;
1771 }
1772 }
1773 } else {
1774 // at this stage we should ignore the DIRECT flag as no direct output could be
1775 // found earlier
1776 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001777 if (com::android::media::audioserver::
1778 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1779 // If the preferred mixer attributes is null, do not select the bit-perfect output
1780 // unless the bit-perfect output is the only output.
1781 // The bit-perfect output can exist while the passed in preferred mixer attributes
1782 // info is null when it is a high priority client. The high priority clients are
1783 // ringtone or alarm, which is not a bit-perfect use case.
1784 size_t i = 0;
1785 while (i < outputs.size() && outputs.size() > 1) {
1786 auto desc = mOutputs.valueFor(outputs[i]);
1787 // The output descriptor must not be null here.
1788 if (desc->isBitPerfect()) {
1789 outputs.removeItemsAt(i);
1790 } else {
1791 i += 1;
1792 }
1793 }
1794 }
jiabina84c3d32022-12-02 18:59:55 +00001795 output = selectOutput(
1796 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1797 }
Eric Laurente552edb2014-03-10 17:42:56 -07001798 }
François Gaffie11d30102018-11-02 16:09:09 +01001799 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001800 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001801 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001802
Eric Laurente552edb2014-03-10 17:42:56 -07001803 return output;
1804}
1805
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001806sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001807 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1808 mAvailableInputDevices);
1809 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1810}
1811
1812DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1813 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1814 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001815}
1816
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001817const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001818 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001819 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1820 if (msdModule != 0) {
1821 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1822 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1823 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1824 const struct audio_port_config *source = &patch->mPatch.sources[j];
1825 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1826 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001827 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001828 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001829 }
1830 }
1831 }
1832 return msdPatches;
1833}
1834
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001835bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1836 ssize_t index = mAudioPatches.indexOfKey(handle);
1837 if (index < 0) {
1838 return false;
1839 }
1840 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1841 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1842 if (msdModule == nullptr) {
1843 return false;
1844 }
1845 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1846 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1847 return true;
1848 }
1849 index = getMsdOutputPatches().indexOfKey(handle);
1850 if (index < 0) {
1851 return false;
1852 }
1853 return true;
1854}
1855
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001856status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1857 const InputProfileCollection &inputProfiles,
1858 const OutputProfileCollection &outputProfiles,
1859 const sp<DeviceDescriptor> &sourceDevice,
1860 const sp<DeviceDescriptor> &sinkDevice,
1861 AudioProfileVector& sourceProfiles,
1862 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001863 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001864 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001865 return NO_INIT;
1866 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001867 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001868 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001869 return NO_INIT;
1870 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001871 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001872 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1873 inProfile->supportsDevice(sourceDevice)) {
1874 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001875 }
1876 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001878 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001879 outProfile->supportsDevice(sinkDevice)) {
1880 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 }
1882 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001883 return NO_ERROR;
1884}
1885
1886status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1887 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1888 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1889{
Dean Wheatley16809da2022-12-09 14:55:46 +11001890 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1891 static const std::vector<audio_format_t> formatsOrder = {{
1892 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001893 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1894 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001895 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1896 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1897 // preferred).
1898 std::vector<audio_channel_mask_t> masks = {{
1899 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1900 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1901 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1902 // insert index masks (higher counts most preferred) as preferred over position masks
1903 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1904 masks.insert(
1905 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1906 }
1907 return masks;
1908 }();
1909
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001910 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001911 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1912 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001913 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001914 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1915 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001916 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001917 }
1918 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1919 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1920 sinkConfig->format = bestSinkConfig.format;
1921 // For encoded streams force direct flag to prevent downstream mixing.
1922 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1923 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001924 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1925 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001926 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001927 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1928 // raw and IEC61937 framed streams.
1929 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1930 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1931 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001932 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1933 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001934 sourceConfig->channel_mask =
1935 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1936 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1937 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001938 sourceConfig->format = bestSinkConfig.format;
1939 // Copy input stream directly without any processing (e.g. resampling).
1940 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1941 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1942 if (hwAvSync) {
1943 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1944 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1945 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1946 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1947 }
1948 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1949 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1950 sinkConfig->config_mask |= config_mask;
1951 sourceConfig->config_mask |= config_mask;
1952 return NO_ERROR;
1953}
1954
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001955PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1956 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001957{
1958 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001959 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1960 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1961 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1962 if (deviceModule == nullptr) {
1963 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1964 return patchBuilder;
1965 }
1966 const InputProfileCollection inputProfiles = msdIsSource ?
1967 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1968 const OutputProfileCollection outputProfiles = msdIsSource ?
1969 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1970
1971 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1972 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1973 device : getMsdAudioOutDevices().itemAt(0);
1974 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1975
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001976 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1977 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001978 AudioProfileVector sourceProfiles;
1979 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001980 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1981 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001982 for (auto hwAvSync : { true, false }) {
1983 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1984 sourceProfiles, sinkProfiles) != NO_ERROR) {
1985 continue;
1986 }
1987 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1988 &sinkConfig) == NO_ERROR) {
1989 // Found a matching config. Re-create PatchBuilder with this config.
1990 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1991 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001992 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001993 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001994 " supporting PCM format conversion.", __func__);
1995 return patchBuilder;
1996}
1997
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001998status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001999 DeviceVector devices;
2000 if (outputDevices != nullptr && outputDevices->size() > 0) {
2001 devices.add(*outputDevices);
2002 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002003 // Use media strategy for unspecified output device. This should only
2004 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2005 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002006 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002007 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002008 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002009 }
Michael Chan6fb34492020-12-08 15:44:49 +11002010 std::vector<PatchBuilder> patchesToCreate;
2011 for (auto i = 0u; i < devices.size(); ++i) {
2012 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002013 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002014 }
2015 // Retain only the MSD patches associated with outputDevices request.
2016 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002017 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002018 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2019 auto retainedPatch = false;
2020 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2021 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2022 patchesToRemove.removeItemsAt(i);
2023 retainedPatch = true;
2024 break;
2025 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002026 }
Michael Chan6fb34492020-12-08 15:44:49 +11002027 if (retainedPatch) {
2028 it = patchesToCreate.erase(it);
2029 continue;
2030 }
2031 ++it;
2032 }
2033 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2034 return NO_ERROR;
2035 }
2036 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2037 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002038 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002039 }
Michael Chan6fb34492020-12-08 15:44:49 +11002040 status_t status = NO_ERROR;
2041 for (const auto &p : patchesToCreate) {
2042 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2043 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2044 char message[256];
2045 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2046 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2047 currStatus == NO_ERROR ? "Success" : "Error",
2048 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2049 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2050 if (currStatus == NO_ERROR) {
2051 ALOGD("%s", message);
2052 } else {
2053 ALOGE("%s", message);
2054 if (status == NO_ERROR) {
2055 status = currStatus;
2056 }
2057 }
2058 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002059 return status;
2060}
2061
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002062void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2063 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002064 for (size_t i = 0; i < msdPatches.size(); i++) {
2065 const auto& patch = msdPatches[i];
2066 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2067 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2068 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2069 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2070 releaseAudioPatch(patch->getHandle(), mUidCached);
2071 break;
2072 }
2073 }
2074 }
2075}
2076
Dorin Drimus94d94412022-02-02 09:05:02 +01002077bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002078 DeviceVector devicesToCheck =
2079 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002080 AudioPatchCollection msdPatches = getMsdOutputPatches();
2081 for (size_t i = 0; i < msdPatches.size(); i++) {
2082 const auto& patch = msdPatches[i];
2083 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2084 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2085 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2086 const auto& foundDevice = devicesToCheck.getDevice(
2087 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2088 if (foundDevice != nullptr) {
2089 devicesToCheck.remove(foundDevice);
2090 if (devicesToCheck.isEmpty()) {
2091 return true;
2092 }
2093 }
2094 }
2095 }
2096 }
2097 return false;
2098}
2099
Eric Laurente0720872014-03-11 09:30:41 -07002100audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002101 audio_output_flags_t flags,
2102 audio_format_t format,
2103 audio_channel_mask_t channelMask,
2104 uint32_t samplingRate,
2105 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002106{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002107 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2108 "%s called with format %#x", __func__, format);
2109
jiabinebb6af42020-06-09 17:31:17 -07002110 // Return the output that haptic-generating attached to when 1) session id is specified,
2111 // 2) haptic-generating effect exists for given session id and 3) the output that
2112 // haptic-generating effect attached to is in given outputs.
2113 if (sessionId != AUDIO_SESSION_NONE) {
2114 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2115 sessionId, FX_IID_HAPTICGENERATOR);
2116 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2117 return hapticGeneratingOutput;
2118 }
2119 }
2120
Eric Laurent16c66dd2019-05-01 17:54:10 -07002121 // Flags disqualifying an output: the match must happen before calling selectOutput()
2122 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2123 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2124
2125 // Flags expressing a functional request: must be honored in priority over
2126 // other criteria
2127 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2128 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002129 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2130 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002131 // Flags expressing a performance request: have lower priority than serving
2132 // requested sampling rate or channel mask
2133 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2134 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2135 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2136
2137 const audio_output_flags_t functionalFlags =
2138 (audio_output_flags_t)(flags & kFunctionalFlags);
2139 const audio_output_flags_t performanceFlags =
2140 (audio_output_flags_t)(flags & kPerformanceFlags);
2141
2142 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2143
Eric Laurente552edb2014-03-10 17:42:56 -07002144 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002145 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002146 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002147 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002148 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002149 // with tiebreak preferring the minimum number of extra functional flags
2150 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002151 // 3: the output supporting the exact channel mask
2152 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002153 // 5: the output with the highest sampling rate if the requested sample rate is
2154 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002155 // 6: the output with the highest number of requested performance flags
2156 // 7: the output with the bit depth the closest to the requested one
2157 // 8: the primary output
2158 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002159
Eric Laurent16c66dd2019-05-01 17:54:10 -07002160 // matching criteria values in priority order for best matching output so far
2161 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002162
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002163 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002164 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2165 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2166 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002167
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002168 for (audio_io_handle_t output : outputs) {
2169 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002170 // matching criteria values in priority order for current output
2171 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002172
Eric Laurent16c66dd2019-05-01 17:54:10 -07002173 if (outputDesc->isDuplicated()) {
2174 continue;
2175 }
2176 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2177 continue;
2178 }
Eric Laurent8838a382014-09-08 16:44:28 -07002179
Eric Laurent16c66dd2019-05-01 17:54:10 -07002180 // If haptic channel is specified, use the haptic output if present.
2181 // When using haptic output, same audio format and sample rate are required.
2182 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002183 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002184 // skip if haptic channel specified but output does not support it, or output support haptic
2185 // but there is no haptic channel requested AND no orphan haptic effect exist
2186 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2187 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 continue;
2189 }
Shunkai Yao808da212024-04-05 22:50:56 +00002190 // In the case of audio-coupled-haptic playback, there is no format conversion and
2191 // resampling in the framework, same format/channel/sampleRate for client and the output
2192 // thread is required. In the case of HapticGenerator effect, do not require format
2193 // matching.
2194 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2195 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002196 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002197 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002198 }
2199
2200 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002201 const int matchingFunctionalFlags =
2202 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2203 const int totalFunctionalFlags =
2204 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2205 // Prefer matching functional flags, but subtract unnecessary functional flags.
2206 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002207
2208 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002209 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2210 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002211 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2212 channelCount <= outputChannelCount) {
2213 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002214 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2215 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002216 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002217 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002218 currentMatchCriteria[3] = outputChannelCount;
2219 }
2220
2221 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002222 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002223 int diff; // avoid unsigned integer overflow.
2224 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2225
2226 // prefer the closest output sampling rate greater than or equal to target
2227 // if none exists, prefer the closest output sampling rate less than target.
2228 //
2229 // criteria is offset to make non-negative.
2230 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 }
2232
2233 // performance flags match
2234 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2235
2236 // format match
2237 if (format != AUDIO_FORMAT_INVALID) {
2238 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002239 PolicyAudioPort::kFormatDistanceMax -
2240 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002241 }
2242
2243 // primary output match
2244 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2245
2246 // compare match criteria by priority then value
2247 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2248 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2249 bestMatchCriteria = currentMatchCriteria;
2250 bestOutput = output;
2251
2252 std::stringstream result;
2253 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2254 std::ostream_iterator<int>(result, " "));
2255 ALOGV("%s new bestOutput %d criteria %s",
2256 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002257 }
2258 }
2259
Eric Laurent16c66dd2019-05-01 17:54:10 -07002260 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002261}
2262
Eric Laurent8fc147b2018-07-22 19:13:55 -07002263status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002264{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002265 ALOGV("%s portId %d", __FUNCTION__, portId);
2266
2267 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2268 if (outputDesc == 0) {
2269 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002270 return BAD_VALUE;
2271 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002272 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002273
Eric Laurent8fc147b2018-07-22 19:13:55 -07002274 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002275 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002276
jiabin220eea12024-05-17 17:55:20 +00002277 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2278 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2279 && outputDesc->isBitPerfect()) {
2280 // Usually, APM selects bit-perfect output for high priority use cases only when
2281 // bit-perfect output is the only output that can be routed to the selected device.
2282 // However, here is no need to play high priority use cases such as ringtone and alarm
2283 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2284 // can attach to new output.
2285 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2286 __func__, client->stream());
2287 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2288 return DEAD_OBJECT;
2289 }
2290
Eric Laurent733ce942017-12-07 12:18:25 -08002291 status_t status = outputDesc->start();
2292 if (status != NO_ERROR) {
2293 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002294 }
2295
Eric Laurent97ac8712018-07-27 18:59:02 -07002296 uint32_t delayMs;
2297 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002298
2299 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002300 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002301 if (status == DEAD_OBJECT) {
2302 sp<SwAudioOutputDescriptor> desc =
2303 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2304 if (desc == nullptr) {
2305 // This is not common, it may indicate something wrong with the HAL.
2306 ALOGE("%s unable to open output with default config", __func__);
2307 return status;
2308 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002309 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002310 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002311 }
jiabina84c3d32022-12-02 18:59:55 +00002312
2313 // If the client is the first one active on preferred mixer parameters, reopen the output
2314 // if the current mixer parameters doesn't match the preferred one.
2315 if (outputDesc->devices().size() == 1) {
2316 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2317 outputDesc->devices()[0]->getId(), client->strategy());
2318 if (info != nullptr && info->getUid() == client->uid()) {
2319 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2320 info->getConfigBase(), info->getFlags())) {
2321 stopSource(outputDesc, client);
2322 outputDesc->stop();
2323 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2324 config.channel_mask = info->getConfigBase().channel_mask;
2325 config.sample_rate = info->getConfigBase().sample_rate;
2326 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002327 sp<SwAudioOutputDescriptor> desc =
2328 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2329 if (desc == nullptr) {
2330 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002331 }
jiabin220eea12024-05-17 17:55:20 +00002332 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002333 // Intentionally return error to let the client side resending request for
2334 // creating and starting.
2335 return DEAD_OBJECT;
2336 }
2337 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002338 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002339 // If it is first bit-perfect client, reroute all clients that will be routed to
2340 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2341 PortHandleVector clientsToInvalidate;
2342 for (size_t i = 0; i < mOutputs.size(); i++) {
2343 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002344 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002345 continue;
2346 }
2347 for (const auto& c : mOutputs[i]->getClientIterable()) {
2348 clientsToInvalidate.push_back(c->portId());
2349 }
2350 }
2351 if (!clientsToInvalidate.empty()) {
2352 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2353 __func__);
2354 mpClientInterface->invalidateTracks(clientsToInvalidate);
2355 }
2356 }
jiabina84c3d32022-12-02 18:59:55 +00002357 }
2358 }
2359
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002360 if (client->hasPreferredDevice()) {
2361 // playback activity with preferred device impacts routing occurred, inform upper layers
2362 mpClientInterface->onRoutingUpdated();
2363 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002364 if (delayMs != 0) {
2365 usleep(delayMs * 1000);
2366 }
2367
jiabin220eea12024-05-17 17:55:20 +00002368 if (status == NO_ERROR &&
2369 outputDesc->mPreferredAttrInfo != nullptr &&
2370 outputDesc->isBitPerfect() &&
2371 com::android::media::audioserver::
2372 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2373 // A new client is started on bit-perfect output, update all clients internal mute.
2374 updateClientsInternalMute(outputDesc);
2375 }
2376
Eric Laurentc75307b2015-03-17 15:29:32 -07002377 return status;
2378}
2379
Eric Laurent96d1dda2022-03-14 17:14:19 +01002380bool AudioPolicyManager::isLeUnicastActive() const {
2381 if (isInCall()) {
2382 return true;
2383 }
2384 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2385}
2386
2387bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2388 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2389 return false;
2390 }
2391 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2392 ALOGV("%s active %d", __func__, active);
2393 return active;
2394}
2395
Eric Laurent97ac8712018-07-27 18:59:02 -07002396status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2397 const sp<TrackClientDescriptor>& client,
2398 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002399{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002400 // cannot start playback of STREAM_TTS if any other output is being used
2401 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002402
2403 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002404 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002405 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002406 auto clientStrategy = client->strategy();
2407 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002408 if (stream == AUDIO_STREAM_TTS) {
2409 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002410 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002411 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002412 return INVALID_OPERATION;
2413 } else {
2414 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2415 }
2416 } else {
2417 // some playback other than beacon starts
2418 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2419 }
2420
Eric Laurent77305a62016-07-25 16:39:22 -07002421 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002422 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002423 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002424
François Gaffie11d30102018-11-02 16:09:09 +01002425 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002426 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002427 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002428 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002429 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002430 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002431 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002432 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002433 } else {
2434 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002435 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002436 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2437 AUDIO_FORMAT_DEFAULT);
2438 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2439 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002440 }
2441
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002442 // requiresMuteCheck is false when we can bypass mute strategy.
2443 // It covers a common case when there is no materially active audio
2444 // and muting would result in unnecessary delay and dropped audio.
2445 const uint32_t outputLatencyMs = outputDesc->latency();
2446 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002447 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002448
Eric Laurente552edb2014-03-10 17:42:56 -07002449 // increment usage count for this stream on the requested output:
2450 // NOTE that the usage count is the same for duplicated output and hardware output which is
2451 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002452 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002453
2454 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002455 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002456 // Preferred device may be exclusive, use only if no other active clients on this output
2457 devices = DeviceVector(
2458 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2459 } else {
2460 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2461 }
François Gaffie11d30102018-11-02 16:09:09 +01002462 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002463 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002464 }
2465 }
Eric Laurente552edb2014-03-10 17:42:56 -07002466
François Gaffiec005e562018-11-06 15:04:49 +01002467 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002468 selectOutputForMusicEffects();
2469 }
2470
François Gaffie1c878552018-11-22 16:53:21 +01002471 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002472 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002473 if (devices.isEmpty()) {
2474 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002475 }
François Gaffiec005e562018-11-06 15:04:49 +01002476 bool shouldWait =
2477 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2478 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2479 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002480 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002481 const bool needToCloseBitPerfectOutput =
2482 (com::android::media::audioserver::
2483 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2484 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2485 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002486 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002487 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002488 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002489 // An output has a shared device if
2490 // - managed by the same hw module
2491 // - supports the currently selected device
2492 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002493 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002494
Eric Laurent77305a62016-07-25 16:39:22 -07002495 // force a device change if any other output is:
2496 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002497 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002498 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002499 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002500 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002501 // change the device currently selected by the other output.
2502 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002503 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002504 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002505 force = true;
2506 }
2507 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002508 // a notification so that audio focus effect can propagate, or that a mute/unmute
2509 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002510 const uint32_t latencyMs = desc->latency();
2511 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2512
2513 if (shouldWait && isActive && (waitMs < latencyMs)) {
2514 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002515 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002516
2517 // Require mute check if another output is on a shared device
2518 // and currently active to have proper drain and avoid pops.
2519 // Note restoring AudioTracks onto this output needs to invoke
2520 // a volume ramp if there is no mute.
2521 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002522
2523 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2524 outputsToReopen.push_back(desc);
2525 }
Eric Laurente552edb2014-03-10 17:42:56 -07002526 }
2527 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002528
jiabin220eea12024-05-17 17:55:20 +00002529 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002530 // If the output is open with preferred mixer attributes, but the routed device is
2531 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2532 // changed.
2533 return DEAD_OBJECT;
2534 }
jiabin220eea12024-05-17 17:55:20 +00002535 for (auto& outputToReopen : outputsToReopen) {
2536 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2537 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002538 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302539 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2540 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002541
Eric Laurente552edb2014-03-10 17:42:56 -07002542 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002543 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002544 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002545 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002546 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002547 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002548 outputDesc->useHwGain() /*force*/)) {
2549 // request AudioService to reinitialize the volume curves asynchronously
2550 ALOGE("checkAndSetVolume failed, requesting volume range init");
2551 mpClientInterface->onVolumeRangeInitRequest();
2552 };
Eric Laurente552edb2014-03-10 17:42:56 -07002553
2554 // update the outputs if starting an output with a stream that can affect notification
2555 // routing
2556 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002557
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002558 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002559 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002560 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002561 }
Eric Laurentdc462862016-07-19 12:29:53 -07002562
2563 if (waitMs > muteWaitMs) {
2564 *delayMs = waitMs - muteWaitMs;
2565 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002566
2567 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2568 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2569 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2570 // change occurs after the MixerThread starts and causes a stream volume
2571 // glitch.
2572 //
2573 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002574 }
Eric Laurentdc462862016-07-19 12:29:53 -07002575
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002576 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002577 mEngine->getForceUse(
2578 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002579 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002580 }
2581
Eric Laurent97ac8712018-07-27 18:59:02 -07002582 // Automatically enable the remote submix input when output is started on a re routing mix
2583 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002584 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2585 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002586 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2587 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2588 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002589 "remote-submix",
2590 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002591 }
2592
Eric Laurent96d1dda2022-03-14 17:14:19 +01002593 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2594
Eric Laurente552edb2014-03-10 17:42:56 -07002595 return NO_ERROR;
2596}
2597
Eric Laurent96d1dda2022-03-14 17:14:19 +01002598void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2599 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2600 bool isUnicastActive = isLeUnicastActive();
2601
2602 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002603 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002604 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2605 for (size_t i = 0; i < mOutputs.size(); i++) {
2606 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2607 if (desc != ignoredOutput && desc->isActive()
2608 && ((isUnicastActive &&
2609 !desc->devices().
2610 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2611 || (wasUnicastActive &&
2612 !desc->devices().getDevicesFromTypes(
2613 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2614 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2615 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002616 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002617 // If the device is using preferred mixer attributes, the output need to reopen
2618 // with default configuration when the new selected devices are different from
2619 // current routing devices.
2620 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2621 continue;
2622 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302623 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002624 // re-apply device specific volume if not done by setOutputDevice()
2625 if (!force) {
2626 applyStreamVolumes(desc, newDevices.types(), delayMs);
2627 }
2628 }
2629 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002630 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002631 }
2632}
2633
Eric Laurent8fc147b2018-07-22 19:13:55 -07002634status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002635{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002636 ALOGV("%s portId %d", __FUNCTION__, portId);
2637
2638 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2639 if (outputDesc == 0) {
2640 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002641 return BAD_VALUE;
2642 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002643 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002644
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002645 if (client->hasPreferredDevice(true)) {
2646 // playback activity with preferred device impacts routing occurred, inform upper layers
2647 mpClientInterface->onRoutingUpdated();
2648 }
2649
Eric Laurent97ac8712018-07-27 18:59:02 -07002650 ALOGV("stopOutput() output %d, stream %d, session %d",
2651 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002652
Eric Laurent97ac8712018-07-27 18:59:02 -07002653 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002654
Eric Laurent733ce942017-12-07 12:18:25 -08002655 if (status == NO_ERROR ) {
2656 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002657 } else {
2658 return status;
2659 }
2660
2661 if (outputDesc->devices().size() == 1) {
2662 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2663 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002664 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002665 if (info != nullptr && info->getUid() == client->uid()) {
2666 info->decreaseActiveClient();
2667 if (info->getActiveClientCount() == 0) {
2668 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002669 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002670 }
2671 }
jiabin220eea12024-05-17 17:55:20 +00002672 if (com::android::media::audioserver::
2673 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2674 !outputReopened && outputDesc->isBitPerfect()) {
2675 // Only need to update the clients' internal mute when the output is bit-perfect and it
2676 // is not reopened.
2677 updateClientsInternalMute(outputDesc);
2678 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002679 }
2680 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002681}
2682
Eric Laurent97ac8712018-07-27 18:59:02 -07002683status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2684 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002685{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002686 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002687 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002688 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002689 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002690
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002691 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2692
François Gaffie1c878552018-11-22 16:53:21 +01002693 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2694 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002695 // Automatically disable the remote submix input when output is stopped on a
2696 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002697 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002698 if (isSingleDeviceType(
2699 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002700 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002701 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002702 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2703 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002704 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002705 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002706 }
2707 }
2708 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002709 if (client->hasPreferredDevice(true) &&
2710 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002711 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002712 forceDeviceUpdate = true;
2713 }
2714
Eric Laurente552edb2014-03-10 17:42:56 -07002715 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002716 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002717
Eric Laurente552edb2014-03-10 17:42:56 -07002718 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002719 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002720 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002721 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002722
2723 // If the routing does not change, if an output is routed on a device using HwGain
2724 // (aka setAudioPortConfig) and there are still active clients following different
2725 // volume group(s), force reapply volume
2726 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2727 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2728
Eric Laurente552edb2014-03-10 17:42:56 -07002729 // delay the device switch by twice the latency because stopOutput() is executed when
2730 // the track stop() command is received and at that time the audio track buffer can
2731 // still contain data that needs to be drained. The latency only covers the audio HAL
2732 // and kernel buffers. Also the latency does not always include additional delay in the
2733 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302734 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002735 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002736
2737 // force restoring the device selection on other active outputs if it differs from the
2738 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002739 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002740 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002741 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002742 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002743 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002744 desc->isActive() &&
2745 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002746 (newDevices != desc->devices())) {
2747 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2748 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002749
jiabin220eea12024-05-17 17:55:20 +00002750 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002751 // If the device is using preferred mixer attributes, the output need to
2752 // reopen with default configuration when the new selected devices are
2753 // different from current routing devices.
2754 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2755 continue;
2756 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302757 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002758
Eric Laurent57de36c2016-09-28 16:59:11 -07002759 // re-apply device specific volume if not done by setOutputDevice()
2760 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002761 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002762 }
Eric Laurente552edb2014-03-10 17:42:56 -07002763 }
2764 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002765 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002766 // update the outputs if stopping one with a stream that can affect notification routing
2767 handleNotificationRoutingForStream(stream);
2768 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002769
2770 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2771 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002772 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002773 }
2774
François Gaffiec005e562018-11-06 15:04:49 +01002775 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002776 selectOutputForMusicEffects();
2777 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002778
2779 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2780
Eric Laurente552edb2014-03-10 17:42:56 -07002781 return NO_ERROR;
2782 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002783 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002784 return INVALID_OPERATION;
2785 }
2786}
2787
jiabinbce0c1d2020-10-05 11:20:18 -07002788bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002789{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002790 ALOGV("%s portId %d", __FUNCTION__, portId);
2791
2792 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2793 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002794 // If an output descriptor is closed due to a device routing change,
2795 // then there are race conditions with releaseOutput from tracks
2796 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2797 // destroyed shortly thereafter.
2798 //
2799 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002800 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002801 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002802 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002803
2804 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002805
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302806 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2807 if (outputDesc->isClientActive(client)) {
2808 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2809 stopOutput(portId);
2810 }
2811
Eric Laurent8fc147b2018-07-22 19:13:55 -07002812 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2813 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002814 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002815 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002816 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002817 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002818 if (--outputDesc->mDirectOpenCount == 0) {
2819 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002820 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002821 }
2822 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302823
Andy Hung39efb7a2018-09-26 15:39:28 -07002824 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002825 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2826 // The output is pending reopened to query dynamic profiles and
2827 // there is no active clients
2828 closeOutput(outputDesc->mIoHandle);
2829 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2830 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2831 if (newOutputDesc == nullptr) {
2832 ALOGE("%s failed to open output", __func__);
2833 }
2834 return true;
2835 }
2836 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002837}
2838
Eric Laurentcaf7f482014-11-25 17:50:47 -08002839status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2840 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002841 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002842 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002843 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002844 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002845 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002846 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002847 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002848 audio_port_handle_t *portId,
2849 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002850{
François Gaffiec005e562018-11-06 15:04:49 +01002851 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002852 "flags %#x attributes=%s requested device ID %d",
2853 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2854 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002855
Eric Laurentad2e7b92017-09-14 20:06:42 -07002856 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002857 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002858 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002859 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002860 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002861 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002862 sp<RecordClientDescriptor> clientDesc;
2863 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002864 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002865 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002866
2867 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2868 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2869 return INVALID_OPERATION;
2870 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002871
Francois Gaffie716e1432019-01-14 16:58:59 +01002872 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2873 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002874 }
2875
Paul McLean466dc8e2015-04-17 13:15:36 -06002876 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002877 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002878 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002879
Eric Laurentad2e7b92017-09-14 20:06:42 -07002880 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2881 // possible
2882 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2883 *input != AUDIO_IO_HANDLE_NONE) {
2884 ssize_t index = mInputs.indexOfKey(*input);
2885 if (index < 0) {
2886 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2887 status = BAD_VALUE;
2888 goto error;
2889 }
2890 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002891 RecordClientVector clients = inputDesc->getClientsForSession(session);
2892 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002893 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2894 status = BAD_VALUE;
2895 goto error;
2896 }
2897 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2898 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002899 // corresponds to a new client and is only permitted from the same UID.
2900 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002901 if (clients.size() > 1) {
2902 for (const auto& client : clients) {
2903 // The client map is ordered by key values (portId) and portIds are allocated
2904 // incrementaly. So the first client in this list is the one opened by audio flinger
2905 // when the mmap stream is created and should be ignored as it does not correspond
2906 // to an actual client
2907 if (client == *clients.cbegin()) {
2908 continue;
2909 }
2910 if (uid != client->uid() && !client->isSilenced()) {
2911 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2912 uid, client->portId(), client->uid());
2913 status = INVALID_OPERATION;
2914 goto error;
2915 }
Eric Laurent331679c2018-04-16 17:03:16 -07002916 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002917 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002918 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002919 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002920
Eric Laurentfecbceb2021-02-09 14:46:43 +01002921 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002922 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002923 }
2924
2925 *input = AUDIO_IO_HANDLE_NONE;
2926 *inputType = API_INPUT_INVALID;
2927
Francois Gaffie716e1432019-01-14 16:58:59 +01002928 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002929 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002930 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002931 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002932 ALOGW("%s could not find input mix for attr %s",
2933 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002934 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002935 }
jiabinc1de2df2019-05-07 14:26:40 -07002936 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2937 String8(attr->tags + strlen("addr=")),
2938 AUDIO_FORMAT_DEFAULT);
2939 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002940 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002941 __func__, attributes.source, attributes.tags);
2942 status = BAD_VALUE;
2943 goto error;
2944 }
2945
Kevin Rocard25f9b052019-02-27 15:08:54 -08002946 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2947 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2948 } else {
2949 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2950 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002951 if (virtualDeviceId) {
2952 *virtualDeviceId = policyMix->mVirtualDeviceId;
2953 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002954 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002955 if (explicitRoutingDevice != nullptr) {
2956 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002957 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002958 // Prevent from storing invalid requested device id in clients
2959 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002960 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002961 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2962 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002963 }
François Gaffie11d30102018-11-02 16:09:09 +01002964 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002965 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002966 status = BAD_VALUE;
2967 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002968 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002969 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2970 *inputType = API_INPUT_MIX_CAPTURE;
2971 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002972 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2973 // there is an external policy, but this input is attached to a mix of recorders,
2974 // meaning it receives audio injected into the framework, so the recorder doesn't
2975 // know about it and is therefore considered "legacy"
2976 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002977
2978 if (virtualDeviceId) {
2979 *virtualDeviceId = policyMix->mVirtualDeviceId;
2980 }
François Gaffie11d30102018-11-02 16:09:09 +01002981 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002982 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002983 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002984 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002985 } else {
2986 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002987 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002988
Eric Laurent599c7582015-12-07 18:05:55 -08002989 }
2990
François Gaffiec005e562018-11-06 15:04:49 +01002991 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002992 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002993 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002994 AudioProfileVector profiles;
2995 status_t ret = getProfilesForDevices(
2996 DeviceVector(device), profiles, flags, true /*isInput*/);
2997 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002998 const auto channels = profiles[0]->getChannels();
2999 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3000 config->channel_mask = *channels.begin();
3001 }
3002 const auto sampleRates = profiles[0]->getSampleRates();
3003 if (!sampleRates.empty() &&
3004 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3005 config->sample_rate = *sampleRates.begin();
3006 }
jiabinf1c73972022-04-14 16:28:52 -07003007 config->format = profiles[0]->getFormat();
3008 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003009 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003010 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003011
Marvin Ramine5a122d2023-12-07 13:57:59 +01003012
3013 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3014 *virtualDeviceId = policyMix->mVirtualDeviceId;
3015 }
3016
Eric Laurent8f42ea12018-08-08 09:08:25 -07003017exit:
3018
François Gaffiec005e562018-11-06 15:04:49 +01003019 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3020 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003021
Francois Gaffie716e1432019-01-14 16:58:59 +01003022 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003023 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003024 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025
Mikhail Naganov2996f672019-04-18 12:29:59 -07003026 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003027 requestedDeviceId, attributes.source, flags,
3028 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003029 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003030 // Move (if found) effect for the client session to its input
3031 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003032 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003033
3034 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3035 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003036
Eric Laurent599c7582015-12-07 18:05:55 -08003037 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003038
3039error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003040 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003041}
3042
3043
François Gaffie11d30102018-11-02 16:09:09 +01003044audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003045 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003046 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003047 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003048 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003049 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003050{
3051 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003052 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003053 bool isSoundTrigger = false;
3054
François Gaffiec005e562018-11-06 15:04:49 +01003055 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003056 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3057 if (index >= 0) {
3058 input = mSoundTriggerSessions.valueFor(session);
3059 isSoundTrigger = true;
3060 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3061 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3062 } else {
3063 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003064 }
François Gaffiec005e562018-11-06 15:04:49 +01003065 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003066 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003067 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003068 }
3069
Carter Hsua3abb402021-10-26 11:11:20 +08003070 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3071 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3072 }
3073
Eric Laurentfe231122017-11-17 17:48:06 -08003074 // sampling rate and flags may be updated by getInputProfile
3075 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3076 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003077 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003078 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003079 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003080 // find a compatible input profile (not necessarily identical in parameters)
3081 sp<IOProfile> profile = getInputProfile(
3082 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3083 if (profile == nullptr) {
3084 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003085 }
jiabin2fd710d2022-05-02 23:20:22 +00003086
Glenn Kasten05ddca52016-02-11 08:17:12 -08003087 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003088 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003089 if (samplingRate == 0) {
3090 samplingRate = profileSamplingRate;
3091 }
Eric Laurente552edb2014-03-10 17:42:56 -07003092
Eric Laurent322b4d22015-04-03 15:57:54 -07003093 if (profile->getModuleHandle() == 0) {
3094 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003095 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003096 }
3097
Eric Laurentec376dc2021-04-08 20:41:22 +02003098 // Reuse an already opened input if a client with the same session ID already exists
3099 // on that input
3100 for (size_t i = 0; i < mInputs.size(); i++) {
3101 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3102 if (desc->mProfile != profile) {
3103 continue;
3104 }
3105 RecordClientVector clients = desc->clientsList();
3106 for (const auto &client : clients) {
3107 if (session == client->session()) {
3108 return desc->mIoHandle;
3109 }
3110 }
3111 }
3112
Eric Laurent3974e3b2017-12-07 17:58:43 -08003113 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003114 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003115 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003116 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003117 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003118 continue;
3119 }
3120 // if sound trigger, reuse input if used by other sound trigger on same session
3121 // else
3122 // reuse input if active client app is not in IDLE state
3123 //
3124 RecordClientVector clients = desc->clientsList();
3125 bool doClose = false;
3126 for (const auto& client : clients) {
3127 if (isSoundTrigger != client->isSoundTrigger()) {
3128 continue;
3129 }
3130 if (client->isSoundTrigger()) {
3131 if (session == client->session()) {
3132 return desc->mIoHandle;
3133 }
3134 continue;
3135 }
3136 if (client->active() && client->appState() != APP_STATE_IDLE) {
3137 return desc->mIoHandle;
3138 }
3139 doClose = true;
3140 }
3141 if (doClose) {
3142 closeInput(desc->mIoHandle);
3143 } else {
3144 i++;
3145 }
3146 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003147 }
3148
Eric Laurentfe231122017-11-17 17:48:06 -08003149 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003150
Eric Laurentfe231122017-11-17 17:48:06 -08003151 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3152 lConfig.sample_rate = profileSamplingRate;
3153 lConfig.channel_mask = profileChannelMask;
3154 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003155
François Gaffie11d30102018-11-02 16:09:09 +01003156 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003157
3158 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003159 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003160 (profileSamplingRate != lConfig.sample_rate) ||
3161 !audio_formats_match(profileFormat, lConfig.format) ||
3162 (profileChannelMask != lConfig.channel_mask)) {
3163 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003164 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003165 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003166 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003167 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003168 }
Eric Laurent599c7582015-12-07 18:05:55 -08003169 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003170 }
3171
Eric Laurentc722f302014-12-10 11:21:49 -08003172 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003173
Eric Laurent599c7582015-12-07 18:05:55 -08003174 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003175 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003176
Eric Laurent599c7582015-12-07 18:05:55 -08003177 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003178}
3179
Eric Laurent4eb58f12018-12-07 16:41:02 -08003180status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003181{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003182 ALOGV("%s portId %d", __FUNCTION__, portId);
3183
3184 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3185 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003186 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003187 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003188 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003189 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003190 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003191 if (client->active()) {
3192 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3193 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003194 }
3195
Eric Laurent8f42ea12018-08-08 09:08:25 -07003196 audio_session_t session = client->session();
3197
Eric Laurent4eb58f12018-12-07 16:41:02 -08003198 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003199
Eric Laurent4eb58f12018-12-07 16:41:02 -08003200 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003201
Eric Laurent4eb58f12018-12-07 16:41:02 -08003202 status_t status = inputDesc->start();
3203 if (status != NO_ERROR) {
3204 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003205 }
Eric Laurente552edb2014-03-10 17:42:56 -07003206
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003207 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003208 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003209 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003210
Eric Laurent8f42ea12018-08-08 09:08:25 -07003211 // indicate active capture to sound trigger service if starting capture from a mic on
3212 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003213 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003214 if (device != nullptr) {
3215 status = setInputDevice(input, device, true /* force */);
3216 } else {
3217 ALOGW("%s no new input device can be found for descriptor %d",
3218 __FUNCTION__, inputDesc->getId());
3219 status = BAD_VALUE;
3220 }
Eric Laurente552edb2014-03-10 17:42:56 -07003221
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003222 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003223 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003224 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003225 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003226 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3227 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003228 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003229 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003230
François Gaffie11d30102018-11-02 16:09:09 +01003231 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3232 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003233 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003234 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003235 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003236
Eric Laurent8f42ea12018-08-08 09:08:25 -07003237 // automatically enable the remote submix output when input is started if not
3238 // used by a policy mix of type MIX_TYPE_RECORDERS
3239 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003240 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003241 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003242 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003243 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003244 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3245 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003246 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003247 if (address != "") {
3248 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3249 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003250 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003251 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003252 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003253 } else if (status != NO_ERROR) {
3254 // Restore client activity state.
3255 inputDesc->setClientActive(client, false);
3256 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003257 }
3258
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003259 ALOGV("%s input %d source = %d status = %d exit",
3260 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003261
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003262 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003263}
3264
Eric Laurent8fc147b2018-07-22 19:13:55 -07003265status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003266{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003267 ALOGV("%s portId %d", __FUNCTION__, portId);
3268
3269 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3270 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003271 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003272 return BAD_VALUE;
3273 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003274 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003275 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003276 if (!client->active()) {
3277 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003278 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003279 }
Carter Hsue6139d52021-07-08 10:30:20 +08003280 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003281 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003282
Eric Laurent8f42ea12018-08-08 09:08:25 -07003283 inputDesc->stop();
3284 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003285 auto current_source = inputDesc->source();
3286 setInputDevice(input, getNewInputDevice(inputDesc),
3287 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003288 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003289 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003290 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003291 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003292 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3293 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003294 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003295 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003296
3297 // automatically disable the remote submix output when input is stopped if not
3298 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003299 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003300 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003301 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003302 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003303 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3304 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003305 }
3306 if (address != "") {
3307 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3308 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003309 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003310 }
3311 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003312 resetInputDevice(input);
3313
3314 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3315 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003316 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3317 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003318 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003319 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003320 }
3321 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003322 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003323 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003324}
3325
Eric Laurent8fc147b2018-07-22 19:13:55 -07003326void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003327{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003328 ALOGV("%s portId %d", __FUNCTION__, portId);
3329
3330 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3331 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003332 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003333 return;
3334 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003335 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003336 audio_io_handle_t input = inputDesc->mIoHandle;
3337
Eric Laurent8f42ea12018-08-08 09:08:25 -07003338 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003339
Andy Hung39efb7a2018-09-26 15:39:28 -07003340 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003341
3342 // If no more clients are present in this session, park effects to an orphan chain
3343 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3344 if (clientsOnSession.size() == 0) {
3345 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3346 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003347 if (inputDesc->getClientCount() > 0) {
3348 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003349 return;
3350 }
3351
Eric Laurent05b90f82014-08-27 15:32:29 -07003352 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003353 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003354 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003355}
3356
Eric Laurent8f42ea12018-08-08 09:08:25 -07003357void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003358{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003359 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003360
3361 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003362 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003363 }
3364}
3365
Eric Laurent8f42ea12018-08-08 09:08:25 -07003366void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3367{
3368 stopInput(portId);
3369 releaseInput(portId);
3370}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003371
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003372bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3373 if (input->clientsList().size() == 0
3374 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3375 return true;
3376 }
3377 for (const auto& client : input->clientsList()) {
3378 sp<DeviceDescriptor> device =
3379 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3380 client->session());
3381 if (!input->supportedDevices().contains(device)) {
3382 return true;
3383 }
3384 }
3385 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3386 return false;
3387}
3388
Eric Laurent0dd51852019-04-19 18:18:58 -07003389void AudioPolicyManager::checkCloseInputs() {
3390 // After connecting or disconnecting an input device, close input if:
3391 // - it has no client (was just opened to check profile) OR
3392 // - none of its supported devices are connected anymore OR
3393 // - one of its clients cannot be routed to one of its supported
3394 // devices anymore. Otherwise update device selection
3395 std::vector<audio_io_handle_t> inputsToClose;
3396 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003397 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003398 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003399 }
3400 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003401 for (const audio_io_handle_t handle : inputsToClose) {
3402 ALOGV("%s closing input %d", __func__, handle);
3403 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003404 }
Eric Laurentd4692962014-05-05 18:13:44 -07003405}
3406
Vlad Popa87e0e582024-05-20 18:49:20 -07003407status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3408 const char *address __unused,
3409 bool enabled,
3410 audio_stream_type_t streamToDriveAbs)
3411{
3412 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3413 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3414 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3415 toString(streamToDriveAbs).c_str());
3416 return BAD_VALUE;
3417 }
3418
3419 if (enabled) {
3420 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3421 } else {
3422 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3423 }
3424
3425 return NO_ERROR;
3426}
3427
François Gaffie251c7f02018-11-07 10:41:08 +01003428void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003429{
3430 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003431 if (indexMin < 0 || indexMax < 0) {
3432 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3433 return;
3434 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003435 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003436
3437 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003438 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3439 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003440 continue;
3441 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003442 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003443 }
Eric Laurente552edb2014-03-10 17:42:56 -07003444}
3445
Eric Laurente0720872014-03-11 09:30:41 -07003446status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003447 int index,
3448 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003449{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003450 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003451 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3452 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3453 return NO_ERROR;
3454 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303455 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3456 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003457 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003458}
3459
Eric Laurente0720872014-03-11 09:30:41 -07003460status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003461 int *index,
3462 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003463{
François Gaffiec005e562018-11-06 15:04:49 +01003464 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3465 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003466 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003467 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003468 deviceTypes = mEngine->getOutputDevicesForStream(
3469 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003470 }
jiabin9a3361e2019-10-01 09:38:30 -07003471 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003472}
3473
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003474status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003475 int index,
3476 audio_devices_t device)
3477{
3478 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003479 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3480 if (group == VOLUME_GROUP_NONE) {
3481 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003482 return BAD_VALUE;
3483 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003484 ALOGV("%s: group %d matching with %s index %d",
3485 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003486 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003487 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003488 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003489 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3490 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3491 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3492 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003493 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3494
3495 status = setVolumeCurveIndex(index, device, curves);
3496 if (status != NO_ERROR) {
3497 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3498 return status;
3499 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003500
jiabin9a3361e2019-10-01 09:38:30 -07003501 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003502 auto curCurvAttrs = curves.getAttributes();
3503 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3504 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003505 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003506 } else if (!curves.getStreamTypes().empty()) {
3507 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003508 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003509 } else {
3510 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3511 return BAD_VALUE;
3512 }
jiabin9a3361e2019-10-01 09:38:30 -07003513 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3514 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003515
François Gaffiecfe17322018-11-07 13:41:29 +01003516 // update volume on all outputs and streams matching the following:
3517 // - The requested stream (or a stream matching for volume control) is active on the output
3518 // - The device (or devices) selected by the engine for this stream includes
3519 // the requested device
3520 // - For non default requested device, currently selected device on the output is either the
3521 // requested device or one of the devices selected by the engine for this stream
3522 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3523 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003524 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003525 for (size_t i = 0; i < mOutputs.size(); i++) {
3526 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003527 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003528
jiabin9a3361e2019-10-01 09:38:30 -07003529 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3530 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003531 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003532
3533 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003534 continue;
3535 }
3536 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3537 curDevices.find(device) == curDevices.end()) {
3538 continue;
3539 }
3540 bool applyVolume = false;
3541 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3542 curSrcDevices.insert(device);
3543 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003544 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3545 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003546 } else {
3547 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3548 }
3549 if (!applyVolume) {
3550 continue; // next output
3551 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003552 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3553 // If a higher priority strategy is active, and the output is routed to a device with a
3554 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003555 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003556 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003557 // If the volume source is active with higher priority source, ensure at least Sw Muted
3558 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003559 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3560 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3561 false /*preferredDevice*/);
3562 if (activeClients.empty()) {
3563 continue;
3564 }
3565 bool isPreempted = false;
3566 bool isHigherPriority = productStrategy < strategy;
3567 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003568 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003569 ALOGV("%s: Strategy=%d (\nrequester:\n"
3570 " group %d, volumeGroup=%d attributes=%s)\n"
3571 " higher priority source active:\n"
3572 " volumeGroup=%d attributes=%s) \n"
3573 " on output %zu, bailing out", __func__, productStrategy,
3574 group, group, toString(attributes).c_str(),
3575 client->volumeSource(), toString(client->attributes()).c_str(), i);
3576 applyVolume = false;
3577 isPreempted = true;
3578 break;
3579 }
3580 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003581 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003582 applyVolume = true;
3583 }
3584 }
3585 if (isPreempted || applyVolume) {
3586 break;
3587 }
3588 }
3589 if (!applyVolume) {
3590 continue; // next output
3591 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003592 }
François Gaffieed91f582020-01-31 10:35:37 +01003593 //FIXME: workaround for truncated touch sounds
3594 // delayed volume change for system stream to be removed when the problem is
3595 // handled by system UI
3596 status_t volStatus = checkAndSetVolume(
3597 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003598 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003599 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3600 if (volStatus != NO_ERROR) {
3601 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003602 }
3603 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003604
3605 // update voice volume if the an active call route exists
3606 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3607 && (curSrcDevices.find(
3608 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3609 != curSrcDevices.end())) {
3610 bool isVoiceVolSrc;
3611 bool isBtScoVolSrc;
3612 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3613 isVoiceVolSrc, isBtScoVolSrc, __func__)
3614 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003615 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3616 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3617 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003618 }
3619 }
3620
François Gaffiecfe17322018-11-07 13:41:29 +01003621 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3622 return status;
3623}
3624
François Gaffieaaac0fd2018-11-22 17:56:39 +01003625status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003626 audio_devices_t device,
3627 IVolumeCurves &volumeCurves)
3628{
3629 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3630 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003631 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3632 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003633 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303634 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3635 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003636 return BAD_VALUE;
3637 }
3638 if (!audio_is_output_device(device)) {
3639 return BAD_VALUE;
3640 }
3641
3642 // Force max volume if stream cannot be muted
3643 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3644
François Gaffieaaac0fd2018-11-22 17:56:39 +01003645 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003646 volumeCurves.addCurrentVolumeIndex(device, index);
3647 return NO_ERROR;
3648}
3649
3650status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3651 int &index,
3652 audio_devices_t device)
3653{
3654 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3655 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003656 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003657 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003658 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003659 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003660 }
jiabin9a3361e2019-10-01 09:38:30 -07003661 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003662}
3663
3664status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3665 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003666 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003667{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003668 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003669 return BAD_VALUE;
3670 }
jiabin9a3361e2019-10-01 09:38:30 -07003671 index = curves.getVolumeIndex(deviceTypes);
3672 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003673 return NO_ERROR;
3674}
3675
3676status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3677 int &index)
3678{
3679 index = getVolumeCurves(attr).getVolumeIndexMin();
3680 return NO_ERROR;
3681}
3682
3683status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3684 int &index)
3685{
3686 index = getVolumeCurves(attr).getVolumeIndexMax();
3687 return NO_ERROR;
3688}
3689
Eric Laurent36829f92017-04-07 19:04:42 -07003690audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003691{
3692 // select one output among several suitable for global effects.
3693 // The priority is as follows:
3694 // 1: An offloaded output. If the effect ends up not being offloadable,
3695 // AudioFlinger will invalidate the track and the offloaded output
3696 // will be closed causing the effect to be moved to a PCM output.
3697 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003698 // 3: The primary output
3699 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003700
François Gaffiec005e562018-11-06 15:04:49 +01003701 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3702 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003703 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003704
Eric Laurent36829f92017-04-07 19:04:42 -07003705 if (outputs.size() == 0) {
3706 return AUDIO_IO_HANDLE_NONE;
3707 }
Eric Laurente552edb2014-03-10 17:42:56 -07003708
Eric Laurent36829f92017-04-07 19:04:42 -07003709 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3710 bool activeOnly = true;
3711
3712 while (output == AUDIO_IO_HANDLE_NONE) {
3713 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3714 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3715 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3716
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003717 for (audio_io_handle_t output : outputs) {
3718 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003719 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003720 continue;
3721 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003722 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3723 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003724 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003725 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003726 }
3727 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003728 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003729 }
3730 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003731 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003732 }
3733 }
3734 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3735 output = outputOffloaded;
3736 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3737 output = outputDeepBuffer;
3738 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3739 output = outputPrimary;
3740 } else {
3741 output = outputs[0];
3742 }
3743 activeOnly = false;
3744 }
3745
3746 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003747 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3748 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003749 mMusicEffectOutput = output;
3750 }
3751
3752 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003753 return output;
3754}
3755
Eric Laurent36829f92017-04-07 19:04:42 -07003756audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3757{
3758 return selectOutputForMusicEffects();
3759}
3760
Eric Laurente0720872014-03-11 09:30:41 -07003761status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003762 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003763 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003764 int session,
3765 int id)
3766{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003767 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003768 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003769 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003770 index = mInputs.indexOfKey(io);
3771 if (index < 0) {
3772 ALOGW("registerEffect() unknown io %d", io);
3773 return INVALID_OPERATION;
3774 }
Eric Laurente552edb2014-03-10 17:42:56 -07003775 }
3776 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003777 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3778 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3779 || strategy == PRODUCT_STRATEGY_NONE));
3780 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003781}
3782
Eric Laurentc241b0d2018-11-28 09:08:49 -08003783status_t AudioPolicyManager::unregisterEffect(int id)
3784{
3785 if (mEffects.getEffect(id) == nullptr) {
3786 return INVALID_OPERATION;
3787 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003788 if (mEffects.isEffectEnabled(id)) {
3789 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3790 setEffectEnabled(id, false);
3791 }
3792 return mEffects.unregisterEffect(id);
3793}
3794
3795status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3796{
3797 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3798 if (effect == nullptr) {
3799 return INVALID_OPERATION;
3800 }
3801
3802 status_t status = mEffects.setEffectEnabled(id, enabled);
3803 if (status == NO_ERROR) {
3804 mInputs.trackEffectEnabled(effect, enabled);
3805 }
3806 return status;
3807}
3808
Eric Laurent6c796322019-04-09 14:13:17 -07003809
3810status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3811{
3812 mEffects.moveEffects(ids, io);
3813 return NO_ERROR;
3814}
3815
Eric Laurentc75307b2015-03-17 15:29:32 -07003816bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3817{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003818 auto vs = toVolumeSource(stream, false);
3819 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003820}
3821
3822bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3823{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003824 auto vs = toVolumeSource(stream, false);
3825 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003826}
3827
Eric Laurente0720872014-03-11 09:30:41 -07003828bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003829{
3830 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003831 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003832 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003833 return true;
3834 }
3835 }
3836 return false;
3837}
3838
Eric Laurent275e8e92014-11-30 15:14:47 -08003839// Register a list of custom mixes with their attributes and format.
3840// When a mix is registered, corresponding input and output profiles are
3841// added to the remote submix hw module. The profile contains only the
3842// parameters (sampling rate, format...) specified by the mix.
3843// The corresponding input remote submix device is also connected.
3844//
3845// When a remote submix device is connected, the address is checked to select the
3846// appropriate profile and the corresponding input or output stream is opened.
3847//
3848// When capture starts, getInputForAttr() will:
3849// - 1 look for a mix matching the address passed in attribtutes tags if any
3850// - 2 if none found, getDeviceForInputSource() will:
3851// - 2.1 look for a mix matching the attributes source
3852// - 2.2 if none found, default to device selection by policy rules
3853// At this time, the corresponding output remote submix device is also connected
3854// and active playback use cases can be transferred to this mix if needed when reconnecting
3855// after AudioTracks are invalidated
3856//
3857// When playback starts, getOutputForAttr() will:
3858// - 1 look for a mix matching the address passed in attribtutes tags if any
3859// - 2 if none found, look for a mix matching the attributes usage
3860// - 3 if none found, default to device and output selection by policy rules.
3861
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003862status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003863{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003864 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3865 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003866 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003867 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003868 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003869 // examine each mix's route type
3870 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003871 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003872 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3873 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3874 ALOGE("Unsupported Policy Mix %zu of %zu: "
3875 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3876 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003877 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003878 break;
3879 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003880 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3881 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003882 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003883 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3884 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003885 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003886 rSubmixModule = mHwModules.getModuleFromName(
3887 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3888 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003889 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003890 i);
3891 res = INVALID_OPERATION;
3892 break;
3893 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003894 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003895
Eric Laurent97ac8712018-07-27 18:59:02 -07003896 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003897 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003898 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003899 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003900 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3901 } else {
3902 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3903 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003904 }
François Gaffie036e1e92015-03-19 10:16:24 +01003905
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003906 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003907 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003908 res = INVALID_OPERATION;
3909 break;
3910 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003911 audio_config_t outputConfig = mix.mFormat;
3912 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003913 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3914 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003915 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3916 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003917 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003918 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3919 audio_is_linear_pcm(outputConfig.format)
3920 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003921 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003922 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3923 audio_is_linear_pcm(inputConfig.format)
3924 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003925
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003926 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003927 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003928 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003929 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003930 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003931 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003932 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003933 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3934 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003935 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003936 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003937 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003938
3939 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3940 mix.mDeviceType, mix.mDeviceAddress,
3941 String8(), AUDIO_FORMAT_DEFAULT);
3942 if (device == nullptr) {
3943 res = INVALID_OPERATION;
3944 break;
3945 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003946
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003947 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003948 // First try to find an already opened output supporting the device
3949 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003950 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003951
Eric Laurentc529cf62020-04-17 18:19:10 -07003952 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003953 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003954 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003955 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003956 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003957 } else {
3958 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003959 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003960 }
3961 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003962 // If no output found, try to find a direct output profile supporting the device
3963 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3964 sp<HwModule> module = mHwModules[i];
3965 for (size_t j = 0;
3966 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3967 j++) {
3968 sp<IOProfile> profile = module->getOutputProfiles()[j];
3969 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3970 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3971 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003972 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003973 res = INVALID_OPERATION;
3974 } else {
3975 foundOutput = true;
3976 }
3977 }
3978 }
3979 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003980 if (res != NO_ERROR) {
3981 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003982 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003983 res = INVALID_OPERATION;
3984 break;
3985 } else if (!foundOutput) {
3986 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003987 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003988 res = INVALID_OPERATION;
3989 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003990 } else {
3991 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003992 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003993 }
Eric Laurentc722f302014-12-10 11:21:49 -08003994 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003995 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003996 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003997 if (audio_flags::audio_mix_ownership()) {
3998 // Only unregister mixes that were actually registered to not accidentally unregister
3999 // mixes that already existed previously.
4000 unregisterPolicyMixes(registeredMixes);
4001 registeredMixes.clear();
4002 } else {
4003 unregisterPolicyMixes(mixes);
4004 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004005 } else if (checkOutputs) {
4006 checkForDeviceAndOutputChanges();
4007 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004008 }
4009 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004010}
4011
4012status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4013{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004014 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004015 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004016 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004017 sp<HwModule> rSubmixModule;
4018 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004019 for (const auto& mix : mixes) {
4020 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004021
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004022 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004023 rSubmixModule = mHwModules.getModuleFromName(
4024 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4025 if (rSubmixModule == 0) {
4026 res = INVALID_OPERATION;
4027 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004028 }
4029 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004030
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004031 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004032
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004033 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004034 res = INVALID_OPERATION;
4035 continue;
4036 }
4037
Marvin Ramin0783e202024-03-05 12:45:50 +01004038 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004039 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004040 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4041 status_t currentRes =
4042 setDeviceConnectionStateInt(device,
4043 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4044 address.c_str(),
4045 "remote-submix",
4046 AUDIO_FORMAT_DEFAULT);
4047 if (!audio_flags::audio_mix_ownership()) {
4048 res = currentRes;
4049 }
4050 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004051 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004052 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004053 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004054 }
4055 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004056 }
jiabin5740f082019-08-19 15:08:30 -07004057 rSubmixModule->removeOutputProfile(address.c_str());
4058 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004059
Kevin Rocard153f92d2018-12-18 18:33:28 -08004060 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004061 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004062 res = INVALID_OPERATION;
4063 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004064 } else {
4065 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004066 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004067 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004068 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004069
4070 if (res == NO_ERROR && checkOutputs) {
4071 checkForDeviceAndOutputChanges();
4072 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004073 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004074 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004075}
4076
Marvin Raminbdefaf02023-11-01 09:10:32 +01004077status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4078 if (!audio_flags::audio_mix_test_api()) {
4079 return INVALID_OPERATION;
4080 }
4081
4082 _aidl_return.clear();
4083 _aidl_return.reserve(mPolicyMixes.size());
4084 for (const auto &policyMix: mPolicyMixes) {
4085 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4086 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4087 policyMix->mCbFlags);
4088 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004089 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004090 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004091 }
4092
Vlad Popaa5d73f32024-03-08 16:05:38 -08004093 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004094 return OK;
4095}
4096
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004097status_t AudioPolicyManager::updatePolicyMix(
4098 const AudioMix& mix,
4099 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4100 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4101 if (res == NO_ERROR) {
4102 checkForDeviceAndOutputChanges();
4103 updateCallAndOutputRouting();
4104 }
4105 return res;
4106}
4107
Mikhail Naganov100f0122018-11-29 11:22:16 -08004108void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4109{
4110 size_t i = 0;
4111 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4112 for (const auto& fmt : mManualSurroundFormats) {
4113 if (i++ != 0) dst->append(", ");
4114 std::string sfmt;
4115 FormatConverter::toString(fmt, sfmt);
4116 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4117 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4118 }
4119}
4120
Eric Laurentc529cf62020-04-17 18:19:10 -07004121// Returns true if all devices types match the predicate and are supported by one HW module
4122bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004123 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004124 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004125 const char *context,
4126 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004127 for (size_t i = 0; i < devices.size(); i++) {
4128 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004129 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004130 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004131 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004132 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004133 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004134 return false;
4135 }
4136 }
4137 return true;
4138}
4139
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004140void AudioPolicyManager::changeOutputDevicesMuteState(
4141 const AudioDeviceTypeAddrVector& devices) {
4142 ALOGVV("%s() num devices %zu", __func__, devices.size());
4143
4144 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4145 getSoftwareOutputsForDevices(devices);
4146
4147 for (size_t i = 0; i < outputs.size(); i++) {
4148 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4149 DeviceVector prevDevices = outputDesc->devices();
4150 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4151 }
4152}
4153
4154std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4155 const AudioDeviceTypeAddrVector& devices) const
4156{
4157 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4158 DeviceVector deviceDescriptors;
4159 for (size_t j = 0; j < devices.size(); j++) {
4160 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4161 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4162 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4163 ALOGE("%s: device type %#x address %s not supported or not an output device",
4164 __func__, devices[j].mType, devices[j].getAddress());
4165 continue;
4166 }
4167 deviceDescriptors.add(desc);
4168 }
4169 for (size_t i = 0; i < mOutputs.size(); i++) {
4170 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4171 continue;
4172 }
4173 outputs.push_back(mOutputs.valueAt(i));
4174 }
4175 return outputs;
4176}
4177
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004178status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004179 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004180 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004181 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4182 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004183 }
4184 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004185 if (res != NO_ERROR) {
4186 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4187 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004188 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004189
4190 checkForDeviceAndOutputChanges();
4191 updateCallAndOutputRouting();
4192
4193 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004194}
4195
4196status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4197 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004198 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4199 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004200 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004201 __FUNCTION__, uid);
4202 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004203 }
4204
Eric Laurentc529cf62020-04-17 18:19:10 -07004205 checkForDeviceAndOutputChanges();
4206 updateCallAndOutputRouting();
4207
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004208 return res;
4209}
4210
Eric Laurent2517af32020-11-25 15:31:27 +01004211
jiabin0a488932020-08-07 17:32:40 -07004212status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4213 device_role_t role,
4214 const AudioDeviceTypeAddrVector &devices) {
4215 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4216 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004217
Eric Laurentc529cf62020-04-17 18:19:10 -07004218 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004219 return BAD_VALUE;
4220 }
jiabin0a488932020-08-07 17:32:40 -07004221 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004222 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004223 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4224 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004225 return status;
4226 }
4227
4228 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004229
4230 bool forceVolumeReeval = false;
4231 // FIXME: workaround for truncated touch sounds
4232 // to be removed when the problem is handled by system UI
4233 uint32_t delayMs = 0;
4234 if (strategy == mCommunnicationStrategy) {
4235 forceVolumeReeval = true;
4236 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4237 updateInputRouting();
4238 }
4239 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004240
4241 return NO_ERROR;
4242}
4243
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004244void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4245 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004246{
4247 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004248 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004249 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004250 // Only apply special touch sound delay once
4251 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004252 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004253 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004254 for (size_t i = 0; i < mOutputs.size(); i++) {
4255 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4256 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004257 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4258 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004259 // As done in setDeviceConnectionState, we could also fix default device issue by
4260 // preventing the force re-routing in case of default dev that distinguishes on address.
4261 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004262 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004263 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004264 // If the device is using preferred mixer attributes, the output need to reopen
4265 // with default configuration when the new selected devices are different from
4266 // current routing devices.
4267 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4268 continue;
4269 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304270
4271 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4272 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004273 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004274 // Only apply special touch sound delay once
4275 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004276 }
4277 if (forceVolumeReeval && !newDevices.isEmpty()) {
4278 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4279 }
4280 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004281 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004282 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004283}
4284
Eric Laurent2517af32020-11-25 15:31:27 +01004285void AudioPolicyManager::updateInputRouting() {
4286 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304287 // Skip for hotword recording as the input device switch
4288 // is handled within sound trigger HAL
4289 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4290 continue;
4291 }
Eric Laurent2517af32020-11-25 15:31:27 +01004292 auto newDevice = getNewInputDevice(activeDesc);
4293 // Force new input selection if the new device can not be reached via current input
4294 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4295 setInputDevice(activeDesc->mIoHandle, newDevice);
4296 } else {
4297 closeInput(activeDesc->mIoHandle);
4298 }
4299 }
4300}
4301
Paul Wang5d7cdb52022-11-22 09:45:06 +00004302status_t
4303AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4304 device_role_t role,
4305 const AudioDeviceTypeAddrVector &devices) {
4306 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4307 dumpAudioDeviceTypeAddrVector(devices).c_str());
4308
Eric Laurent78fedbf2023-03-09 14:40:44 +01004309 if (!areAllDevicesSupported(
4310 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004311 return BAD_VALUE;
4312 }
4313 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4314 if (status != NO_ERROR) {
4315 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4316 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4317 return status;
4318 }
4319
4320 checkForDeviceAndOutputChanges();
4321
4322 bool forceVolumeReeval = false;
4323 // TODO(b/263479999): workaround for truncated touch sounds
4324 // to be removed when the problem is handled by system UI
4325 uint32_t delayMs = 0;
4326 if (strategy == mCommunnicationStrategy) {
4327 forceVolumeReeval = true;
4328 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4329 updateInputRouting();
4330 }
4331 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4332
4333 return NO_ERROR;
4334}
4335
4336status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4337 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004338{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004339 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004340
Paul Wang5d7cdb52022-11-22 09:45:06 +00004341 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004342 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004343 ALOGW_IF(status != NAME_NOT_FOUND,
4344 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004345 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004346 return status;
4347 }
4348
4349 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004350
4351 bool forceVolumeReeval = false;
4352 // FIXME: workaround for truncated touch sounds
4353 // to be removed when the problem is handled by system UI
4354 uint32_t delayMs = 0;
4355 if (strategy == mCommunnicationStrategy) {
4356 forceVolumeReeval = true;
4357 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4358 updateInputRouting();
4359 }
4360 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004361
4362 return NO_ERROR;
4363}
4364
jiabin0a488932020-08-07 17:32:40 -07004365status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4366 device_role_t role,
4367 AudioDeviceTypeAddrVector &devices) {
4368 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004369}
4370
Jiabin Huang3b98d322020-09-03 17:54:16 +00004371status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4372 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4373 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4374 dumpAudioDeviceTypeAddrVector(devices).c_str());
4375
Mikhail Naganov55773032020-10-01 15:08:13 -07004376 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004377 return BAD_VALUE;
4378 }
4379 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4380 ALOGW_IF(status != NO_ERROR,
4381 "Engine could not set preferred devices %s for audio source %d role %d",
4382 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4383
4384 return status;
4385}
4386
4387status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4388 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4389 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4390 dumpAudioDeviceTypeAddrVector(devices).c_str());
4391
Mikhail Naganov55773032020-10-01 15:08:13 -07004392 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004393 return BAD_VALUE;
4394 }
4395 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4396 ALOGW_IF(status != NO_ERROR,
4397 "Engine could not add preferred devices %s for audio source %d role %d",
4398 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4399
Eric Laurent2517af32020-11-25 15:31:27 +01004400 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004401 return status;
4402}
4403
4404status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4405 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4406{
4407 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4408 dumpAudioDeviceTypeAddrVector(devices).c_str());
4409
Eric Laurent78fedbf2023-03-09 14:40:44 +01004410 if (!areAllDevicesSupported(
4411 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004412 return BAD_VALUE;
4413 }
4414
4415 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4416 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004417 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004418 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004419 if (status == NO_ERROR) {
4420 updateInputRouting();
4421 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004422 return status;
4423}
4424
4425status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4426 device_role_t role) {
4427 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4428
4429 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004430 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004431 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004432 if (status == NO_ERROR) {
4433 updateInputRouting();
4434 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004435 return status;
4436}
4437
4438status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4439 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4440 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4441}
4442
Oscar Azucena90e77632019-11-27 17:12:28 -08004443status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004444 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004445 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004446 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4447 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004448 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004449 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4450 if (status != NO_ERROR) {
4451 ALOGE("%s() could not set device affinity for userId %d",
4452 __FUNCTION__, userId);
4453 return status;
4454 }
4455
4456 // reevaluate outputs for all devices
4457 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004458 changeOutputDevicesMuteState(devices);
4459 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4460 true /* skipDelays */);
4461 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004462
4463 return NO_ERROR;
4464}
4465
4466status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004467 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004468 AudioDeviceTypeAddrVector devices;
4469 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004470 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4471 if (status != NO_ERROR) {
4472 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4473 __FUNCTION__, userId);
4474 return status;
4475 }
4476
4477 // reevaluate outputs for all devices
4478 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004479 changeOutputDevicesMuteState(devices);
4480 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4481 true /* skipDelays */);
4482 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004483
4484 return NO_ERROR;
4485}
4486
Andy Hungc29d82b2018-10-05 12:23:17 -07004487void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004488{
Andy Hungc29d82b2018-10-05 12:23:17 -07004489 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004490 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004491 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004492 std::string stateLiteral;
4493 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004494 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004495 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4496 "communications", "media", "record", "dock", "system",
4497 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4498 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4499 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004500 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4501 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4502 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4503 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4504 dst->append(" (MANUAL: ");
4505 dumpManualSurroundFormats(dst);
4506 dst->append(")");
4507 }
4508 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004509 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004510 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4511 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004512 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004513 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004514
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004515 dst->append("\n");
4516 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4517 dst->append("\n");
4518 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004519 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004520 mOutputs.dump(dst);
4521 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004522 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004523 mAudioPatches.dump(dst);
4524 mPolicyMixes.dump(dst);
4525 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004526
Kevin Rocardb99cc752019-03-21 20:52:24 -07004527 dst->appendFormat(" AllowedCapturePolicies:\n");
4528 for (auto& policy : mAllowedCapturePolicies) {
4529 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4530 }
4531
jiabina84c3d32022-12-02 18:59:55 +00004532 dst->appendFormat(" Preferred mixer audio configuration:\n");
4533 for (const auto it : mPreferredMixerAttrInfos) {
4534 dst->appendFormat(" - device port id: %d\n", it.first);
4535 for (const auto preferredMixerInfoIt : it.second) {
4536 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4537 preferredMixerInfoIt.second->dump(dst);
4538 }
4539 }
4540
François Gaffiec005e562018-11-06 15:04:49 +01004541 dst->appendFormat("\nPolicy Engine dump:\n");
4542 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004543
4544 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4545 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4546 dst->appendFormat(" - device type: %s, driving stream %d\n",
4547 dumpDeviceTypes({it.first}).c_str(),
4548 mEngine->getVolumeGroupForAttributes(it.second));
4549 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004550}
4551
4552status_t AudioPolicyManager::dump(int fd)
4553{
4554 String8 result;
4555 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004556 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004557 return NO_ERROR;
4558}
4559
Kevin Rocardb99cc752019-03-21 20:52:24 -07004560status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4561{
4562 mAllowedCapturePolicies[uid] = capturePolicy;
4563 return NO_ERROR;
4564}
4565
Eric Laurente552edb2014-03-10 17:42:56 -07004566// This function checks for the parameters which can be offloaded.
4567// This can be enhanced depending on the capability of the DSP and policy
4568// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004569audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004570{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004571 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004572 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004573 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004574 offloadInfo.format,
4575 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4576 offloadInfo.has_video);
4577
jiabin2b9d5a12021-12-10 01:06:29 +00004578 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004579 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004580 }
4581
4582 // See if there is a profile to support this.
4583 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004584 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004585 offloadInfo.sample_rate,
4586 offloadInfo.format,
4587 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004588 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4589 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004590 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4591 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4592 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004593 if (profile == nullptr) {
4594 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4595 }
4596 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4597 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4598 }
4599 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004600}
4601
Michael Chana94fbb22018-04-24 14:31:19 +10004602bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4603 const audio_attributes_t& attributes) {
4604 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004605 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004606 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4607 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004608 config.sample_rate,
4609 config.format,
4610 config.channel_mask,
4611 output_flags,
4612 true /* directOnly */);
4613 ALOGV("%s() profile %sfound with name: %s, "
4614 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4615 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004616 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004617 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004618
4619 // also try the MSD module if compatible profile not found
4620 if (profile == nullptr) {
4621 profile = getMsdProfileForOutput(outputDevices,
4622 config.sample_rate,
4623 config.format,
4624 config.channel_mask,
4625 output_flags,
4626 true /* directOnly */);
4627 ALOGV("%s() MSD profile %sfound with name: %s, "
4628 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4629 __FUNCTION__, profile != 0 ? "" : "NOT ",
4630 (profile != 0 ? profile->getTagName().c_str() : "null"),
4631 config.sample_rate, config.format, config.channel_mask, output_flags);
4632 }
4633 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004634}
4635
jiabin2b9d5a12021-12-10 01:06:29 +00004636bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4637 bool durationIgnored) {
4638 if (mMasterMono) {
4639 return false; // no offloading if mono is set.
4640 }
4641
4642 // Check if offload has been disabled
4643 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4644 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4645 return false;
4646 }
4647
4648 // Check if stream type is music, then only allow offload as of now.
4649 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4650 {
4651 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4652 return false;
4653 }
4654
4655 //TODO: enable audio offloading with video when ready
4656 const bool allowOffloadWithVideo =
4657 property_get_bool("audio.offload.video", false /* default_value */);
4658 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4659 ALOGV("%s: has_video == true, returning false", __func__);
4660 return false;
4661 }
4662
4663 //If duration is less than minimum value defined in property, return false
4664 const int min_duration_secs = property_get_int32(
4665 "audio.offload.min.duration.secs", -1 /* default_value */);
4666 if (!durationIgnored) {
4667 if (min_duration_secs >= 0) {
4668 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4669 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4670 __func__, min_duration_secs);
4671 return false;
4672 }
4673 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4674 ALOGV("%s: Offload denied by duration < default min(=%u)",
4675 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4676 return false;
4677 }
4678 }
4679
4680 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4681 // creating an offloaded track and tearing it down immediately after start when audioflinger
4682 // detects there is an active non offloadable effect.
4683 // FIXME: We should check the audio session here but we do not have it in this context.
4684 // This may prevent offloading in rare situations where effects are left active by apps
4685 // in the background.
4686 if (mEffects.isNonOffloadableEffectEnabled()) {
4687 return false;
4688 }
4689
4690 return true;
4691}
4692
4693audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4694 const audio_config_t *config) {
4695 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4696 offloadInfo.format = config->format;
4697 offloadInfo.sample_rate = config->sample_rate;
4698 offloadInfo.channel_mask = config->channel_mask;
4699 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4700 offloadInfo.has_video = false;
4701 offloadInfo.is_streaming = false;
4702 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4703
4704 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4705 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4706 audio_flags_to_audio_output_flags(attr->flags, &flags);
4707 // only retain flags that will drive compressed offload or passthrough
4708 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4709 if (offloadPossible) {
4710 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4711 }
4712 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4713
Dorin Drimusfae3c642022-03-17 18:36:30 +01004714 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004715 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004716 DeviceVector outputDevices = engineOutputDevices;
4717 // the MSD module checks for different conditions and output devices
4718 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4719 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4720 continue;
4721 }
4722 outputDevices = getMsdAudioOutDevices();
4723 }
jiabin2b9d5a12021-12-10 01:06:29 +00004724 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004725 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004726 config->sample_rate, nullptr /*updatedSamplingRate*/,
4727 config->format, nullptr /*updatedFormat*/,
4728 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004729 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004730 continue;
4731 }
4732 // reject profiles not corresponding to a device currently available
4733 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4734 continue;
4735 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004736 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4737 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004738 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004739 != AUDIO_DIRECT_NOT_SUPPORTED) {
4740 // Already reports offload gapless supported. No need to report offload support.
4741 continue;
4742 }
4743 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4744 != AUDIO_OUTPUT_FLAG_NONE) {
4745 // If offload gapless is reported, no need to report offload support.
4746 directMode = (audio_direct_mode_t) ((directMode &
4747 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4748 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4749 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004750 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004751 }
4752 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004753 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004754 }
4755 }
4756 }
4757 return directMode;
4758}
4759
Dorin Drimusf2196d82022-01-03 12:11:18 +01004760status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4761 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004762 if (mEffects.isNonOffloadableEffectEnabled()) {
4763 return OK;
4764 }
jiabinf1c73972022-04-14 16:28:52 -07004765 DeviceVector devices;
4766 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004767 if (status != OK) {
4768 return status;
4769 }
4770 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4771 if (devices.empty()) {
4772 return OK; // no output devices for the attributes
4773 }
jiabinf1c73972022-04-14 16:28:52 -07004774 return getProfilesForDevices(devices, audioProfilesVector,
4775 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004776}
4777
jiabina84c3d32022-12-02 18:59:55 +00004778status_t AudioPolicyManager::getSupportedMixerAttributes(
4779 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4780 ALOGV("%s, portId=%d", __func__, portId);
4781 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4782 if (deviceDescriptor == nullptr) {
4783 ALOGE("%s the requested device is currently unavailable", __func__);
4784 return BAD_VALUE;
4785 }
jiabin96daffc2023-05-11 17:51:55 +00004786 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4787 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4788 deviceDescriptor->type());
4789 return BAD_VALUE;
4790 }
jiabina84c3d32022-12-02 18:59:55 +00004791 for (const auto& hwModule : mHwModules) {
4792 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4793 if (curProfile->supportsDevice(deviceDescriptor)) {
4794 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4795 }
4796 }
4797 }
4798 return NO_ERROR;
4799}
4800
4801status_t AudioPolicyManager::setPreferredMixerAttributes(
4802 const audio_attributes_t *attr,
4803 audio_port_handle_t portId,
4804 uid_t uid,
4805 const audio_mixer_attributes_t *mixerAttributes) {
4806 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4807 "mixerBehavior=%d}, uid=%d, portId=%u",
4808 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4809 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4810 mixerAttributes->mixer_behavior, uid, portId);
4811 if (attr->usage != AUDIO_USAGE_MEDIA) {
4812 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4813 return BAD_VALUE;
4814 }
4815 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4816 if (deviceDescriptor == nullptr) {
4817 ALOGE("%s the requested device is currently unavailable", __func__);
4818 return BAD_VALUE;
4819 }
4820 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4821 ALOGE("%s(%d), type=%d, is not a usb output device",
4822 __func__, portId, deviceDescriptor->type());
4823 return BAD_VALUE;
4824 }
4825
4826 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4827 audio_flags_to_audio_output_flags(attr->flags, &flags);
4828 flags = (audio_output_flags_t) (flags |
4829 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4830 sp<IOProfile> profile = nullptr;
4831 DeviceVector devices(deviceDescriptor);
4832 for (const auto& hwModule : mHwModules) {
4833 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4834 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004835 && curProfile->getCompatibilityScore(
4836 devices,
4837 mixerAttributes->config.sample_rate,
4838 nullptr /*updatedSamplingRate*/,
4839 mixerAttributes->config.format,
4840 nullptr /*updatedFormat*/,
4841 mixerAttributes->config.channel_mask,
4842 nullptr /*updatedChannelMask*/,
4843 flags,
4844 false /*exactMatchRequiredForInputFlags*/)
4845 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004846 profile = curProfile;
4847 break;
4848 }
4849 }
4850 }
4851 if (profile == nullptr) {
4852 ALOGE("%s, there is no compatible profile found", __func__);
4853 return BAD_VALUE;
4854 }
4855
4856 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4857 sp<PreferredMixerAttributesInfo>::make(
4858 uid, portId, profile, flags, *mixerAttributes);
4859 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4860 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4861
4862 // If 1) there is any client from the preferred mixer configuration owner that is currently
4863 // active and matches the strategy and 2) current output is on the preferred device and the
4864 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4865 // configuration.
4866 std::vector<audio_io_handle_t> outputsToReopen;
4867 for (size_t i = 0; i < mOutputs.size(); i++) {
4868 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004869 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4870 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004871 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004872 } else {
4873 for (const auto &client: output->getActiveClients()) {
4874 if (client->uid() == uid && client->strategy() == strategy) {
4875 client->setIsInvalid();
4876 outputsToReopen.push_back(output->mIoHandle);
4877 }
jiabina84c3d32022-12-02 18:59:55 +00004878 }
4879 }
4880 }
4881 }
4882 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4883 config.sample_rate = mixerAttributes->config.sample_rate;
4884 config.channel_mask = mixerAttributes->config.channel_mask;
4885 config.format = mixerAttributes->config.format;
4886 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004887 sp<SwAudioOutputDescriptor> desc =
4888 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4889 if (desc == nullptr) {
4890 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4891 continue;
4892 }
jiabin220eea12024-05-17 17:55:20 +00004893 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004894 }
4895
4896 return NO_ERROR;
4897}
4898
4899sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004900 audio_port_handle_t devicePortId,
4901 product_strategy_t strategy,
4902 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004903 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4904 if (it == mPreferredMixerAttrInfos.end()) {
4905 return nullptr;
4906 }
jiabind9a58d32023-06-01 17:57:30 +00004907 if (activeBitPerfectPreferred) {
4908 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004909 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004910 return info;
4911 }
4912 }
jiabina84c3d32022-12-02 18:59:55 +00004913 }
jiabind9a58d32023-06-01 17:57:30 +00004914 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4915 return strategyMatchedMixerAttrInfoIt == it->second.end()
4916 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004917}
4918
4919status_t AudioPolicyManager::getPreferredMixerAttributes(
4920 const audio_attributes_t *attr,
4921 audio_port_handle_t portId,
4922 audio_mixer_attributes_t* mixerAttributes) {
4923 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4924 portId, mEngine->getProductStrategyForAttributes(*attr));
4925 if (info == nullptr) {
4926 return NAME_NOT_FOUND;
4927 }
4928 *mixerAttributes = info->getMixerAttributes();
4929 return NO_ERROR;
4930}
4931
4932status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4933 audio_port_handle_t portId,
4934 uid_t uid) {
4935 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4936 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4937 if (preferredMixerAttrInfo == nullptr) {
4938 return NAME_NOT_FOUND;
4939 }
4940 if (preferredMixerAttrInfo->getUid() != uid) {
4941 ALOGE("%s, requested uid=%d, owned uid=%d",
4942 __func__, uid, preferredMixerAttrInfo->getUid());
4943 return PERMISSION_DENIED;
4944 }
4945 mPreferredMixerAttrInfos[portId].erase(strategy);
4946 if (mPreferredMixerAttrInfos[portId].empty()) {
4947 mPreferredMixerAttrInfos.erase(portId);
4948 }
4949
4950 // Reconfig existing output
4951 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4952 for (size_t i = 0; i < mOutputs.size(); i++) {
4953 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4954 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4955 }
4956 }
4957 for (const auto output : potentialOutputsToReopen) {
4958 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4959 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4960 preferredMixerAttrInfo->getFlags())) {
4961 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4962 }
4963 }
4964 return NO_ERROR;
4965}
4966
Eric Laurent6a94d692014-05-20 11:18:06 -07004967status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4968 audio_port_type_t type,
4969 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004970 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 unsigned int *generation)
4972{
jiabin19cdba52020-11-24 11:28:58 -08004973 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4974 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004975 return BAD_VALUE;
4976 }
4977 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004978 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004979 *num_ports = 0;
4980 }
4981
4982 size_t portsWritten = 0;
4983 size_t portsMax = *num_ports;
4984 *num_ports = 0;
4985 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004986 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4987 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004989 for (const auto& dev : mAvailableOutputDevices) {
4990 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004991 continue;
4992 }
4993 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004994 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004995 }
4996 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 }
4999 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005000 for (const auto& dev : mAvailableInputDevices) {
5001 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005002 continue;
5003 }
5004 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005005 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005006 }
5007 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 }
5010 }
5011 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5012 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5013 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5014 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5015 }
5016 *num_ports += mInputs.size();
5017 }
5018 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005019 size_t numOutputs = 0;
5020 for (size_t i = 0; i < mOutputs.size(); i++) {
5021 if (!mOutputs[i]->isDuplicated()) {
5022 numOutputs++;
5023 if (portsWritten < portsMax) {
5024 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5025 }
5026 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 }
Eric Laurent84c70242014-06-23 08:46:27 -07005028 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005029 }
5030 }
jiabina84c3d32022-12-02 18:59:55 +00005031
Eric Laurent6a94d692014-05-20 11:18:06 -07005032 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005033 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005034 return NO_ERROR;
5035}
5036
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005037status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5038 std::vector<media::AudioPortFw>* _aidl_return) {
5039 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5040 audio_port_v7 port;
5041 dev->toAudioPort(&port);
5042 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5043 _aidl_return->push_back(std::move(aidlPort));
5044 return OK;
5045 };
5046
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005047 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005048 for (const auto& dev : module->getDeclaredDevices()) {
5049 if (role == media::AudioPortRole::NONE ||
5050 ((role == media::AudioPortRole::SOURCE)
5051 == audio_is_input_device(dev->type()))) {
5052 RETURN_STATUS_IF_ERROR(pushPort(dev));
5053 }
5054 }
5055 }
5056 return OK;
5057}
5058
jiabin19cdba52020-11-24 11:28:58 -08005059status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005060{
Eric Laurent99fcae42018-05-17 16:59:18 -07005061 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5062 return BAD_VALUE;
5063 }
5064 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5065 if (dev != 0) {
5066 dev->toAudioPort(port);
5067 return NO_ERROR;
5068 }
5069 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5070 if (dev != 0) {
5071 dev->toAudioPort(port);
5072 return NO_ERROR;
5073 }
5074 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5075 if (out != 0) {
5076 out->toAudioPort(port);
5077 return NO_ERROR;
5078 }
5079 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5080 if (in != 0) {
5081 in->toAudioPort(port);
5082 return NO_ERROR;
5083 }
5084 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005085}
5086
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005087status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5088 audio_patch_handle_t *handle,
5089 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005090{
François Gaffieafd4cea2019-11-18 15:50:22 +01005091 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005092 if (handle == NULL || patch == NULL) {
5093 return BAD_VALUE;
5094 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005095 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005096 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005097 return BAD_VALUE;
5098 }
5099 // only one source per audio patch supported for now
5100 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005101 return INVALID_OPERATION;
5102 }
Eric Laurent874c42872014-08-08 15:13:39 -07005103 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005104 return INVALID_OPERATION;
5105 }
Eric Laurent874c42872014-08-08 15:13:39 -07005106 for (size_t i = 0; i < patch->num_sinks; i++) {
5107 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5108 return INVALID_OPERATION;
5109 }
5110 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005111
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005112 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5113 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5114 if (srcDevice == nullptr || sinkDevice == nullptr) {
5115 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5116 return BAD_VALUE;
5117 }
5118 ALOGV("%s between source %s and sink %s", __func__,
5119 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5120 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5121 // Default attributes, default volume priority, not to infer with non raw audio patches.
5122 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5123 const struct audio_port_config *source = &patch->sources[0];
5124 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005125 new SourceClientDescriptor(
5126 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5127 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005128 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005129 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005130
5131 status_t status =
5132 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5133
5134 if (status != NO_ERROR) {
5135 return INVALID_OPERATION;
5136 }
5137 mAudioSources.add(portId, sourceDesc);
5138 return NO_ERROR;
5139}
5140
5141status_t AudioPolicyManager::connectAudioSourceToSink(
5142 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5143 const struct audio_patch *patch,
5144 audio_patch_handle_t &handle,
5145 uid_t uid, uint32_t delayMs)
5146{
5147 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5148 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5149 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5150 return INVALID_OPERATION;
5151 }
5152 sourceDesc->connect(handle, sinkDevice);
5153 if (isMsdPatch(handle)) {
5154 return NO_ERROR;
5155 }
5156 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5157 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5158 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5159 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5160 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5161 goto FailurePatchAdded;
5162 }
5163 status = swOutput->start();
5164 if (status != NO_ERROR) {
5165 goto FailureSourceAdded;
5166 }
5167 swOutput->addClient(sourceDesc);
5168 status = startSource(swOutput, sourceDesc, &delayMs);
5169 if (status != NO_ERROR) {
5170 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5171 goto FailureSourceActive;
5172 }
5173 if (delayMs != 0) {
5174 usleep(delayMs * 1000);
5175 }
5176 return NO_ERROR;
5177
5178FailureSourceActive:
5179 swOutput->stop();
5180 releaseOutput(sourceDesc->portId());
5181FailureSourceAdded:
5182 sourceDesc->setSwOutput(nullptr);
5183FailurePatchAdded:
5184 releaseAudioPatchInternal(handle);
5185 return INVALID_OPERATION;
5186}
5187
5188status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5189 audio_patch_handle_t *handle,
5190 uid_t uid, uint32_t delayMs,
5191 const sp<SourceClientDescriptor>& sourceDesc)
5192{
5193 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005194 sp<AudioPatch> patchDesc;
5195 ssize_t index = mAudioPatches.indexOfKey(*handle);
5196
François Gaffieafd4cea2019-11-18 15:50:22 +01005197 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5198 patch->sources[0].role,
5199 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005200#if LOG_NDEBUG == 0
5201 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005202 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5203 patch->sinks[i].role,
5204 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005205 }
5206#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005207
5208 if (index >= 0) {
5209 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005210 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5211 __func__, mUidCached, patchDesc->getUid(), uid);
5212 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 return INVALID_OPERATION;
5214 }
5215 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005216 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 }
5218
5219 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005220 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005221 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005222 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005223 return BAD_VALUE;
5224 }
Eric Laurent84c70242014-06-23 08:46:27 -07005225 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5226 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005227 if (patchDesc != 0) {
5228 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005229 ALOGV("%s source id differs for patch current id %d new id %d",
5230 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 return BAD_VALUE;
5232 }
5233 }
Eric Laurent874c42872014-08-08 15:13:39 -07005234 DeviceVector devices;
5235 for (size_t i = 0; i < patch->num_sinks; i++) {
5236 // Only support mix to devices connection
5237 // TODO add support for mix to mix connection
5238 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005239 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005240 return INVALID_OPERATION;
5241 }
5242 sp<DeviceDescriptor> devDesc =
5243 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5244 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005245 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005246 return BAD_VALUE;
5247 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005248
jiabin66acc432024-02-06 00:57:36 +00005249 if (outputDesc->mProfile->getCompatibilityScore(
5250 DeviceVector(devDesc),
5251 patch->sources[0].sample_rate,
5252 nullptr, // updatedSamplingRate
5253 patch->sources[0].format,
5254 nullptr, // updatedFormat
5255 patch->sources[0].channel_mask,
5256 nullptr, // updatedChannelMask
5257 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005258 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005259 return INVALID_OPERATION;
5260 }
5261 devices.add(devDesc);
5262 }
5263 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005264 return INVALID_OPERATION;
5265 }
Eric Laurent874c42872014-08-08 15:13:39 -07005266
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005268 ALOGV("%s setting device %s on output %d",
5269 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305270 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 index = mAudioPatches.indexOfKey(*handle);
5272 if (index >= 0) {
5273 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005274 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 }
5276 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005277 patchDesc->setUid(uid);
5278 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005280 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005281 return INVALID_OPERATION;
5282 }
5283 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5284 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5285 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005286 // only one sink supported when connecting an input device to a mix
5287 if (patch->num_sinks > 1) {
5288 return INVALID_OPERATION;
5289 }
François Gaffie53615e22015-03-19 09:24:12 +01005290 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005291 if (inputDesc == NULL) {
5292 return BAD_VALUE;
5293 }
5294 if (patchDesc != 0) {
5295 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5296 return BAD_VALUE;
5297 }
5298 }
François Gaffie11d30102018-11-02 16:09:09 +01005299 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005301 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005302 return BAD_VALUE;
5303 }
5304
jiabin66acc432024-02-06 00:57:36 +00005305 if (inputDesc->mProfile->getCompatibilityScore(
5306 DeviceVector(device),
5307 patch->sinks[0].sample_rate,
5308 nullptr, /*updatedSampleRate*/
5309 patch->sinks[0].format,
5310 nullptr, /*updatedFormat*/
5311 patch->sinks[0].channel_mask,
5312 nullptr, /*updatedChannelMask*/
5313 // FIXME for the parameter type,
5314 // and the NONE
5315 (audio_output_flags_t)
5316 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005317 return INVALID_OPERATION;
5318 }
5319 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005320 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005321 device->toString().c_str(), inputDesc->mIoHandle);
5322 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 index = mAudioPatches.indexOfKey(*handle);
5324 if (index >= 0) {
5325 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005326 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005327 }
5328 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005329 patchDesc->setUid(uid);
5330 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005331 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005332 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005333 return INVALID_OPERATION;
5334 }
5335 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5336 // device to device connection
5337 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005338 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005339 return BAD_VALUE;
5340 }
5341 }
François Gaffie11d30102018-11-02 16:09:09 +01005342 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005343 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005344 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005345 return BAD_VALUE;
5346 }
Eric Laurent874c42872014-08-08 15:13:39 -07005347
Eric Laurent6a94d692014-05-20 11:18:06 -07005348 //update source and sink with our own data as the data passed in the patch may
5349 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005350 PatchBuilder patchBuilder;
5351 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005352
5353 // if first sink is to MSD, establish single MSD patch
5354 if (getMsdAudioOutDevices().contains(
5355 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5356 ALOGV("%s patching to MSD", __FUNCTION__);
5357 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5358 goto installPatch;
5359 }
5360
François Gaffieafd4cea2019-11-18 15:50:22 +01005361 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5362 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005363
Eric Laurent874c42872014-08-08 15:13:39 -07005364 for (size_t i = 0; i < patch->num_sinks; i++) {
5365 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005366 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005367 return INVALID_OPERATION;
5368 }
François Gaffie11d30102018-11-02 16:09:09 +01005369 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005370 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005371 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005372 return BAD_VALUE;
5373 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005374 audio_port_config sinkPortConfig = {};
5375 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5376 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005377
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005378 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5379 // volume management purpose (tracking activity)
5380 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5381 // in config XML to reach the sink so that is can be declared as available.
5382 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005383 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005384 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005385 // take care of dynamic routing for SwOutput selection,
5386 audio_attributes_t attributes = sourceDesc->attributes();
5387 audio_stream_type_t stream = sourceDesc->stream();
5388 audio_attributes_t resultAttr;
5389 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5390 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005391 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5392 config.channel_mask =
5393 (audio_channel_mask_get_representation(sourceMask)
5394 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5395 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005396 config.format = sourceDesc->config().format;
5397 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5398 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5399 bool isRequestedDeviceForExclusiveUse = false;
5400 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005401 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005402 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005403 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5404 &stream, sourceDesc->uid(), &config, &flags,
5405 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005406 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005407 if (output == AUDIO_IO_HANDLE_NONE) {
5408 ALOGV("%s no output for device %s",
5409 __FUNCTION__, sinkDevice->toString().c_str());
5410 return INVALID_OPERATION;
5411 }
5412 outputDesc = mOutputs.valueFor(output);
5413 if (outputDesc->isDuplicated()) {
5414 ALOGE("%s output is duplicated", __func__);
5415 return INVALID_OPERATION;
5416 }
François Gaffie7e39df22022-04-26 12:48:49 +02005417 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5418 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005419 } else {
5420 // Same for "raw patches" aka created from createAudioPatch API
5421 SortedVector<audio_io_handle_t> outputs =
5422 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5423 // if the sink device is reachable via an opened output stream, request to
5424 // go via this output stream by adding a second source to the patch
5425 // description
5426 output = selectOutput(outputs);
5427 if (output == AUDIO_IO_HANDLE_NONE) {
5428 ALOGE("%s no output available for internal patch sink", __func__);
5429 return INVALID_OPERATION;
5430 }
5431 outputDesc = mOutputs.valueFor(output);
5432 if (outputDesc->isDuplicated()) {
5433 ALOGV("%s output for device %s is duplicated",
5434 __func__, sinkDevice->toString().c_str());
5435 return INVALID_OPERATION;
5436 }
François Gaffie7e39df22022-04-26 12:48:49 +02005437 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005438 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005439 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005440 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005441 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005442 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005443 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5444 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005445 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5446 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005447 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005448 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005449 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005450 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005451 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005452 return INVALID_OPERATION;
5453 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005454 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005455 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005456 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005457 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005458 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005459 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005460 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005461 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5462 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005463 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005464 }
Eric Laurent83b88082014-06-20 18:31:16 -07005465 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005466 }
5467 // TODO: check from routing capabilities in config file and other conflicting patches
5468
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005469installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005470 status_t status = installPatch(
5471 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005472 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005473 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005474 return INVALID_OPERATION;
5475 }
5476 } else {
5477 return BAD_VALUE;
5478 }
5479 } else {
5480 return BAD_VALUE;
5481 }
5482 return NO_ERROR;
5483}
5484
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005485status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005486{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005487 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005488 ssize_t index = mAudioPatches.indexOfKey(handle);
5489
5490 if (index < 0) {
5491 return BAD_VALUE;
5492 }
5493 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005494 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5495 __func__, mUidCached, patchDesc->getUid(), uid);
5496 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005497 return INVALID_OPERATION;
5498 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005499 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5500 for (size_t i = 0; i < mAudioSources.size(); i++) {
5501 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5502 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5503 portId = sourceDesc->portId();
5504 break;
5505 }
5506 }
5507 return portId != AUDIO_PORT_HANDLE_NONE ?
5508 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005509}
Eric Laurent6a94d692014-05-20 11:18:06 -07005510
François Gaffieafd4cea2019-11-18 15:50:22 +01005511status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005512 uint32_t delayMs,
5513 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005514{
5515 ALOGV("%s patch %d", __func__, handle);
5516 if (mAudioPatches.indexOfKey(handle) < 0) {
5517 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5518 return BAD_VALUE;
5519 }
5520 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005521 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005522 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005523 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005524 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005525 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005526 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005527 return BAD_VALUE;
5528 }
5529
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305530 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005531 getNewOutputDevices(outputDesc, true /*fromCache*/),
5532 true,
5533 0,
5534 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005535 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5536 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005537 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005538 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005539 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005540 return BAD_VALUE;
5541 }
5542 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005543 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005544 true,
5545 NULL);
5546 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005547 status_t status =
5548 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5549 ALOGV("%s patch panel returned %d patchHandle %d",
5550 __func__, status, patchDesc->getAfHandle());
5551 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005552 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005553 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005554 // SW or HW Bridge
5555 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5556 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005557 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005558 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5559 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5560 outputDesc = sourceDesc->swOutput().promote();
5561 }
5562 if (outputDesc == nullptr) {
5563 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5564 // releaseOutput has already called closeOutput in case of direct output
5565 return NO_ERROR;
5566 }
François Gaffie7e39df22022-04-26 12:48:49 +02005567 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005568 // While using a HwBridge, force reconsidering device only if not reusing an existing
5569 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005570 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005571 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5572 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5573 // Reconsider device only for cases:
5574 // 1 / Active Output
5575 // 2 / Inactive Output previously hosting HwBridge
5576 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5577 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5578 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305579 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005580 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5581 outputDesc->devices(),
5582 force,
5583 0,
5584 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005585 } else {
5586 return BAD_VALUE;
5587 }
5588 } else {
5589 return BAD_VALUE;
5590 }
5591 return NO_ERROR;
5592}
5593
5594status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5595 struct audio_patch *patches,
5596 unsigned int *generation)
5597{
François Gaffie53615e22015-03-19 09:24:12 +01005598 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005599 return BAD_VALUE;
5600 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005601 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005602 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005603}
5604
Eric Laurente1715a42014-05-20 11:30:42 -07005605status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005606{
Eric Laurente1715a42014-05-20 11:30:42 -07005607 ALOGV("setAudioPortConfig()");
5608
5609 if (config == NULL) {
5610 return BAD_VALUE;
5611 }
5612 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5613 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005614 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5615 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005616 }
5617
Eric Laurenta121f902014-06-03 13:32:54 -07005618 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005619 if (config->type == AUDIO_PORT_TYPE_MIX) {
5620 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005621 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005622 if (outputDesc == NULL) {
5623 return BAD_VALUE;
5624 }
Eric Laurent84c70242014-06-23 08:46:27 -07005625 ALOG_ASSERT(!outputDesc->isDuplicated(),
5626 "setAudioPortConfig() called on duplicated output %d",
5627 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005628 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005629 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005630 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005631 if (inputDesc == NULL) {
5632 return BAD_VALUE;
5633 }
Eric Laurenta121f902014-06-03 13:32:54 -07005634 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005635 } else {
5636 return BAD_VALUE;
5637 }
5638 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5639 sp<DeviceDescriptor> deviceDesc;
5640 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5641 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5642 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5643 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5644 } else {
5645 return BAD_VALUE;
5646 }
5647 if (deviceDesc == NULL) {
5648 return BAD_VALUE;
5649 }
Eric Laurenta121f902014-06-03 13:32:54 -07005650 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005651 } else {
5652 return BAD_VALUE;
5653 }
5654
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005655 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005656 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5657 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005658 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005659 audioPortConfig->toAudioPortConfig(&newConfig, config);
5660 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005661 }
Eric Laurenta121f902014-06-03 13:32:54 -07005662 if (status != NO_ERROR) {
5663 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005664 }
Eric Laurente1715a42014-05-20 11:30:42 -07005665
5666 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005667}
5668
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005669void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5670{
Eric Laurentd60560a2015-04-10 11:31:20 -07005671 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005672 clearAudioPatches(uid);
5673 clearSessionRoutes(uid);
5674}
5675
Eric Laurent6a94d692014-05-20 11:18:06 -07005676void AudioPolicyManager::clearAudioPatches(uid_t uid)
5677{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005678 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005679 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005680 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005681 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005682 }
5683 }
5684}
5685
François Gaffiec005e562018-11-06 15:04:49 +01005686void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005687{
François Gaffiec005e562018-11-06 15:04:49 +01005688 // Take the first attributes following the product strategy as it is used to retrieve the routed
5689 // device. All attributes wihin a strategy follows the same "routing strategy"
5690 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5691 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005692 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005693 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005694 for (size_t j = 0; j < mOutputs.size(); j++) {
5695 if (mOutputs.keyAt(j) == ouptutToSkip) {
5696 continue;
5697 }
5698 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005699 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005700 continue;
5701 }
5702 // If the default device for this strategy is on another output mix,
5703 // invalidate all tracks in this strategy to force re connection.
5704 // Otherwise select new device on the output mix.
5705 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005706 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005707 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005708 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005709 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005710 // If the device is using preferred mixer attributes, the output need to reopen
5711 // with default configuration when the new selected devices are different from
5712 // current routing devices.
5713 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5714 continue;
5715 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305716 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005717 }
5718 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005719 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005720}
5721
5722void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5723{
5724 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005725 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005726 for (size_t i = 0; i < mOutputs.size(); i++) {
5727 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005728 for (const auto& client : outputDesc->getClientIterable()) {
5729 if (client->hasPreferredDevice() && client->uid() == uid) {
5730 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005731 auto clientStrategy = client->strategy();
5732 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5733 end(affectedStrategies)) {
5734 continue;
5735 }
5736 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005737 }
5738 }
5739 }
5740 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005741 for (const auto& strategy : affectedStrategies) {
5742 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005743 }
5744
5745 // remove input routes associated with this uid
5746 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005747 for (size_t i = 0; i < mInputs.size(); i++) {
5748 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005749 for (const auto& client : inputDesc->getClientIterable()) {
5750 if (client->hasPreferredDevice() && client->uid() == uid) {
5751 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5752 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005753 }
5754 }
5755 }
5756 // reroute inputs if necessary
5757 SortedVector<audio_io_handle_t> inputsToClose;
5758 for (size_t i = 0; i < mInputs.size(); i++) {
5759 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005760 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005761 inputsToClose.add(inputDesc->mIoHandle);
5762 }
5763 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005764 for (const auto& input : inputsToClose) {
5765 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005766 }
5767}
5768
Eric Laurentd60560a2015-04-10 11:31:20 -07005769void AudioPolicyManager::clearAudioSources(uid_t uid)
5770{
5771 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005772 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5773 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005774 stopAudioSource(mAudioSources.keyAt(i));
5775 }
5776 }
5777}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005778
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005779status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5780 audio_io_handle_t *ioHandle,
5781 audio_devices_t *device)
5782{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005783 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5784 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005785 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005786 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5787 if (deviceDesc == nullptr) {
5788 return INVALID_OPERATION;
5789 }
5790 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005791
François Gaffiedf372692015-03-19 10:43:27 +01005792 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005793}
5794
Eric Laurentd60560a2015-04-10 11:31:20 -07005795status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005796 const audio_attributes_t *attributes,
5797 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005798 uid_t uid) {
5799 return startAudioSourceInternal(source, attributes, portId, uid,
David Li48b6a832024-07-01 13:14:10 +00005800 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurent963dbcc2024-06-20 12:34:15 +00005801}
5802
5803status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5804 const audio_attributes_t *attributes,
5805 audio_port_handle_t *portId,
David Li48b6a832024-07-01 13:14:10 +00005806 uid_t uid, bool internal, bool isCallRx,
5807 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005808{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005809 ALOGV("%s", __FUNCTION__);
5810 *portId = AUDIO_PORT_HANDLE_NONE;
5811
5812 if (source == NULL || attributes == NULL || portId == NULL) {
5813 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5814 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005815 return BAD_VALUE;
5816 }
5817
Eric Laurentd60560a2015-04-10 11:31:20 -07005818 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5819 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005820 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5821 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005822 return INVALID_OPERATION;
5823 }
5824
François Gaffie11d30102018-11-02 16:09:09 +01005825 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005826 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005827 String8(source->ext.device.address),
5828 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005829 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005830 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005831 return BAD_VALUE;
5832 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005833
jiabin4ef93452019-09-10 14:29:54 -07005834 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005835
François Gaffieaaac0fd2018-11-22 17:56:39 +01005836 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005837 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005838 mEngine->getStreamTypeForAttributes(*attributes),
5839 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005840 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005841
David Li48b6a832024-07-01 13:14:10 +00005842 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005843 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005844 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005845 }
5846 return status;
5847}
5848
David Li48b6a832024-07-01 13:14:10 +00005849status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5850 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005851{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005852 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005853
5854 // make sure we only have one patch per source.
5855 disconnectAudioSource(sourceDesc);
5856
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005857 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005858 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5859 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5860 sourceDesc->srcDevice()->type(),
5861 String8(sourceDesc->srcDevice()->address().c_str()),
5862 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005863 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005864 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005865 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005866 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005867 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5868 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5869 return INVALID_OPERATION;
5870 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005871 PatchBuilder patchBuilder;
5872 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5873 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005874
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005875 return connectAudioSourceToSink(
David Li48b6a832024-07-01 13:14:10 +00005876 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005877}
5878
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005879status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005880{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005881 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5882 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005883 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005884 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005885 return BAD_VALUE;
5886 }
5887 status_t status = disconnectAudioSource(sourceDesc);
5888
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005889 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005890 return status;
5891}
5892
Andy Hung2ddee192015-12-18 17:34:44 -08005893status_t AudioPolicyManager::setMasterMono(bool mono)
5894{
5895 if (mMasterMono == mono) {
5896 return NO_ERROR;
5897 }
5898 mMasterMono = mono;
5899 // if enabling mono we close all offloaded devices, which will invalidate the
5900 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5901 // for recreating the new AudioTrack as non-offloaded PCM.
5902 //
5903 // If disabling mono, we leave all tracks as is: we don't know which clients
5904 // and tracks are able to be recreated as offloaded. The next "song" should
5905 // play back offloaded.
5906 if (mMasterMono) {
5907 Vector<audio_io_handle_t> offloaded;
5908 for (size_t i = 0; i < mOutputs.size(); ++i) {
5909 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5910 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5911 offloaded.push(desc->mIoHandle);
5912 }
5913 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005914 for (const auto& handle : offloaded) {
5915 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005916 }
5917 }
5918 // update master mono for all remaining outputs
5919 for (size_t i = 0; i < mOutputs.size(); ++i) {
5920 updateMono(mOutputs.keyAt(i));
5921 }
5922 return NO_ERROR;
5923}
5924
5925status_t AudioPolicyManager::getMasterMono(bool *mono)
5926{
5927 *mono = mMasterMono;
5928 return NO_ERROR;
5929}
5930
Eric Laurentac9cef52017-06-09 15:46:26 -07005931float AudioPolicyManager::getStreamVolumeDB(
5932 audio_stream_type_t stream, int index, audio_devices_t device)
5933{
jiabin9a3361e2019-10-01 09:38:30 -07005934 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005935}
5936
jiabin81772902018-04-02 17:52:27 -07005937status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5938 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005939 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005940{
Kriti Dang6537def2021-03-02 13:46:59 +01005941 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5942 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005943 return BAD_VALUE;
5944 }
Kriti Dang6537def2021-03-02 13:46:59 +01005945 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5946 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005947
5948 size_t formatsWritten = 0;
5949 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005950
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005951 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005952 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5953 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005954 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005955 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005956 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005957 bool formatEnabled = true;
5958 switch (forceUse) {
5959 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005960 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005961 break;
5962 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5963 formatEnabled = false;
5964 break;
5965 default: // AUTO or ALWAYS => true
5966 break;
jiabin81772902018-04-02 17:52:27 -07005967 }
5968 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5969 }
jiabin81772902018-04-02 17:52:27 -07005970 }
5971 return NO_ERROR;
5972}
5973
Kriti Dang6537def2021-03-02 13:46:59 +01005974status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5975 audio_format_t *surroundFormats) {
5976 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5977 return BAD_VALUE;
5978 }
5979 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5980 __func__, *numSurroundFormats, surroundFormats);
5981
5982 size_t formatsWritten = 0;
5983 size_t formatsMax = *numSurroundFormats;
5984 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5985
5986 // Return formats from all device profiles that have already been resolved by
5987 // checkOutputsForDevice().
5988 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5989 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5990 audio_devices_t deviceType = device->type();
5991 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5992 // returns formats reported by HDMI devices.
5993 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5994 continue;
5995 }
5996 // Formats reported by sink devices
5997 std::unordered_set<audio_format_t> formatset;
5998 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5999 formatset.insert(it->second.begin(), it->second.end());
6000 }
6001
6002 // Formats hard-coded in the in policy configuration file (if any).
6003 FormatVector encodedFormats = device->encodedFormats();
6004 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6005 // Filter the formats which are supported by the vendor hardware.
6006 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006007 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006008 formats.insert(*it);
6009 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006010 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006011 if (pair.second.count(*it) != 0) {
6012 formats.insert(pair.first);
6013 break;
6014 }
6015 }
6016 }
6017 }
6018 }
6019 *numSurroundFormats = formats.size();
6020 for (const auto& format: formats) {
6021 if (formatsWritten < formatsMax) {
6022 surroundFormats[formatsWritten++] = format;
6023 }
6024 }
6025 return NO_ERROR;
6026}
6027
jiabin81772902018-04-02 17:52:27 -07006028status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6029{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006030 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006031 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6032 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006033 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006034 return BAD_VALUE;
6035 }
6036
Mikhail Naganov100f0122018-11-29 11:22:16 -08006037 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6038 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006039 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006040 return INVALID_OPERATION;
6041 }
6042
Mikhail Naganov100f0122018-11-29 11:22:16 -08006043 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006044 return NO_ERROR;
6045 }
6046
Mikhail Naganov100f0122018-11-29 11:22:16 -08006047 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006048 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006049 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006050 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006051 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006052 }
6053 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006054 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006055 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006056 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006057 }
6058 }
6059
6060 sp<SwAudioOutputDescriptor> outputDesc;
6061 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006062 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6063 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006064 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6065 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006066 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006067 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006068 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6069 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6070 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006071 name.c_str(),
6072 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006073 if (status != NO_ERROR) {
6074 continue;
6075 }
6076 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6077 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6078 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006079 name.c_str(),
6080 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006081 profileUpdated |= (status == NO_ERROR);
6082 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006083 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006084 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006085 AUDIO_DEVICE_IN_HDMI);
6086 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6087 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006088 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006089 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006090 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6091 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6092 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006093 name.c_str(),
6094 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006095 if (status != NO_ERROR) {
6096 continue;
6097 }
6098 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6099 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6100 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006101 name.c_str(),
6102 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006103 profileUpdated |= (status == NO_ERROR);
6104 }
6105
jiabin81772902018-04-02 17:52:27 -07006106 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006107 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006108 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006109 }
6110
6111 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6112}
6113
Eric Laurent5ada82e2019-08-29 17:53:54 -07006114void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006115{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006116 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006117 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006118 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006119 }
6120}
6121
jiabin6012f912018-11-02 17:06:30 -07006122bool AudioPolicyManager::isHapticPlaybackSupported()
6123{
6124 for (const auto& hwModule : mHwModules) {
6125 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6126 for (const auto &outProfile : outputProfiles) {
6127 struct audio_port audioPort;
6128 outProfile->toAudioPort(&audioPort);
6129 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6130 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6131 return true;
6132 }
6133 }
6134 }
6135 }
6136 return false;
6137}
6138
Carter Hsu325a8eb2022-01-19 19:56:51 +08006139bool AudioPolicyManager::isUltrasoundSupported()
6140{
6141 bool hasUltrasoundOutput = false;
6142 bool hasUltrasoundInput = false;
6143 for (const auto& hwModule : mHwModules) {
6144 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6145 if (!hasUltrasoundOutput) {
6146 for (const auto &outProfile : outputProfiles) {
6147 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6148 hasUltrasoundOutput = true;
6149 break;
6150 }
6151 }
6152 }
6153
6154 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6155 if (!hasUltrasoundInput) {
6156 for (const auto &inputProfile : inputProfiles) {
6157 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6158 hasUltrasoundInput = true;
6159 break;
6160 }
6161 }
6162 }
6163
6164 if (hasUltrasoundOutput && hasUltrasoundInput)
6165 return true;
6166 }
6167 return false;
6168}
6169
Atneya Nair698f5ef2022-12-15 16:15:09 -08006170bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6171{
6172 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6173 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6174 for (const auto& hwModule : mHwModules) {
6175 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6176 for (const auto &inputProfile : inputProfiles) {
6177 if ((inputProfile->getFlags() & mask) == mask) {
6178 return true;
6179 }
6180 }
6181 }
6182 return false;
6183}
6184
Eric Laurent8340e672019-11-06 11:01:08 -08006185bool AudioPolicyManager::isCallScreenModeSupported()
6186{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006187 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006188}
6189
6190
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006191status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006192{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006193 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006194 if (!sourceDesc->isConnected()) {
6195 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6196 return NO_ERROR;
6197 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006198 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6199 if (swOutput != 0) {
6200 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006201 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006202 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006203 }
jiabinbce0c1d2020-10-05 11:20:18 -07006204 if (releaseOutput(sourceDesc->portId())) {
6205 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6206 // no need to release audio patch here but just return NO_ERROR.
6207 return NO_ERROR;
6208 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006209 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006210 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006211 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006212 // close Hwoutput and remove from mHwOutputs
6213 } else {
6214 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6215 }
6216 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006217 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006218 sourceDesc->disconnect();
6219 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006220}
6221
François Gaffiec005e562018-11-06 15:04:49 +01006222sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6223 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006224{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006225 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006226 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006227 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006228 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006229 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6230 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006231 source = sourceDesc;
6232 break;
6233 }
6234 }
6235 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006236}
6237
Eric Laurentb4f42a92022-01-17 17:37:31 +01006238bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006239 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006240 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006241{
6242 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6243 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006244 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006245 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006246 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6247 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6248 return false;
6249 }
6250 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6251 return false;
6252 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006253 }
6254
Eric Laurentd332bc82023-08-04 11:45:23 +02006255 // The caller can have the audio config criteria ignored by either passing a null ptr or
6256 // the AUDIO_CONFIG_INITIALIZER value.
6257 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006258 // some positional channel masks and PCM format and for stereo if low latency performance
6259 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006260
6261 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006262 static const bool stereo_spatialization_enabled =
6263 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006264 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006265 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006266 ? audio_channel_mask_contains_stereo(config->channel_mask)
6267 : audio_is_channel_mask_spatialized(config->channel_mask);
6268 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006269 return false;
6270 }
6271 if (!audio_is_linear_pcm(config->format)) {
6272 return false;
6273 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006274 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6275 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6276 return false;
6277 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006278 }
6279
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006280 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006281 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006282 if (profile == nullptr) {
6283 return false;
6284 }
6285
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006286 return true;
6287}
6288
Shunkai Yao57b93392024-04-26 04:12:21 +00006289// The Spatializer output is compatible with Haptic use cases if:
6290// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6291// with client if client haptic channel bits were set, or
6292// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6293// including the haptic bits or creating the HapticGenerator effect for same session.
6294bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6295 const audio_config_t* config, audio_session_t sessionId) const {
6296 const auto clientHapticChannel =
6297 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6298 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6299 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6300
6301 if (threadOutputHapticChannel) {
6302 // check format and sampleRate match if client haptic channel mask exist
6303 if (clientHapticChannel) {
6304 return mSpatializerOutput->getFormat() == config->format &&
6305 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6306 }
6307 return true;
6308 } else {
6309 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6310 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6311 // HapticGenerator effect for this session) are not supported.
6312 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006313 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006314 }
6315}
6316
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006317void AudioPolicyManager::checkVirtualizerClientRoutes() {
6318 std::set<audio_stream_type_t> streamsToInvalidate;
6319 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006320 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6321 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006322 audio_attributes_t attr = client->attributes();
6323 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6324 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6325 audio_config_base_t clientConfig = client->config();
6326 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006327 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006328 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006329 streamsToInvalidate.insert(client->stream());
6330 }
6331 }
6332 }
6333
jiabinc44b3462022-12-08 12:52:31 -08006334 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006335}
6336
Eric Laurente191d1b2022-04-15 11:59:25 +02006337
6338bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6339 const sp<SwAudioOutputDescriptor>& outputDesc) {
6340 if (outputDesc->isDuplicated()) {
6341 return false;
6342 }
6343 DeviceVector devices = outputDesc->supportedDevices();
6344 for (size_t i = 0; i < mOutputs.size(); i++) {
6345 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6346 if (desc == outputDesc || desc->isDuplicated()) {
6347 continue;
6348 }
6349 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6350 if (!sharedDevices.isEmpty()
6351 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6352 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6353 return false;
6354 }
6355 }
6356 return true;
6357}
6358
6359
Eric Laurentfa0f6742021-08-17 18:39:44 +02006360status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006361 const audio_attributes_t *attr,
6362 audio_io_handle_t *output) {
6363 *output = AUDIO_IO_HANDLE_NONE;
6364
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006365 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6366 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6367 audio_config_t *configPtr = nullptr;
6368 audio_config_t config;
6369 if (mixerConfig != nullptr) {
6370 config = audio_config_initializer(mixerConfig);
6371 configPtr = &config;
6372 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006373 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006374 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006375 return BAD_VALUE;
6376 }
6377
6378 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006379 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006380 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006381 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006382 return BAD_VALUE;
6383 }
6384
Eric Laurente191d1b2022-04-15 11:59:25 +02006385 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006386 for (size_t i = 0; i < mOutputs.size(); i++) {
6387 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006388 if (!desc->isDuplicated()
6389 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6390 spatializerOutputs.push_back(desc);
6391 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006392 }
6393 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006394 mSpatializerOutput.clear();
6395 bool outputsChanged = false;
6396 for (const auto& desc : spatializerOutputs) {
6397 if (desc->mProfile == profile
6398 && (configPtr == nullptr
6399 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6400 mSpatializerOutput = desc;
6401 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6402 } else {
6403 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6404 " and devices %s", __func__, desc->mIoHandle,
6405 configPtr != nullptr ? configPtr->channel_mask : 0,
6406 devices.toString().c_str());
6407 closeOutput(desc->mIoHandle);
6408 outputsChanged = true;
6409 }
Eric Laurent39095982021-08-24 18:29:27 +02006410 }
6411
Eric Laurente191d1b2022-04-15 11:59:25 +02006412 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006413 sp<SwAudioOutputDescriptor> desc =
6414 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006415 if (desc != nullptr) {
6416 mSpatializerOutput = desc;
6417 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006418 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006419 }
6420
6421 checkVirtualizerClientRoutes();
6422
Eric Laurente191d1b2022-04-15 11:59:25 +02006423 if (outputsChanged) {
6424 mPreviousOutputs = mOutputs;
6425 mpClientInterface->onAudioPortListUpdate();
6426 }
6427
6428 if (mSpatializerOutput == nullptr) {
6429 ALOGV("%s could not open spatializer output with requested config", __func__);
6430 return BAD_VALUE;
6431 }
Eric Laurent39095982021-08-24 18:29:27 +02006432 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006433 ALOGV("%s returning new spatializer output %d", __func__, *output);
6434 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006435}
6436
Eric Laurentfa0f6742021-08-17 18:39:44 +02006437status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6438 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006439 return INVALID_OPERATION;
6440 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006441 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006442 return BAD_VALUE;
6443 }
Eric Laurent39095982021-08-24 18:29:27 +02006444
Eric Laurente191d1b2022-04-15 11:59:25 +02006445 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6446 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6447 closeOutput(mSpatializerOutput->mIoHandle);
6448 //from now on mSpatializerOutput is null
6449 checkVirtualizerClientRoutes();
6450 }
Eric Laurent39095982021-08-24 18:29:27 +02006451
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006452 return NO_ERROR;
6453}
6454
Eric Laurente552edb2014-03-10 17:42:56 -07006455// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006456// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006457// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006458uint32_t AudioPolicyManager::nextAudioPortGeneration()
6459{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006460 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006461}
6462
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006463AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006464 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006465 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006466 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006467 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006468 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006469 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006470 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006471 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006472 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006473 mAudioPortGeneration(1),
6474 mBeaconMuteRefCount(0),
6475 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006476 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006477 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006478 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006479 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006480{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006481}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006482
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006483status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006484 if (mEngine == nullptr) {
6485 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006486 }
6487 mEngine->setObserver(this);
6488 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006489 if (status != NO_ERROR) {
6490 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6491 return status;
6492 }
François Gaffie2110e042015-03-24 08:41:51 +01006493
jiabin29230182023-04-04 21:02:36 +00006494 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6495 // at the end of this function.
6496 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006497 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6498 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6499
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006500 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006501 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006502 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006503
Eric Laurent3a4311c2014-03-17 12:00:47 -07006504 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006505 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6506 defaultOutputDevice == nullptr ||
6507 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6508 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6509 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006510 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006511 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006512 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006513
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006514 // Silence ALOGV statements
6515 property_set("log.tag." LOG_TAG, "D");
6516
Eric Laurente552edb2014-03-10 17:42:56 -07006517 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006518 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006519}
6520
Eric Laurente0720872014-03-11 09:30:41 -07006521AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006522{
Eric Laurente552edb2014-03-10 17:42:56 -07006523 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006524 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006525 }
6526 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006527 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006528 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006529 mAvailableOutputDevices.clear();
6530 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006531 mOutputs.clear();
6532 mInputs.clear();
6533 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006534 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006535 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006536}
6537
Eric Laurente0720872014-03-11 09:30:41 -07006538status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006539{
Eric Laurent87ffa392015-05-22 10:32:38 -07006540 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006541}
6542
Eric Laurente552edb2014-03-10 17:42:56 -07006543// ---
6544
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006545void AudioPolicyManager::onNewAudioModulesAvailable()
6546{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006547 DeviceVector newDevices;
6548 onNewAudioModulesAvailableInt(&newDevices);
6549 if (!newDevices.empty()) {
6550 nextAudioPortGeneration();
6551 mpClientInterface->onAudioPortListUpdate();
6552 }
6553}
6554
6555void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6556{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006557 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006558 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6559 continue;
6560 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006561 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006562 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6563 handle != AUDIO_MODULE_HANDLE_NONE) {
6564 hwModule->setHandle(handle);
6565 } else {
6566 ALOGW("could not load HW module %s", hwModule->getName());
6567 continue;
6568 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006569 }
6570 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006571 // open all output streams needed to access attached devices.
6572 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006573 // This also validates mAvailableOutputDevices list
6574 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6575 if (!outProfile->canOpenNewIo()) {
6576 ALOGE("Invalid Output profile max open count %u for profile %s",
6577 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6578 continue;
6579 }
6580 if (!outProfile->hasSupportedDevices()) {
6581 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6582 continue;
6583 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006584 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6585 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006586 mTtsOutputAvailable = true;
6587 }
6588
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006589 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006590 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006591 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006592 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6593 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006594 } else {
6595 // choose first device present in profile's SupportedDevices also part of
6596 // mAvailableOutputDevices.
6597 if (availProfileDevices.isEmpty()) {
6598 continue;
6599 }
6600 supportedDevice = availProfileDevices.itemAt(0);
6601 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006602 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006603 continue;
6604 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306605
6606 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6607 && availProfileDevices.areAllDevicesAttached()) {
6608 ALOGV("%s skip opening output for mmap profile %s", __func__,
6609 outProfile->getTagName().c_str());
6610 continue;
6611 }
6612
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006613 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6614 mpClientInterface);
6615 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006616 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006617 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006618 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6619 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006620 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006621 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006622 if (status != NO_ERROR) {
6623 ALOGW("Cannot open output stream for devices %s on hw module %s",
6624 supportedDevice->toString().c_str(), hwModule->getName());
6625 continue;
6626 }
6627 for (const auto &device : availProfileDevices) {
6628 // give a valid ID to an attached device once confirmed it is reachable
6629 if (!device->isAttached()) {
6630 device->attach(hwModule);
6631 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006632 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006633 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006634 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6635 }
6636 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006637 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006638 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6639 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006640 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006641 }
Eric Laurent39095982021-08-24 18:29:27 +02006642 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006643 outputDesc->close();
6644 } else {
6645 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306646 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006647 DeviceVector(supportedDevice),
6648 true,
6649 0,
6650 NULL);
6651 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006652 }
6653 // open input streams needed to access attached devices to validate
6654 // mAvailableInputDevices list
6655 for (const auto& inProfile : hwModule->getInputProfiles()) {
6656 if (!inProfile->canOpenNewIo()) {
6657 ALOGE("Invalid Input profile max open count %u for profile %s",
6658 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6659 continue;
6660 }
6661 if (!inProfile->hasSupportedDevices()) {
6662 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6663 continue;
6664 }
6665 // chose first device present in profile's SupportedDevices also part of
6666 // available input devices
6667 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006668 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006669 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006670 ALOGV("%s: Input device list is empty! for profile %s",
6671 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006672 continue;
6673 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306674
6675 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6676 && availProfileDevices.areAllDevicesAttached()) {
6677 ALOGV("%s skip opening input for mmap profile %s", __func__,
6678 inProfile->getTagName().c_str());
6679 continue;
6680 }
6681
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006682 sp<AudioInputDescriptor> inputDesc =
6683 new AudioInputDescriptor(inProfile, mpClientInterface);
6684
6685 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6686 status_t status = inputDesc->open(nullptr,
6687 availProfileDevices.itemAt(0),
6688 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006689 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006690 &input);
6691 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306692 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6693 __func__, availProfileDevices.toString().c_str(),
6694 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006695 continue;
6696 }
6697 for (const auto &device : availProfileDevices) {
6698 // give a valid ID to an attached device once confirmed it is reachable
6699 if (!device->isAttached()) {
6700 device->attach(hwModule);
6701 device->importAudioPortAndPickAudioProfile(inProfile, true);
6702 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006703 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006704 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6705 }
6706 }
6707 inputDesc->close();
6708 }
6709 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006710
6711 // Check if spatializer outputs can be closed until used.
6712 // mOutputs vector never contains duplicated outputs at this point.
6713 std::vector<audio_io_handle_t> outputsClosed;
6714 for (size_t i = 0; i < mOutputs.size(); i++) {
6715 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6716 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6717 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6718 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006719 nextAudioPortGeneration();
6720 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6721 if (index >= 0) {
6722 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6723 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6724 patchDesc->getAfHandle(), 0);
6725 mAudioPatches.removeItemsAt(index);
6726 mpClientInterface->onAudioPatchListUpdate();
6727 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006728 desc->close();
6729 }
6730 }
6731 for (auto output : outputsClosed) {
6732 removeOutput(output);
6733 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006734}
6735
Eric Laurent98e38192018-02-15 18:31:53 -08006736void AudioPolicyManager::addOutput(audio_io_handle_t output,
6737 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006738{
Eric Laurent1c333e22014-05-20 10:48:17 -07006739 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006740 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006741 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006742 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006743 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006744}
6745
François Gaffie53615e22015-03-19 09:24:12 +01006746void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6747{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006748 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6749 ALOGV("%s: removing primary output", __func__);
6750 mPrimaryOutput = nullptr;
6751 }
François Gaffie53615e22015-03-19 09:24:12 +01006752 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006753 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006754}
6755
Eric Laurent98e38192018-02-15 18:31:53 -08006756void AudioPolicyManager::addInput(audio_io_handle_t input,
6757 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006758{
Eric Laurent1c333e22014-05-20 10:48:17 -07006759 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006760 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006761}
Eric Laurente552edb2014-03-10 17:42:56 -07006762
François Gaffie11d30102018-11-02 16:09:09 +01006763status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006764 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006765 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006766{
François Gaffie11d30102018-11-02 16:09:09 +01006767 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006768 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006769 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006770
François Gaffie11d30102018-11-02 16:09:09 +01006771 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006772 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006773 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006774 }
Eric Laurente552edb2014-03-10 17:42:56 -07006775
Eric Laurent3b73df72014-03-11 09:06:29 -07006776 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006777 // first call getAudioPort to get the supported attributes from the HAL
6778 struct audio_port_v7 port = {};
6779 device->toAudioPort(&port);
6780 status_t status = mpClientInterface->getAudioPort(&port);
6781 if (status == NO_ERROR) {
6782 device->importAudioPort(port);
6783 }
6784
6785 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006786 for (size_t i = 0; i < mOutputs.size(); i++) {
6787 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006788 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006789 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006790 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6791 mOutputs.keyAt(i), device->toString().c_str());
6792 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006793 }
6794 }
6795 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006796 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006797 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006798 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6799 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006800 if (profile->supportsDevice(device)) {
6801 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306802 ALOGV("%s(): adding profile %s from module %s",
6803 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006804 }
6805 }
6806 }
6807
Eric Laurent7b279bb2015-12-14 10:18:23 -08006808 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006809
Eric Laurente552edb2014-03-10 17:42:56 -07006810 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006811 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006812 return BAD_VALUE;
6813 }
6814
6815 // open outputs for matching profiles if needed. Direct outputs are also opened to
6816 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6817 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006818 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006819
6820 // nothing to do if one output is already opened for this profile
6821 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006822 for (j = 0; j < outputs.size(); j++) {
6823 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006824 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006825 // matching profile: save the sample rates, format and channel masks supported
6826 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006827 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006828 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006829 }
Eric Laurente552edb2014-03-10 17:42:56 -07006830 break;
6831 }
6832 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006833 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006834 continue;
6835 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306836 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6837 ALOGV("%s skip opening output for mmap profile %s",
6838 __func__, profile->getTagName().c_str());
6839 continue;
6840 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006841 if (!profile->canOpenNewIo()) {
6842 ALOGW("Max Output number %u already opened for this profile %s",
6843 profile->maxOpenCount, profile->getTagName().c_str());
6844 continue;
6845 }
6846
Eric Laurent83efe1c2017-07-09 16:51:08 -07006847 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006848 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006849 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6850 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006851 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006852 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006853 profiles.removeAt(profile_index);
6854 profile_index--;
6855 } else {
6856 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006857 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006858 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006859 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6860 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006861 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006862 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006863
François Gaffie11d30102018-11-02 16:09:09 +01006864 if (device_distinguishes_on_address(deviceType)) {
6865 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6866 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306867 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6868 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006869 }
Eric Laurente552edb2014-03-10 17:42:56 -07006870 ALOGV("checkOutputsForDevice(): adding output %d", output);
6871 }
6872 }
6873
6874 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006875 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006876 return BAD_VALUE;
6877 }
Eric Laurentd4692962014-05-05 18:13:44 -07006878 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006879 // check if one opened output is not needed any more after disconnecting one device
6880 for (size_t i = 0; i < mOutputs.size(); i++) {
6881 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006882 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006883 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006884 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006885 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006886 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006887 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006888 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6889 mOutputs.keyAt(i));
6890 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006891 }
Eric Laurente552edb2014-03-10 17:42:56 -07006892 }
6893 }
Eric Laurentd4692962014-05-05 18:13:44 -07006894 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006895 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006896 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6897 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006898 if (!profile->supportsDevice(device)) {
6899 continue;
6900 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306901 ALOGV("%s(): clearing direct output profile %s on module %s",
6902 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006903 profile->clearAudioProfiles();
6904 if (!profile->hasDynamicAudioProfile()) {
6905 continue;
6906 }
6907 // When a device is disconnected, if there is an IOProfile that contains dynamic
6908 // profiles and supports the disconnected device, call getAudioPort to repopulate
6909 // the capabilities of the devices that is supported by the IOProfile.
6910 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6911 if (supportedDevice == device ||
6912 !mAvailableOutputDevices.contains(supportedDevice)) {
6913 continue;
6914 }
6915 struct audio_port_v7 port;
6916 supportedDevice->toAudioPort(&port);
6917 status_t status = mpClientInterface->getAudioPort(&port);
6918 if (status == NO_ERROR) {
6919 supportedDevice->importAudioPort(port);
6920 }
Eric Laurente552edb2014-03-10 17:42:56 -07006921 }
6922 }
6923 }
6924 }
6925 return NO_ERROR;
6926}
6927
François Gaffie11d30102018-11-02 16:09:09 +01006928status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006929 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006930{
François Gaffie11d30102018-11-02 16:09:09 +01006931 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006932 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006933 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006934 }
6935
Eric Laurentd4692962014-05-05 18:13:44 -07006936 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006937 sp<AudioInputDescriptor> desc;
6938
jiabinbf5f4262023-04-12 21:48:34 +00006939 // first call getAudioPort to get the supported attributes from the HAL
6940 struct audio_port_v7 port = {};
6941 device->toAudioPort(&port);
6942 status_t status = mpClientInterface->getAudioPort(&port);
6943 if (status == NO_ERROR) {
6944 device->importAudioPort(port);
6945 }
6946
Eric Laurent0dd51852019-04-19 18:18:58 -07006947 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006948 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006949 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006950 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006951 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006952 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006953 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006954
François Gaffie11d30102018-11-02 16:09:09 +01006955 if (profile->supportsDevice(device)) {
6956 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306957 ALOGV("%s : adding profile %s from module %s", __func__,
6958 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006959 }
6960 }
6961 }
6962
Eric Laurent0dd51852019-04-19 18:18:58 -07006963 if (profiles.isEmpty()) {
6964 ALOGW("%s: No input profile available for device %s",
6965 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006966 return BAD_VALUE;
6967 }
6968
6969 // open inputs for matching profiles if needed. Direct inputs are also opened to
6970 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6971 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6972
Eric Laurent1c333e22014-05-20 10:48:17 -07006973 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006974
Eric Laurentd4692962014-05-05 18:13:44 -07006975 // nothing to do if one input is already opened for this profile
6976 size_t input_index;
6977 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6978 desc = mInputs.valueAt(input_index);
6979 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006980 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006981 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006982 }
Eric Laurentd4692962014-05-05 18:13:44 -07006983 break;
6984 }
6985 }
6986 if (input_index != mInputs.size()) {
6987 continue;
6988 }
6989
Jaideep Sharma44824a22024-06-18 16:32:34 +05306990 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6991 ALOGV("%s skip opening input for mmap profile %s",
6992 __func__, profile->getTagName().c_str());
6993 continue;
6994 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006995 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306996 ALOGW("%s Max Input number %u already opened for this profile %s",
6997 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08006998 continue;
6999 }
7000
Eric Laurentfe231122017-11-17 17:48:06 -08007001 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007002 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307003 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00007004 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7005 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007006
Eric Laurentcf2c0212014-07-25 16:20:43 -07007007 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007008 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007009 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007010 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007011 mpClientInterface->setParameters(input, String8(param));
7012 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007013 }
jiabin12537fc2023-10-12 17:56:08 +00007014 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007015 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307016 ALOGW("%s direct input missing param for profile %s", __func__,
7017 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007018 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007019 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007020 }
7021
Eric Laurent0dd51852019-04-19 18:18:58 -07007022 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007023 addInput(input, desc);
7024 }
7025 } // endif input != 0
7026
Eric Laurentcf2c0212014-07-25 16:20:43 -07007027 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307028 ALOGW("%s could not open input for device %s on profile %s", __func__,
7029 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007030 profiles.removeAt(profile_index);
7031 profile_index--;
7032 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007033 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007034 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007035 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307036 ALOGV("%s: adding input %d for profile %s", __func__,
7037 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007038
7039 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307040 ALOGV("%s: closing input %d for profile %s", __func__,
7041 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007042 closeInput(input);
7043 }
Eric Laurentd4692962014-05-05 18:13:44 -07007044 }
7045 } // end scan profiles
7046
7047 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007048 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007049 return BAD_VALUE;
7050 }
7051 } else {
7052 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007053 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007054 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007055 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007056 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007057 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007058 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007059 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307060 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7061 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007062 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007063 }
7064 }
7065 }
7066 } // end disconnect
7067
7068 return NO_ERROR;
7069}
7070
7071
Eric Laurente0720872014-03-11 09:30:41 -07007072void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007073{
7074 ALOGV("closeOutput(%d)", output);
7075
François Gaffie1c878552018-11-22 16:53:21 +01007076 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7077 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007078 ALOGW("closeOutput() unknown output %d", output);
7079 return;
7080 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007081 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007082 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007083
Eric Laurente552edb2014-03-10 17:42:56 -07007084 // look for duplicated outputs connected to the output being removed.
7085 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007086 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7087 if (dupOutput->isDuplicated() &&
7088 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7089 sp<SwAudioOutputDescriptor> remainingOutput =
7090 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007091 // As all active tracks on duplicated output will be deleted,
7092 // and as they were also referenced on the other output, the reference
7093 // count for their stream type must be adjusted accordingly on
7094 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007095 const bool wasActive = remainingOutput->isActive();
7096 // Note: no-op on the closing output where all clients has already been set inactive
7097 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007098 // stop() will be a no op if the output is still active but is needed in case all
7099 // active streams refcounts where cleared above
7100 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007101 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007102 }
Eric Laurente552edb2014-03-10 17:42:56 -07007103 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7104 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7105
7106 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007107 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007108 }
7109 }
7110
Eric Laurent05b90f82014-08-27 15:32:29 -07007111 nextAudioPortGeneration();
7112
François Gaffie1c878552018-11-22 16:53:21 +01007113 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007114 if (index >= 0) {
7115 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007116 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7117 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007118 mAudioPatches.removeItemsAt(index);
7119 mpClientInterface->onAudioPatchListUpdate();
7120 }
7121
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007122 if (closingOutputWasActive) {
7123 closingOutput->stop();
7124 }
François Gaffie1c878552018-11-22 16:53:21 +01007125 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007126 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007127 for (const auto device : closingOutput->devices()) {
7128 device->setPreferredConfig(nullptr);
7129 }
7130 }
Eric Laurente552edb2014-03-10 17:42:56 -07007131
François Gaffie53615e22015-03-19 09:24:12 +01007132 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007133 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007134 if (closingOutput == mSpatializerOutput) {
7135 mSpatializerOutput.clear();
7136 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007137
7138 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7139 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007140 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007141 bool directOutputOpen = false;
7142 for (size_t i = 0; i < mOutputs.size(); i++) {
7143 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7144 directOutputOpen = true;
7145 break;
7146 }
7147 }
7148 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007149 ALOGV("no direct outputs open, reset MSD patches");
7150 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7151 // how output devices for patching are resolved. Avoid by caching and reusing the
7152 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7153 // devices to patch to. This may be complicated by the fact that devices may become
7154 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007155 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007156 }
7157 }
jiabin220eea12024-05-17 17:55:20 +00007158
7159 if (closingOutput->mPreferredAttrInfo != nullptr) {
7160 closingOutput->mPreferredAttrInfo->resetActiveClient();
7161 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007162}
7163
7164void AudioPolicyManager::closeInput(audio_io_handle_t input)
7165{
7166 ALOGV("closeInput(%d)", input);
7167
7168 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7169 if (inputDesc == NULL) {
7170 ALOGW("closeInput() unknown input %d", input);
7171 return;
7172 }
7173
Eric Laurent6a94d692014-05-20 11:18:06 -07007174 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007175
François Gaffie11d30102018-11-02 16:09:09 +01007176 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007177 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007178 if (index >= 0) {
7179 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007180 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7181 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007182 mAudioPatches.removeItemsAt(index);
7183 mpClientInterface->onAudioPatchListUpdate();
7184 }
7185
François Gaffie6ebbce02023-07-19 13:27:53 +02007186 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007187 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007188 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007189
François Gaffie11d30102018-11-02 16:09:09 +01007190 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7191 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007192 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007193 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007194 }
Eric Laurente552edb2014-03-10 17:42:56 -07007195}
7196
François Gaffie11d30102018-11-02 16:09:09 +01007197SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7198 const DeviceVector &devices,
7199 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007200{
7201 SortedVector<audio_io_handle_t> outputs;
7202
François Gaffie11d30102018-11-02 16:09:09 +01007203 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007204 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007205 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007206 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007207 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007208 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007209 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007210 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007211 outputs.add(openOutputs.keyAt(i));
7212 }
7213 }
7214 return outputs;
7215}
7216
Mikhail Naganov37977152018-07-11 15:54:44 -07007217void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7218{
7219 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7220 // output is suspended before any tracks are moved to it
7221 checkA2dpSuspend();
7222 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007223 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007224 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007225 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007226 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007227 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7228 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7229 // configuration changes will ultimately be rerouted correctly. We can still avoid
7230 // unnecessary rerouting by caching and reusing the arguments to
7231 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7232 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007233 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007234 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007235 // an event that changed routing likely occurred, inform upper layers
7236 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007237}
7238
François Gaffiec005e562018-11-06 15:04:49 +01007239bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7240 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007241{
François Gaffiec005e562018-11-06 15:04:49 +01007242 return mEngine->getProductStrategyForAttributes(lAttr) ==
7243 mEngine->getProductStrategyForAttributes(rAttr);
7244}
7245
Francois Gaffieff1eb522020-05-06 18:37:04 +02007246void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7247{
7248 for (size_t i = 0; i < mAudioSources.size(); i++) {
7249 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7250 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007251 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007252 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007253 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007254 }
7255 }
7256}
7257
7258void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7259{
7260 for (size_t i = 0; i < mAudioSources.size(); i++) {
7261 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7262 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7263 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7264 disconnectAudioSource(sourceDesc);
7265 }
7266 }
7267}
7268
François Gaffiec005e562018-11-06 15:04:49 +01007269void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7270{
7271 auto psId = mEngine->getProductStrategyForAttributes(attr);
7272
7273 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7274 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007275
François Gaffie11d30102018-11-02 16:09:09 +01007276 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7277 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007278
Eric Laurentc209fe42020-06-05 18:11:23 -07007279 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007280 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007281 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007282 // take into account dynamic audio policies related changes: if a client is now associated
7283 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007284 // invalidate clients on outputs that do not support all the newly selected devices for the
7285 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007286 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007287 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007288 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007289 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007290 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007291
Eric Laurentc209fe42020-06-05 18:11:23 -07007292 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7293 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7294 continue;
7295 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007296 if (!desc->supportsAllDevices(newDevices)) {
7297 invalidatedOutputs.push_back(desc);
7298 break;
7299 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007300 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007301 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007302 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7303 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7304 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007305 if (status == OK) {
7306 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7307 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7308 maxLatency = desc->latency();
7309 }
7310 invalidatedOutputs.push_back(desc);
7311 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007312 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007313 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007314 }
7315 }
7316
Eric Laurent56ed8842022-11-15 16:04:41 +01007317 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007318 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7319 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007320 for (audio_io_handle_t srcOut : srcOutputs) {
7321 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007322 if (desc == nullptr) continue;
7323
7324 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007325 maxLatency = desc->latency();
7326 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007327
Eric Laurent56ed8842022-11-15 16:04:41 +01007328 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007329 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007330 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007331 // a client on a non direct outputs has necessarily a linear PCM format
7332 // so we can call selectOutput() safely
7333 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7334 client->flags(),
7335 client->config().format,
7336 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007337 client->config().sample_rate,
7338 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007339 if (newOutput != srcOut) {
7340 invalidate = true;
7341 break;
7342 }
7343 } else {
7344 sp<IOProfile> profile = getProfileForOutput(newDevices,
7345 client->config().sample_rate,
7346 client->config().format,
7347 client->config().channel_mask,
7348 client->flags(),
7349 true /* directOnly */);
7350 if (profile != desc->mProfile) {
7351 invalidate = true;
7352 break;
7353 }
7354 }
7355 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007356 // mute strategy while moving tracks from one output to another
7357 if (invalidate) {
7358 invalidatedOutputs.push_back(desc);
7359 if (desc->isStrategyActive(psId)) {
7360 setStrategyMute(psId, true, desc);
7361 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7362 newDevices.types());
7363 }
Eric Laurente552edb2014-03-10 17:42:56 -07007364 }
François Gaffiec005e562018-11-06 15:04:49 +01007365 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007366 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007367 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007368 }
Eric Laurente552edb2014-03-10 17:42:56 -07007369 }
7370
Eric Laurent56ed8842022-11-15 16:04:41 +01007371 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7372 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7373 std::to_string(srcOutputs[0]).c_str(),
7374 std::to_string(dstOutputs[0]).c_str());
7375
François Gaffiec005e562018-11-06 15:04:49 +01007376 // Move effects associated to this stream from previous output to new output
7377 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007378 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007379 }
François Gaffiec005e562018-11-06 15:04:49 +01007380 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007381 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007382 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007383 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007384 desc->setTracksInvalidatedStatusByStrategy(psId);
7385 }
Eric Laurente552edb2014-03-10 17:42:56 -07007386 }
7387 }
7388}
7389
Eric Laurente0720872014-03-11 09:30:41 -07007390void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007391{
François Gaffiec005e562018-11-06 15:04:49 +01007392 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7393 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7394 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007395 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007396 }
Eric Laurente552edb2014-03-10 17:42:56 -07007397}
7398
Kevin Rocard153f92d2018-12-18 18:33:28 -08007399void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007400 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007401 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007402 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007403 for (size_t i = 0; i < mOutputs.size(); i++) {
7404 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7405 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007406 sp<AudioPolicyMix> primaryMix;
7407 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007408 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007409 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7410 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7411 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007412 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7413 for (auto &secondaryMix : secondaryMixes) {
7414 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7415 if (outputDesc != nullptr &&
7416 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7417 secondaryDescs.push_back(outputDesc);
7418 }
7419 }
7420
jiabinc44b3462022-12-08 12:52:31 -08007421 if (status != OK &&
7422 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7423 // When it failed to query secondary output, only invalidate the client that is not
7424 // MMAP. The reason is that MMAP stream will not support secondary output.
7425 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007426 } else if (!std::equal(
7427 client->getSecondaryOutputs().begin(),
7428 client->getSecondaryOutputs().end(),
7429 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungced57302024-08-14 11:37:57 -07007430 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7431 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007432 // If the format is not PCM, the tracks should be invalidated to get correct
7433 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007434 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007435 } else {
7436 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7437 std::vector<audio_io_handle_t> secondaryOutputIds;
7438 for (const auto &secondaryDesc: secondaryDescs) {
7439 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7440 weakSecondaryDescs.push_back(secondaryDesc);
7441 }
7442 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7443 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007444 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007445 }
7446 }
7447 }
jiabin10a03f12021-05-07 23:46:28 +00007448 if (!trackSecondaryOutputs.empty()) {
7449 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7450 }
jiabinc44b3462022-12-08 12:52:31 -08007451 if (!clientsToInvalidate.empty()) {
7452 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7453 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007454 }
7455}
7456
Eric Laurent2517af32020-11-25 15:31:27 +01007457bool AudioPolicyManager::isScoRequestedForComm() const {
7458 AudioDeviceTypeAddrVector devices;
7459 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7460 for (const auto &device : devices) {
7461 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7462 return true;
7463 }
7464 }
7465 return false;
7466}
7467
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007468bool AudioPolicyManager::isHearingAidUsedForComm() const {
7469 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7470 true /*fromCache*/);
7471 for (const auto &device : devices) {
7472 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7473 return true;
7474 }
7475 }
7476 return false;
7477}
7478
7479
Eric Laurente0720872014-03-11 09:30:41 -07007480void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007481{
François Gaffie53615e22015-03-19 09:24:12 +01007482 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007483 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007484 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007485 return;
7486 }
7487
Eric Laurent3a4311c2014-03-17 12:00:47 -07007488 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007489 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7490 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007491 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007492
7493 // if suspended, restore A2DP output if:
7494 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007495 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007496 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007497 //
Eric Laurentf732e072016-08-03 19:30:28 -07007498 // if not suspended, suspend A2DP output if:
7499 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007500 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007501 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007502 //
7503 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007504 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007505 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007506 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007507 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007508
7509 mpClientInterface->restoreOutput(a2dpOutput);
7510 mA2dpSuspended = false;
7511 }
7512 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007513 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007514 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007515 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007516 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007517
7518 mpClientInterface->suspendOutput(a2dpOutput);
7519 mA2dpSuspended = true;
7520 }
7521 }
7522}
7523
François Gaffie11d30102018-11-02 16:09:09 +01007524DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7525 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007526{
François Gaffiedb1755b2023-09-01 11:50:35 +02007527 if (outputDesc == nullptr) {
7528 return DeviceVector{};
7529 }
François Gaffie11d30102018-11-02 16:09:09 +01007530
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007531 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007532 if (index >= 0) {
7533 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007534 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007535 ALOGV("%s device %s forced by patch %d", __func__,
7536 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7537 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007538 }
7539 }
7540
Dean Wheatley514b4312020-06-17 21:45:00 +10007541 // Do not retrieve engine device for outputs through MSD
7542 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7543 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7544 return outputDesc->devices();
7545 }
7546
Eric Laurent97ac8712018-07-27 18:59:02 -07007547 // Honor explicit routing requests only if no client using default routing is active on this
7548 // input: a specific app can not force routing for other apps by setting a preferred device.
7549 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007550 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007551 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007552 if (device != nullptr) {
7553 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007554 }
7555
François Gaffiea807ef92018-11-05 10:44:33 +01007556 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7557 // of setForceUse / Default Bus device here
7558 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7559 if (device != nullptr) {
7560 return DeviceVector(device);
7561 }
7562
François Gaffiedb1755b2023-09-01 11:50:35 +02007563 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007564 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7565 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307566 auto hasStreamActive = [&](auto stream) {
7567 return hasStream(streams, stream) && isStreamActive(stream, 0);
7568 };
Eric Laurent484e9272018-06-07 17:29:23 -07007569
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307570 auto doGetOutputDevicesForVoice = [&]() {
7571 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007572 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307573 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007574 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7575 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307576 };
7577
7578 // With low-latency playing on speaker, music on WFD, when the first low-latency
7579 // output is stopped, getNewOutputDevices checks for a product strategy
7580 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007581 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307582 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7583 // stream is associated to the output descriptor.
7584 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7585 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7586 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7587 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007588 // Retrieval of devices for voice DL is done on primary output profile, cannot
7589 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007590 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007591 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7592 break;
7593 }
Eric Laurente552edb2014-03-10 17:42:56 -07007594 }
François Gaffiec005e562018-11-06 15:04:49 +01007595 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007596 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007597}
7598
François Gaffie11d30102018-11-02 16:09:09 +01007599sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7600 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007601{
François Gaffie11d30102018-11-02 16:09:09 +01007602 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007603
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007604 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007605 if (index >= 0) {
7606 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007607 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007608 ALOGV("getNewInputDevice() device %s forced by patch %d",
7609 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7610 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007611 }
7612 }
7613
Eric Laurent97ac8712018-07-27 18:59:02 -07007614 // Honor explicit routing requests only if no client using default routing is active on this
7615 // input: a specific app can not force routing for other apps by setting a preferred device.
7616 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007617 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7618 if (device != nullptr) {
7619 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007620 }
7621
Eric Laurentdc95a252018-04-12 12:46:56 -07007622 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007623 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007624 audio_attributes_t attributes;
7625 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007626 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007627 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7628 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007629 attributes = topClient->attributes();
7630 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007631 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007632 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007633 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7634 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007635 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007636 }
7637
Francois Gaffie716e1432019-01-14 16:58:59 +01007638 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7639 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007640 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007641 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007642 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007643 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007644
Eric Laurente552edb2014-03-10 17:42:56 -07007645 return device;
7646}
7647
Eric Laurent794fde22016-03-11 09:50:45 -08007648bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7649 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007650 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007651}
7652
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007653status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007654 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007655 if (devices == nullptr) {
7656 return BAD_VALUE;
7657 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007658
Andy Hung6d23c0f2022-02-16 09:37:15 -08007659 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007660 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7661 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007662 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007663 for (const auto& device : curDevices) {
7664 devices->push_back(device->getDeviceTypeAddr());
7665 }
7666 return NO_ERROR;
7667}
7668
Eric Laurente0720872014-03-11 09:30:41 -07007669void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007670 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007671 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007672 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007673 updateDevicesAndOutputs();
7674 break;
7675 default:
7676 break;
7677 }
7678}
7679
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007680uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007681
7682 // skip beacon mute management if a dedicated TTS output is available
7683 if (mTtsOutputAvailable) {
7684 return 0;
7685 }
7686
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007687 switch(event) {
7688 case STARTING_OUTPUT:
7689 mBeaconMuteRefCount++;
7690 break;
7691 case STOPPING_OUTPUT:
7692 if (mBeaconMuteRefCount > 0) {
7693 mBeaconMuteRefCount--;
7694 }
7695 break;
7696 case STARTING_BEACON:
7697 mBeaconPlayingRefCount++;
7698 break;
7699 case STOPPING_BEACON:
7700 if (mBeaconPlayingRefCount > 0) {
7701 mBeaconPlayingRefCount--;
7702 }
7703 break;
7704 }
7705
7706 if (mBeaconMuteRefCount > 0) {
7707 // any playback causes beacon to be muted
7708 return setBeaconMute(true);
7709 } else {
7710 // no other playback: unmute when beacon starts playing, mute when it stops
7711 return setBeaconMute(mBeaconPlayingRefCount == 0);
7712 }
7713}
7714
7715uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7716 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7717 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7718 // keep track of muted state to avoid repeating mute/unmute operations
7719 if (mBeaconMuted != mute) {
7720 // mute/unmute AUDIO_STREAM_TTS on all outputs
7721 ALOGV("\t muting %d", mute);
7722 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007723 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7724 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7725 ALOGV("\t no tts volume source available");
7726 return 0;
7727 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007728 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007729 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007730 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007731 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007732 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007733 maxLatency = latency;
7734 }
7735 }
7736 mBeaconMuted = mute;
7737 return maxLatency;
7738 }
7739 return 0;
7740}
7741
Eric Laurente0720872014-03-11 09:30:41 -07007742void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007743{
François Gaffiec005e562018-11-06 15:04:49 +01007744 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007745 mPreviousOutputs = mOutputs;
7746}
7747
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007748uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007749 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007750 uint32_t delayMs)
7751{
7752 // mute/unmute strategies using an incompatible device combination
7753 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7754 // if unmuting, unmute only after the specified delay
7755 if (outputDesc->isDuplicated()) {
7756 return 0;
7757 }
7758
7759 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007760 DeviceVector devices = outputDesc->devices();
7761 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007762
François Gaffiec005e562018-11-06 15:04:49 +01007763 auto productStrategies = mEngine->getOrderedProductStrategies();
7764 for (const auto &productStrategy : productStrategies) {
7765 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7766 DeviceVector curDevices =
7767 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7768 curDevices = curDevices.filter(outputDesc->supportedDevices());
7769 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007770 bool doMute = false;
7771
François Gaffiec005e562018-11-06 15:04:49 +01007772 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007773 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007774 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7775 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007776 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007777 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007778 }
Eric Laurent99401132014-05-07 19:48:15 -07007779 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007780 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007781 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007782 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007783 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007784 continue;
7785 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307786 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007787 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7788 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7789 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007790 if (mute) {
7791 // FIXME: should not need to double latency if volume could be applied
7792 // immediately by the audioflinger mixer. We must account for the delay
7793 // between now and the next time the audioflinger thread for this output
7794 // will process a buffer (which corresponds to one buffer size,
7795 // usually 1/2 or 1/4 of the latency).
7796 if (muteWaitMs < desc->latency() * 2) {
7797 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007798 }
7799 }
7800 }
7801 }
7802 }
7803 }
7804
Eric Laurent99401132014-05-07 19:48:15 -07007805 // temporary mute output if device selection changes to avoid volume bursts due to
7806 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007807 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007808 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007809
Eric Laurentdc462862016-07-19 12:29:53 -07007810 if (muteWaitMs < tempMuteWaitMs) {
7811 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007812 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007813
7814 // If recommended duration is defined, replace temporary mute duration to avoid
7815 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7816 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7817 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7818 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7819 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7820
François Gaffieaaac0fd2018-11-22 17:56:39 +01007821 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7822 // make sure that we do not start the temporary mute period too early in case of
7823 // delayed device change
7824 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7825 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007826 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007827 }
7828 }
7829
Eric Laurente552edb2014-03-10 17:42:56 -07007830 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7831 if (muteWaitMs > delayMs) {
7832 muteWaitMs -= delayMs;
7833 usleep(muteWaitMs * 1000);
7834 return muteWaitMs;
7835 }
7836 return 0;
7837}
7838
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307839uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7840 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007841 const DeviceVector &devices,
7842 bool force,
7843 int delayMs,
7844 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007845 bool requiresMuteCheck, bool requiresVolumeCheck,
7846 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007847{
jiabin3ff8d7d2022-12-13 06:27:44 +00007848 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307849 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7850 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7851 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007852 uint32_t muteWaitMs;
7853
7854 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307855 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007856 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307857 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007858 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007859 return muteWaitMs;
7860 }
Eric Laurente552edb2014-03-10 17:42:56 -07007861
7862 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007863 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007864 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007865 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007866
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307867 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7868 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007869
7870 if (!filteredDevices.isEmpty()) {
7871 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007872 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007873
7874 // if the outputs are not materially active, there is no need to mute.
7875 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007876 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007877 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307878 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7879 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007880 muteWaitMs = 0;
7881 }
Eric Laurente552edb2014-03-10 17:42:56 -07007882
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007883 bool outputRouted = outputDesc->isRouted();
7884
Eric Laurent79ea9582020-06-11 18:49:24 -07007885 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7886 // output profile or if new device is not supported AND previous device(s) is(are) still
7887 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007888 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307889 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7890 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007891 // restore previous device after evaluating strategy mute state
7892 outputDesc->setDevices(prevDevices);
7893 return muteWaitMs;
7894 }
7895
Eric Laurente552edb2014-03-10 17:42:56 -07007896 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007897 // the requested device is AUDIO_DEVICE_NONE
7898 // OR the requested device is the same as current device
7899 // AND force is not specified
7900 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007901 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007902 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307903 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7904 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7905 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007906 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307907 ALOGV("%s %s setting same device on routed output, force apply volumes",
7908 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007909 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7910 }
Eric Laurente552edb2014-03-10 17:42:56 -07007911 return muteWaitMs;
7912 }
7913
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307914 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7915 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007916
Eric Laurente552edb2014-03-10 17:42:56 -07007917 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007918 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007919 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007920 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007921 PatchBuilder patchBuilder;
7922 patchBuilder.addSource(outputDesc);
7923 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7924 for (const auto &filteredDevice : filteredDevices) {
7925 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007926 }
7927
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007928 // Add half reported latency to delayMs when muteWaitMs is null in order
7929 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007930 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7931 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7932 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007933 }
Eric Laurente552edb2014-03-10 17:42:56 -07007934
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007935 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7936 if (!skipMuteDelay) {
7937 // update stream volumes according to new device
7938 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7939 }
Eric Laurente552edb2014-03-10 17:42:56 -07007940
7941 return muteWaitMs;
7942}
7943
Eric Laurentc75307b2015-03-17 15:29:32 -07007944status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007945 int delayMs,
7946 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007947{
Eric Laurent6a94d692014-05-20 11:18:06 -07007948 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007949 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7950 return INVALID_OPERATION;
7951 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007952 if (patchHandle) {
7953 index = mAudioPatches.indexOfKey(*patchHandle);
7954 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007955 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007956 }
7957 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007958 return INVALID_OPERATION;
7959 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007960 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007961 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007962 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007963 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007964 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007965 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007966 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007967 return status;
7968}
7969
7970status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007971 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007972 bool force,
7973 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007974{
7975 status_t status = NO_ERROR;
7976
Eric Laurent1f2f2232014-06-02 12:01:23 -07007977 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007978 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7979 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007980
François Gaffie11d30102018-11-02 16:09:09 +01007981 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007982 PatchBuilder patchBuilder;
7983 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007984 // AUDIO_SOURCE_HOTWORD is for internal use only:
7985 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007986 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7987 auto result = usecase;
7988 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7989 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7990 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10007991 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07007992 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10007993 if (audio_is_remote_submix_device(device->type())) {
7994 // remote submix HAL does not support audio conversion, need source device
7995 // audio config to match the sink input descriptor audio config, otherwise AIDL
7996 // HAL patching will fail
7997 audio_port_config srcDevicePortConfig = {};
7998 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
7999 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8000 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8001 srcDevicePortConfig.format = inputDesc->getFormat();
8002 patchBuilder.addSource(srcDevicePortConfig);
8003 } else {
8004 patchBuilder.addSource(device);
8005 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008006 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008007 }
8008 }
8009 return status;
8010}
8011
Eric Laurent6a94d692014-05-20 11:18:06 -07008012status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8013 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008014{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008015 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008016 ssize_t index;
8017 if (patchHandle) {
8018 index = mAudioPatches.indexOfKey(*patchHandle);
8019 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008020 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008021 }
8022 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008023 return INVALID_OPERATION;
8024 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008025 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008026 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008027 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008028 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008029 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008030 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008031 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008032 return status;
8033}
8034
François Gaffie11d30102018-11-02 16:09:09 +01008035sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008036 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008037 audio_format_t& format,
8038 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008039 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008040{
8041 // Choose an input profile based on the requested capture parameters: select the first available
8042 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008043 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008044
Atneya Nair0f0a8032022-12-12 16:20:12 -08008045 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8046 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8047 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8048
8049 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008050
jiabin2fd710d2022-05-02 23:20:22 +00008051 for (;;) {
8052 sp<IOProfile> firstInexact = nullptr;
8053 uint32_t updatedSamplingRate = 0;
8054 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8055 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8056 for (const auto& hwModule : mHwModules) {
8057 for (const auto& profile : hwModule->getInputProfiles()) {
8058 // profile->log();
8059 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008060 if (profile->getCompatibilityScore(
8061 DeviceVector(device),
8062 samplingRate,
8063 &updatedSamplingRate,
8064 format,
8065 &updatedFormat,
8066 channelMask,
8067 &updatedChannelMask,
8068 // FIXME ugly cast
8069 (audio_output_flags_t) flags,
8070 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8071 samplingRate = updatedSamplingRate;
8072 format = updatedFormat;
8073 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008074 return profile;
8075 }
jiabin66acc432024-02-06 00:57:36 +00008076 if (firstInexact == nullptr
8077 && profile->getCompatibilityScore(
8078 DeviceVector(device),
8079 samplingRate,
8080 &updatedSamplingRate,
8081 format,
8082 &updatedFormat,
8083 channelMask,
8084 &updatedChannelMask,
8085 // FIXME ugly cast
8086 (audio_output_flags_t) flags,
8087 false /*exactMatchRequiredForInputFlags*/)
8088 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008089 firstInexact = profile;
8090 }
8091 }
8092 }
8093
8094 if (firstInexact != nullptr) {
8095 samplingRate = updatedSamplingRate;
8096 format = updatedFormat;
8097 channelMask = updatedChannelMask;
8098 return firstInexact;
8099 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8100 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8101 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8102 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8103 flags = AUDIO_INPUT_FLAG_NONE;
8104 } else { // fail
8105 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8106 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8107 samplingRate, format, channelMask, oriFlags);
8108 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008109 }
8110 }
jiabin2fd710d2022-05-02 23:20:22 +00008111
8112 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008113}
8114
Vlad Popa87e0e582024-05-20 18:49:20 -07008115float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8116 VolumeSource volumeSource,
8117 int index,
8118 const DeviceTypeSet &deviceTypes)
8119{
8120 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8121 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8122 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8123
8124 if (com_android_media_audio_abs_volume_index_fix()) {
8125 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8126 mAbsoluteVolumeDrivingStreams.end()) {
8127 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8128 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8129 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8130 ALOGD("%s: no group matching with %s", __FUNCTION__,
8131 toString(attributesToDriveAbs).c_str());
8132 return volumeDb;
8133 }
8134
8135 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8136 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8137 if (vsToDriveAbs == volumeSource) {
8138 // attenuation is applied by the abs volume controller
8139 return volumeDbMax;
8140 } else {
8141 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8142 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8143 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8144 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8145 curvesAbs.getVolumeIndexMax());
8146 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8147 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8148 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8149 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8150 return newVolumeDb;
8151 }
8152 }
8153 return volumeDb;
8154 } else {
8155 return volumeDb;
8156 }
8157}
8158
François Gaffieaaac0fd2018-11-22 17:56:39 +01008159float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8160 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008161 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008162 const DeviceTypeSet& deviceTypes,
8163 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008164{
Vlad Popa87e0e582024-05-20 18:49:20 -07008165 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008166 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8167 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8168
8169 if (!computeInternalInteraction) {
8170 return volumeDb;
8171 }
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008172
8173 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8174 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8175 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8176 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008177 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8178 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8179 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8180 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8181 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008182 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008183 mOutputs.isActive(ringVolumeSrc, 0)) {
8184 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008185 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8186 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008187 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008188 }
8189
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008190 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008191 if ((volumeSource != callVolumeSrc && (isInCall() ||
8192 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008193 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008194 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8195 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008196 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8197 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8198 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008199 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008200 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008201 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008202 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008203 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8204 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008205 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008206 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8207 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8208 // programmatically muted.
8209 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8210 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8211 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008212 bool exemptFromCapping =
8213 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8214 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008215 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8216 volumeSource, volumeDb);
8217 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008218 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8219 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8220 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008221 }
8222 }
Eric Laurente552edb2014-03-10 17:42:56 -07008223 // if a headset is connected, apply the following rules to ring tones and notifications
8224 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008225 // - always attenuate notifications volume by 6dB
8226 // - attenuate ring tones volume by 6dB unless music is not playing and
8227 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008228 // - if music is playing, always limit the volume to current music volume,
8229 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008230 if (!Intersection(deviceTypes,
8231 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8232 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008233 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8234 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008235 ((volumeSource == alarmVolumeSrc ||
8236 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008237 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8238 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8239 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008240 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8241 curves.canBeMuted()) {
8242
Eric Laurente552edb2014-03-10 17:42:56 -07008243 // when the phone is ringing we must consider that music could have been paused just before
8244 // by the music application and behave as if music was active if the last music track was
8245 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008246 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8247 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008248 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008249 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008250 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8251 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008252 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008253 float musicVolDb = computeVolume(musicCurves,
8254 musicVolumeSrc,
8255 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008256 musicDevice,
8257 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008258 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8259 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8260 if (volumeDb > minVolDb) {
8261 volumeDb = minVolDb;
8262 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008263 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008264 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8265 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008266 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8267 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8268 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8269 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008270 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008271 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008272 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8273 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008274 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8275 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008276 }
8277 }
jiabin9a3361e2019-10-01 09:38:30 -07008278 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008279 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008280 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008281 }
8282 }
8283
François Gaffie43c73442018-11-08 08:21:55 +01008284 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008285}
8286
Eric Laurent3839bc02018-07-10 18:33:34 -07008287int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008288 VolumeSource fromVolumeSource,
8289 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008290{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008291 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008292 return srcIndex;
8293 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008294 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8295 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008296 float minSrc = (float)srcCurves.getVolumeIndexMin();
8297 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8298 float minDst = (float)dstCurves.getVolumeIndexMin();
8299 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008300
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008301 // preserve mute request or correct range
8302 if (srcIndex < minSrc) {
8303 if (srcIndex == 0) {
8304 return 0;
8305 }
8306 srcIndex = minSrc;
8307 } else if (srcIndex > maxSrc) {
8308 srcIndex = maxSrc;
8309 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008310 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8311}
8312
François Gaffieaaac0fd2018-11-22 17:56:39 +01008313status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8314 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008315 int index,
8316 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008317 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008318 int delayMs,
8319 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008320{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008321 // APM is single threaded, and single instance.
8322 static std::set<IVolumeCurves*> invalidCurvesReported;
8323
François Gaffieaaac0fd2018-11-22 17:56:39 +01008324 // do not change actual attributes volume if the attributes is muted
8325 if (outputDesc->isMuted(volumeSource)) {
8326 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8327 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008328 return NO_ERROR;
8329 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008330
Eric Laurent5baf07c2024-01-11 16:57:27 +00008331 bool isVoiceVolSrc;
8332 bool isBtScoVolSrc;
8333 if (!isVolumeConsistentForCalls(
8334 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008335 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008336 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008337 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008338 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008339
jiabin9a3361e2019-10-01 09:38:30 -07008340 if (deviceTypes.empty()) {
8341 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008342 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008343 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008344 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008345 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008346
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008347 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008348 if (!invalidCurvesReported.count(&curves)) {
8349 invalidCurvesReported.insert(&curves);
8350 String8 dump;
8351 curves.dump(&dump);
8352 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8353 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008354 return BAD_VALUE;
8355 }
8356
jiabin9a3361e2019-10-01 09:38:30 -07008357 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8358 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008359 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008360 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008361 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8362 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008363 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008364 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008365 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008366 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8367 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008368
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008369 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008370 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8371 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8372 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008373 }
Eric Laurente552edb2014-03-10 17:42:56 -07008374 return NO_ERROR;
8375}
8376
Eric Laurent5baf07c2024-01-11 16:57:27 +00008377void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008378 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008379 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008380 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008381 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008382 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008383 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8384 } else {
8385 voiceVolume = index == 0 ? 0.0 : 1.0;
8386 }
8387 if (voiceVolume != mLastVoiceVolume) {
8388 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8389 mLastVoiceVolume = voiceVolume;
8390 }
8391}
8392
8393bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8394 const DeviceTypeSet& deviceTypes,
8395 bool& isVoiceVolSrc,
8396 bool& isBtScoVolSrc,
8397 const char* caller) {
8398 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8399 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8400 const bool isScoRequested = isScoRequestedForComm();
8401 const bool isHAUsed = isHearingAidUsedForComm();
8402
8403 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8404 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8405
8406 if ((callVolSrc != btScoVolSrc) &&
8407 ((isVoiceVolSrc && isScoRequested) ||
8408 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8409 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8410 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8411 volumeSource, isScoRequested ? " " : " not ");
8412 return false;
8413 }
8414 return true;
8415}
8416
Eric Laurentc75307b2015-03-17 15:29:32 -07008417void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008418 const DeviceTypeSet& deviceTypes,
8419 int delayMs,
8420 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008421{
jiabincd510522020-01-22 09:40:55 -08008422 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008423 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8424 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8425 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008426 curves.getVolumeIndex(deviceTypes),
8427 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008428 }
8429}
8430
François Gaffiec005e562018-11-06 15:04:49 +01008431void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
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{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008437 std::vector<VolumeSource> sourcesToMute;
8438 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8439 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8440 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008441 VolumeSource source = toVolumeSource(attributes, false);
8442 if ((source != VOLUME_SOURCE_NONE) &&
8443 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8444 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008445 sourcesToMute.push_back(source);
8446 }
Eric Laurente552edb2014-03-10 17:42:56 -07008447 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008448 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008449 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008450 }
8451
Eric Laurente552edb2014-03-10 17:42:56 -07008452}
8453
François Gaffieaaac0fd2018-11-22 17:56:39 +01008454void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8455 bool on,
8456 const sp<AudioOutputDescriptor>& outputDesc,
8457 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008458 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008459{
jiabin9a3361e2019-10-01 09:38:30 -07008460 if (deviceTypes.empty()) {
8461 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008462 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008463 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008464 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008465 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008466 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008467 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008468 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8469 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008470 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008471 }
8472 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008473 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8474 // ignored
8475 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008476 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008477 if (!outputDesc->isMuted(volumeSource)) {
8478 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008479 return;
8480 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008481 if (outputDesc->decMuteCount(volumeSource) == 0) {
8482 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008483 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008484 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008485 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008486 delayMs);
8487 }
8488 }
8489}
8490
François Gaffie53615e22015-03-19 09:24:12 +01008491bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8492{
François Gaffiec005e562018-11-06 15:04:49 +01008493 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008494 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8495 return true;
8496 }
8497
8498 // has known usage?
8499 switch (paa->usage) {
8500 case AUDIO_USAGE_UNKNOWN:
8501 case AUDIO_USAGE_MEDIA:
8502 case AUDIO_USAGE_VOICE_COMMUNICATION:
8503 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8504 case AUDIO_USAGE_ALARM:
8505 case AUDIO_USAGE_NOTIFICATION:
8506 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8507 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8508 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8509 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8510 case AUDIO_USAGE_NOTIFICATION_EVENT:
8511 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8512 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8513 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8514 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008515 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008516 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008517 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008518 case AUDIO_USAGE_EMERGENCY:
8519 case AUDIO_USAGE_SAFETY:
8520 case AUDIO_USAGE_VEHICLE_STATUS:
8521 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008522 break;
8523 default:
8524 return false;
8525 }
8526 return true;
8527}
8528
François Gaffie2110e042015-03-24 08:41:51 +01008529audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8530{
8531 return mEngine->getForceUse(usage);
8532}
8533
Eric Laurent96d1dda2022-03-14 17:14:19 +01008534bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008535 return isStateInCall(mEngine->getPhoneState());
8536}
8537
Eric Laurent96d1dda2022-03-14 17:14:19 +01008538bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008539 return is_state_in_call(state);
8540}
8541
Eric Laurentf9cccec2022-11-16 19:12:00 +01008542bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008543 audio_mode_t mode = mEngine->getPhoneState();
8544 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008545 || (mode == AUDIO_MODE_CALL_SCREEN)
8546 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008547}
8548
Eric Laurentf9cccec2022-11-16 19:12:00 +01008549bool AudioPolicyManager::isInCallOrScreening() const {
8550 audio_mode_t mode = mEngine->getPhoneState();
8551 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8552}
8553
Eric Laurentd60560a2015-04-10 11:31:20 -07008554void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8555{
8556 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008557 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008558 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008559 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008560 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008561 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008562 }
8563 }
8564
8565 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8566 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8567 bool release = false;
8568 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8569 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8570 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8571 source->ext.device.type == deviceDesc->type()) {
8572 release = true;
8573 }
8574 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008575 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008576 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8577 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8578 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008579 sink->ext.device.type == deviceDesc->type() &&
8580 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8581 || strncmp(sink->ext.device.address, address,
8582 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008583 release = true;
8584 }
8585 }
8586 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008587 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8588 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008589 }
8590 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008591
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008592 mInputs.clearSessionRoutesForDevice(deviceDesc);
8593
Francois Gaffie716e1432019-01-14 16:58:59 +01008594 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008595}
8596
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008597void AudioPolicyManager::modifySurroundFormats(
8598 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008599 std::unordered_set<audio_format_t> enforcedSurround(
8600 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008601 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008602 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008603 allSurround.insert(pair.first);
8604 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8605 }
Phil Burk09bc4612016-02-24 15:58:15 -08008606
8607 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8608 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008609 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008610 // This is the resulting set of formats depending on the surround mode:
8611 // 'all surround' = allSurround
8612 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8613 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8614 // 'manual surround' = mManualSurroundFormats
8615 // AUTO: formats v 'enforced surround'
8616 // ALWAYS: formats v 'all surround' v 'enforced surround'
8617 // NEVER: formats ^ 'non-surround'
8618 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008619
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008620 std::unordered_set<audio_format_t> formatSet;
8621 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8622 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008623 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008624 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008625 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008626 formatSet.insert(*formatIter);
8627 }
8628 }
8629 } else {
8630 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8631 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008632 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008633
jiabin81772902018-04-02 17:52:27 -07008634 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008635 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008636 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8637 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8638 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008639 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008640 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8641 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8642 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008643 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008644 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008645 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008646 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008647 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008648 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008649}
8650
jiabin06e4bab2019-07-29 10:13:34 -07008651void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8652 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008653 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8654 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8655
8656 // If NEVER, then remove support for channelMasks > stereo.
8657 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008658 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8659 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008660 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008661 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008662 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008663 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008664 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008665 }
8666 }
jiabin81772902018-04-02 17:52:27 -07008667 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8668 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8669 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008670 bool supports5dot1 = false;
8671 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008672 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008673 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8674 supports5dot1 = true;
8675 break;
8676 }
8677 }
8678 // If not then add 5.1 support.
8679 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008680 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008681 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008682 }
Phil Burk09bc4612016-02-24 15:58:15 -08008683 }
8684}
8685
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008686void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008687 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008688 const sp<IOProfile>& profile) {
8689 if (!profile->hasDynamicAudioProfile()) {
8690 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008691 }
François Gaffie112b0af2015-11-19 16:13:25 +01008692
jiabin12537fc2023-10-12 17:56:08 +00008693 audio_port_v7 devicePort;
8694 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008695
jiabin12537fc2023-10-12 17:56:08 +00008696 audio_port_v7 mixPort;
8697 profile->toAudioPort(&mixPort);
8698 mixPort.ext.mix.handle = ioHandle;
8699
8700 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8701 if (status != NO_ERROR) {
8702 ALOGE("%s failed to query the attributes of the mix port", __func__);
8703 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008704 }
jiabin12537fc2023-10-12 17:56:08 +00008705
8706 std::set<audio_format_t> supportedFormats;
8707 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8708 supportedFormats.insert(mixPort.audio_profiles[i].format);
8709 }
8710 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8711 mReportedFormatsMap[devDesc] = formats;
8712
8713 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8714 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8715 modifySurroundFormats(devDesc, &formats);
8716 size_t modifiedNumProfiles = 0;
8717 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8718 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8719 formats.end()) {
8720 // Skip the format that is not present after modifying surround formats.
8721 continue;
8722 }
8723 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8724 sizeof(struct audio_profile));
8725 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8726 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8727 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8728 modifySurroundChannelMasks(&channels);
8729 std::copy(channels.begin(), channels.end(),
8730 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8731 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8732 }
8733 mixPort.num_audio_profiles = modifiedNumProfiles;
8734 }
8735 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008736}
Eric Laurentd60560a2015-04-10 11:31:20 -07008737
Mikhail Naganovdc769682018-05-04 15:34:08 -07008738status_t AudioPolicyManager::installPatch(const char *caller,
8739 audio_patch_handle_t *patchHandle,
8740 AudioIODescriptorInterface *ioDescriptor,
8741 const struct audio_patch *patch,
8742 int delayMs)
8743{
8744 ssize_t index = mAudioPatches.indexOfKey(
8745 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8746 *patchHandle : ioDescriptor->getPatchHandle());
8747 sp<AudioPatch> patchDesc;
8748 status_t status = installPatch(
8749 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8750 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008751 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008752 }
8753 return status;
8754}
8755
8756status_t AudioPolicyManager::installPatch(const char *caller,
8757 ssize_t index,
8758 audio_patch_handle_t *patchHandle,
8759 const struct audio_patch *patch,
8760 int delayMs,
8761 uid_t uid,
8762 sp<AudioPatch> *patchDescPtr)
8763{
8764 sp<AudioPatch> patchDesc;
8765 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8766 if (index >= 0) {
8767 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008768 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008769 }
8770
8771 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8772 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8773 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8774 if (status == NO_ERROR) {
8775 if (index < 0) {
8776 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008777 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008778 } else {
8779 patchDesc->mPatch = *patch;
8780 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008781 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008782 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008783 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008784 }
8785 nextAudioPortGeneration();
8786 mpClientInterface->onAudioPatchListUpdate();
8787 }
8788 if (patchDescPtr) *patchDescPtr = patchDesc;
8789 return status;
8790}
8791
jiabinbce0c1d2020-10-05 11:20:18 -07008792bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8793{
8794 const TrackClientVector activeClients = output->getActiveClients();
8795 if (activeClients.empty()) {
8796 return true;
8797 }
8798 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8799 if (index < 0) {
8800 ALOGE("%s, no audio patch found while there are active clients on output %d",
8801 __func__, output->getId());
8802 return false;
8803 }
8804 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8805 DeviceVector routedDevices;
8806 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8807 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8808 patchDesc->mPatch.sinks[i].id);
8809 if (device == nullptr) {
8810 ALOGE("%s, no audio device found with id(%d)",
8811 __func__, patchDesc->mPatch.sinks[i].id);
8812 return false;
8813 }
8814 routedDevices.add(device);
8815 }
8816 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008817 if (client->isInvalid()) {
8818 // No need to take care about invalidated clients.
8819 continue;
8820 }
jiabinbce0c1d2020-10-05 11:20:18 -07008821 sp<DeviceDescriptor> preferredDevice =
8822 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8823 if (mEngine->getOutputDevicesForAttributes(
8824 client->attributes(), preferredDevice, false) == routedDevices) {
8825 return false;
8826 }
8827 }
8828 return true;
8829}
8830
8831sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008832 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008833 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8834 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008835{
8836 for (const auto& device : devices) {
8837 // TODO: This should be checking if the profile supports the device combo.
8838 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008839 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8840 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008841 return nullptr;
8842 }
8843 }
8844 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8845 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008846 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008847 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11008848 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008849 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008850 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008851 return nullptr;
8852 }
jiabin14b50cc2023-12-13 19:01:52 +00008853 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8854 auto portConfig = desc->getConfig();
8855 for (const auto& device : devices) {
8856 device->setPreferredConfig(&portConfig);
8857 }
8858 }
jiabinbce0c1d2020-10-05 11:20:18 -07008859
8860 // Here is where the out_set_parameters() for card & device gets called
8861 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8862 const audio_devices_t deviceType = device->type();
8863 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008864 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008865 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8866 mpClientInterface->setParameters(output, String8(param));
8867 free(param);
8868 }
jiabin12537fc2023-10-12 17:56:08 +00008869 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008870 if (!profile->hasValidAudioProfile()) {
8871 ALOGW("%s() missing param", __func__);
8872 desc->close();
8873 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008874 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8875 // Reopen the output with the best audio profile picked by APM when the profile supports
8876 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008877 desc->close();
8878 output = AUDIO_IO_HANDLE_NONE;
8879 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8880 profile->pickAudioProfile(
8881 config.sample_rate, config.channel_mask, config.format);
8882 config.offload_info.sample_rate = config.sample_rate;
8883 config.offload_info.channel_mask = config.channel_mask;
8884 config.offload_info.format = config.format;
8885
Dean Wheatleydfb67b82024-01-23 09:36:29 +11008886 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008887 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008888 if (status != NO_ERROR) {
8889 return nullptr;
8890 }
8891 }
8892
8893 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008894 setOutputDevices(__func__, desc,
8895 devices,
8896 true,
8897 0,
8898 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008899 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8900 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8901
jiabinbce0c1d2020-10-05 11:20:18 -07008902 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8903 sp<AudioPolicyMix> policyMix;
8904 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8905 policyMix->setOutput(desc);
8906 desc->mPolicyMix = policyMix;
8907 } else {
8908 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008909 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008910 }
8911
baek.kim -61c20122022-07-27 10:05:32 +00008912 } else if (hasPrimaryOutput() && speaker != nullptr
8913 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008914 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8915 // no duplicated output for:
8916 // - direct outputs
8917 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008918 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008919 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8920
8921 //TODO: configure audio effect output stage here
8922
8923 // open a duplicating output thread for the new output and the primary output
8924 sp<SwAudioOutputDescriptor> dupOutputDesc =
8925 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8926 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8927 if (status == NO_ERROR) {
8928 // add duplicated output descriptor
8929 addOutput(duplicatedOutput, dupOutputDesc);
8930 } else {
8931 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8932 mPrimaryOutput->mIoHandle, output);
8933 desc->close();
8934 removeOutput(output);
8935 nextAudioPortGeneration();
8936 return nullptr;
8937 }
8938 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008939 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8940 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8941 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008942 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008943 }
jiabinbce0c1d2020-10-05 11:20:18 -07008944 return desc;
8945}
8946
jiabinf1c73972022-04-14 16:28:52 -07008947status_t AudioPolicyManager::getDevicesForAttributes(
8948 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8949 // Devices are determined in the following precedence:
8950 //
8951 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8952 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8953 //
8954 // If no such dynamic policy then
8955 // 2) Devices containing an active client using setPreferredDevice
8956 // with same strategy as the attributes.
8957 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8958 //
8959 // If no corresponding active client with setPreferredDevice then
8960 // 3) Devices associated with the strategy determined by the attributes
8961 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8962 //
8963 // See related getOutputForAttrInt().
8964
8965 // check dynamic policies but only for primary descriptors (secondary not used for audible
8966 // audio routing, only used for duplication for playback capture)
8967 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008968 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008969 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008970 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8971 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8972 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008973 if (status != OK) {
8974 return status;
8975 }
8976
8977 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8978 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8979 // as they are unaffected by device/stream volume
8980 // (per SwAudioOutputDescriptor::isFixedVolume()).
8981 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8982 ) {
8983 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8984 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8985 devices.add(deviceDesc);
8986 } else {
8987 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8988 // which selects setPreferredDevice if active. This means forVolume call
8989 // will take an active setPreferredDevice, if such exists.
8990
8991 devices = mEngine->getOutputDevicesForAttributes(
8992 attr, nullptr /* preferredDevice */, false /* fromCache */);
8993 }
8994
8995 if (forVolume) {
8996 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8997 // for single volume control in AudioService (such relationship should exist if
8998 // SPEAKER_SAFE is present).
8999 //
9000 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9001 DeviceVector speakerSafeDevices =
9002 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9003 if (!speakerSafeDevices.isEmpty()) {
9004 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9005 devices.remove(speakerSafeDevices);
9006 }
9007 }
9008
9009 return NO_ERROR;
9010}
9011
9012status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9013 AudioProfileVector& audioProfiles,
9014 uint32_t flags,
9015 bool isInput) {
9016 for (const auto& hwModule : mHwModules) {
9017 // the MSD module checks for different conditions
9018 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9019 continue;
9020 }
9021 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9022 : hwModule->getOutputProfiles();
9023 for (const auto& profile : ioProfiles) {
9024 if (!profile->areAllDevicesSupported(devices) ||
9025 !profile->isCompatibleProfileForFlags(
9026 flags, false /*exactMatchRequiredForInputFlags*/)) {
9027 continue;
9028 }
9029 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9030 }
9031 }
9032
9033 if (!isInput) {
9034 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9035 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9036 if (msdModule != nullptr) {
9037 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9038 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9039 for (const auto &profile: msdModule->getOutputProfiles()) {
9040 if (!profile->asAudioPort()->isDirectOutput()) {
9041 continue;
9042 }
9043 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9044 }
9045 } else {
9046 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9047 }
9048 }
9049 }
9050
9051 return NO_ERROR;
9052}
9053
jiabin3ff8d7d2022-12-13 06:27:44 +00009054sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9055 const audio_config_t *config,
9056 audio_output_flags_t flags,
9057 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009058 closeOutput(outputDesc->mIoHandle);
9059 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9060 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9061 if (preferredOutput == nullptr) {
9062 ALOGE("%s failed to reopen output device=%d, caller=%s",
9063 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009064 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009065 return preferredOutput;
9066}
9067
9068void AudioPolicyManager::reopenOutputsWithDevices(
9069 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9070 for (const auto& [output, devices] : outputsToReopen) {
9071 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9072 closeOutput(output);
9073 openOutputWithProfileAndDevice(desc->mProfile, devices);
9074 }
jiabina84c3d32022-12-02 18:59:55 +00009075}
9076
jiabinc44b3462022-12-08 12:52:31 -08009077PortHandleVector AudioPolicyManager::getClientsForStream(
9078 audio_stream_type_t streamType) const {
9079 PortHandleVector clients;
9080 for (size_t i = 0; i < mOutputs.size(); ++i) {
9081 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9082 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9083 }
9084 return clients;
9085}
9086
9087void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9088 PortHandleVector clients;
9089 for (auto stream : streams) {
9090 PortHandleVector clientsForStream = getClientsForStream(stream);
9091 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9092 }
9093 mpClientInterface->invalidateTracks(clients);
9094}
9095
jiabin220eea12024-05-17 17:55:20 +00009096void AudioPolicyManager::updateClientsInternalMute(
9097 const sp<android::SwAudioOutputDescriptor> &desc) {
9098 if (!desc->isBitPerfect() ||
9099 !com::android::media::audioserver::
9100 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9101 // This is only used for bit perfect output now.
9102 return;
9103 }
9104 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9105 bool bitPerfectClientInternalMute = false;
9106 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9107 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9108 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9109 bitPerfectClient = client;
9110 continue;
9111 }
9112 bool muted = false;
9113 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9114 // System sound is muted.
9115 muted = true;
9116 } else {
9117 bitPerfectClientInternalMute = true;
9118 }
9119 if (client->setInternalMute(muted)) {
9120 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9121 if (!result.ok()) {
9122 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9123 continue;
9124 }
9125 media::TrackInternalMuteInfo info;
9126 info.portId = result.value();
9127 info.muted = client->getInternalMute();
9128 clientsInternalMute.push_back(std::move(info));
9129 }
9130 }
9131 if (bitPerfectClient != nullptr &&
9132 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9133 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9134 if (result.ok()) {
9135 media::TrackInternalMuteInfo info;
9136 info.portId = result.value();
9137 info.muted = bitPerfectClient->getInternalMute();
9138 clientsInternalMute.push_back(std::move(info));
9139 } else {
9140 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9141 __func__, bitPerfectClient->portId());
9142 }
9143 }
9144 if (!clientsInternalMute.empty()) {
9145 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9146 status != NO_ERROR) {
9147 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9148 }
9149 }
9150}
9151
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009152} // namespace android