blob: 2897db86ea91924264ed77339dc453880df4f0bd [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())
1253 && !audio_is_linear_pcm(config->format)) {
1254 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001255 return BAD_VALUE;
1256 }
1257 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001258 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001259 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1260 primaryMix->mDeviceAddress,
1261 AUDIO_FORMAT_DEFAULT);
1262 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001263 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001264 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1265 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001266 // if a direct output can be opened to deliver the track's multi-channel content to the
1267 // output rather than being downmixed by the primary output, then use this direct
1268 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1269 // mix.
1270 bool tryDirectForChannelMask = policyDesc != nullptr
1271 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1272 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001273 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001274 audio_io_handle_t newOutput;
1275 status = openDirectOutput(
1276 *stream, session, config,
1277 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001278 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001279 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001280 policyDesc = mOutputs.valueFor(newOutput);
1281 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001282 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001283 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001284 policyDesc = nullptr;
1285 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001286 }
1287 if (policyDesc != nullptr) {
1288 policyDesc->mPolicyMix = primaryMix;
1289 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001290 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1291 : AUDIO_PORT_HANDLE_NONE;
1292 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1293 // Remove direct flag as it is not on a direct output.
1294 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1295 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001296
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001297 ALOGV("getOutputForAttr() returns output %d", *output);
1298 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1299 *outputType = API_OUT_MIX_PLAYBACK;
1300 } else {
1301 *outputType = API_OUTPUT_LEGACY;
1302 }
1303 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001304 } else {
1305 if (policyMixDevice != nullptr) {
1306 ALOGE("%s, try to use primary mix but no output found", __func__);
1307 return INVALID_OPERATION;
1308 }
1309 // Fallback to default engine selection as the selected primary mix device is not
1310 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001311 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001312 }
François Gaffiec005e562018-11-06 15:04:49 +01001313 // Virtual sources must always be dynamicaly or explicitly routed
1314 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1315 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1316 return BAD_VALUE;
1317 }
1318 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1319 // in order to let the choice of the order to future vendor engine
1320 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001321
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001322 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001323 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001324 }
1325
Nadav Barb2f18162018-07-18 13:01:53 +03001326 // Set incall music only if device was explicitly set, and fallback to the device which is
1327 // chosen by the engine if not.
1328 // FIXME: provide a more generic approach which is not device specific and move this back
1329 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001330 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001331 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001332 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001333 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001334 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001335 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001336 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001337 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001338 }
1339 }
1340
François Gaffiec005e562018-11-06 15:04:49 +01001341 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1342 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1343 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001344
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001345 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001346 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001347 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001348 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001349 ALOGV("%s() Using MSD devices %s instead of devices %s",
1350 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001351 } else {
1352 *output = AUDIO_IO_HANDLE_NONE;
1353 }
1354 }
1355 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001356 sp<PreferredMixerAttributesInfo> info = nullptr;
1357 if (outputDevices.size() == 1) {
1358 info = getPreferredMixerAttributesInfo(
1359 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001360 mEngine->getProductStrategyForAttributes(*resultAttr),
1361 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001362 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1363 // and it is currently active.
1364 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001365 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001366 info = nullptr;
1367 }
jiabin220eea12024-05-17 17:55:20 +00001368 if (com::android::media::audioserver::
1369 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1370 if (info != nullptr && info->getUid() == uid &&
1371 info->configMatches(*config) &&
1372 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1373 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1374 [this, &outputDevices](audio_usage_t usage) {
1375 return mOutputs.isUsageActiveOnDevice(
1376 usage, outputDevices[0]); }))) {
1377 // Bit-perfect request is not allowed when the phone mode is not normal or
1378 // there is any higher priority user case active.
1379 return INVALID_OPERATION;
1380 }
1381 }
jiabina84c3d32022-12-02 18:59:55 +00001382 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001383 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001384 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001385 // The client will be active if the client is currently preferred mixer owner and the
1386 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001387 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001388 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001389 && info->getUid() == uid
1390 && *output != AUDIO_IO_HANDLE_NONE
1391 // When bit-perfect output is selected for the preferred mixer attributes owner,
1392 // only need to consider the config matches.
1393 && mOutputs.valueFor(*output)->isConfigurationMatched(
1394 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001395
1396 if (*isBitPerfect) {
1397 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1398 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001399 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001400 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001401 AudioProfileVector profiles;
1402 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1403 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001404 const auto channels = profiles[0]->getChannels();
1405 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1406 config->channel_mask = *channels.begin();
1407 }
1408 const auto sampleRates = profiles[0]->getSampleRates();
1409 if (!sampleRates.empty() &&
1410 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1411 config->sample_rate = *sampleRates.begin();
1412 }
jiabinf1c73972022-04-14 16:28:52 -07001413 config->format = profiles[0]->getFormat();
1414 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001415 return INVALID_OPERATION;
1416 }
Paul McLeanaa981192015-03-21 09:55:15 -07001417
François Gaffiec005e562018-11-06 15:04:49 +01001418 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001419 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001420 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001421 *selectedDeviceId = outputDevice->getId();
1422 break;
1423 }
1424 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001425
Eric Laurent8a1095a2019-11-08 14:44:16 -08001426 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1427 *outputType = API_OUTPUT_TELEPHONY_TX;
1428 } else {
1429 *outputType = API_OUTPUT_LEGACY;
1430 }
1431
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001432 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1433
1434 return NO_ERROR;
1435}
1436
1437status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1438 audio_io_handle_t *output,
1439 audio_session_t session,
1440 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001441 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001442 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001443 audio_output_flags_t *flags,
1444 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001445 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001446 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001447 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001448 bool *isSpatialized,
1449 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001450{
1451 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1452 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1453 return INVALID_OPERATION;
1454 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001455 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001456 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001457 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001458 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001459 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001460 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001461 const sp<DeviceDescriptor> requestedDevice =
1462 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1463
1464 // Prevent from storing invalid requested device id in clients
1465 const audio_port_handle_t sanitizedRequestedPortId =
1466 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1467 *selectedDeviceId = sanitizedRequestedPortId;
1468
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001469 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001470 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001471 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1472 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001473 if (status != NO_ERROR) {
1474 return status;
1475 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001476 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001477 if (secondaryOutputs != nullptr) {
1478 for (auto &secondaryMix : secondaryMixes) {
1479 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1480 if (outputDesc != nullptr &&
1481 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1482 secondaryOutputs->push_back(outputDesc->mIoHandle);
1483 weakSecondaryOutputDescs.push_back(outputDesc);
1484 }
1485 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001486 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001487
Eric Laurent8fc147b2018-07-22 19:13:55 -07001488 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001489 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001490 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001491 };
jiabin4ef93452019-09-10 14:29:54 -07001492 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001493
Eric Laurentc209fe42020-06-05 18:11:23 -07001494 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001495 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001496 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001497 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001498 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001499 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001500 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001501 std::move(weakSecondaryOutputDescs),
1502 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001503 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001504
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001505 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1506 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001507
Eric Laurente83b55d2014-11-14 10:06:21 -08001508 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001509}
1510
Eric Laurentc529cf62020-04-17 18:19:10 -07001511status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1512 audio_session_t session,
1513 const audio_config_t *config,
1514 audio_output_flags_t flags,
1515 const DeviceVector &devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001516 audio_io_handle_t *output,
1517 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001518
1519 *output = AUDIO_IO_HANDLE_NONE;
1520
1521 // skip direct output selection if the request can obviously be attached to a mixed output
1522 // and not explicitly requested
1523 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1524 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1525 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1526 return NAME_NOT_FOUND;
1527 }
1528
Mikhail Naganov285c1732024-09-05 17:26:50 -07001529 // Reject flag combinations that do not make sense. Note that the requested flags might not
1530 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1531 // combine the requested flags with its own flags, yielding an unsupported combination.
1532 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1533 return NAME_NOT_FOUND;
1534 }
1535
Eric Laurentc529cf62020-04-17 18:19:10 -07001536 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1537 // This prevents creating an offloaded track and tearing it down immediately after start
1538 // when audioflinger detects there is an active non offloadable effect.
1539 // FIXME: We should check the audio session here but we do not have it in this context.
1540 // This may prevent offloading in rare situations where effects are left active by apps
1541 // in the background.
1542 sp<IOProfile> profile;
1543 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1544 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1545 profile = getProfileForOutput(
1546 devices, config->sample_rate, config->format, config->channel_mask,
1547 flags, true /* directOnly */);
1548 }
1549
1550 if (profile == nullptr) {
1551 return NAME_NOT_FOUND;
1552 }
1553
1554 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1555 for (size_t i = 0; i < mOutputs.size(); i++) {
1556 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1557 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1558 // reuse direct output if currently open by the same client
1559 // and configured with same parameters
1560 if ((config->sample_rate == desc->getSamplingRate()) &&
1561 (config->format == desc->getFormat()) &&
1562 (config->channel_mask == desc->getChannelMask()) &&
1563 (session == desc->mDirectClientSession)) {
1564 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301565 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001566 mOutputs.keyAt(i), session);
1567 *output = mOutputs.keyAt(i);
1568 return NO_ERROR;
1569 }
1570 }
1571 }
1572
1573 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001574 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301575 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1576 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001577 return NAME_NOT_FOUND;
1578 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1579 // MMAP gracefully handles lack of an exclusive track resource by mixing
1580 // above the audio framework. For AAudio to know that the limit is reached,
1581 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301582 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1583 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001584 return NAME_NOT_FOUND;
1585 } else {
1586 // Close outputs on this profile, if available, to free resources for this request
1587 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1588 const auto desc = mOutputs.valueAt(i);
1589 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301590 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1591 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001592 closeOutput(desc->mIoHandle);
1593 }
1594 }
1595 }
1596 }
1597
1598 // Unable to close streams to find free resources for this request
1599 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301600 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1601 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001602 return NAME_NOT_FOUND;
1603 }
1604
Atneya Nairb16666a2023-12-11 20:18:33 -08001605 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001606
Michael Chan6fb34492020-12-08 15:44:49 +11001607 // An MSD patch may be using the only output stream that can service this request. Release
1608 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001609 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001610
Eric Laurentf1f22e72021-07-13 14:04:14 +02001611 status_t status =
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001612 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1613 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001614
1615 // only accept an output with the requested parameters
1616 if (status != NO_ERROR ||
1617 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1618 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1619 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1620 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1621 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1622 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1623 config->channel_mask, outputDesc->getChannelMask());
1624 if (*output != AUDIO_IO_HANDLE_NONE) {
1625 outputDesc->close();
1626 }
1627 // fall back to mixer output if possible when the direct output could not be open
1628 if (audio_is_linear_pcm(config->format) &&
1629 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1630 return NAME_NOT_FOUND;
1631 }
1632 *output = AUDIO_IO_HANDLE_NONE;
1633 return BAD_VALUE;
1634 }
1635 outputDesc->mDirectOpenCount = 1;
1636 outputDesc->mDirectClientSession = session;
1637
1638 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001639 setOutputDevices(__func__, outputDesc,
1640 devices,
1641 true,
1642 0,
1643 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001644 mPreviousOutputs = mOutputs;
1645 ALOGV("%s returns new direct output %d", __func__, *output);
1646 mpClientInterface->onAudioPortListUpdate();
1647 return NO_ERROR;
1648}
1649
François Gaffie11d30102018-11-02 16:09:09 +01001650audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1651 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001652 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001653 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001654 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001655 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001656 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001657 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001658 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001659{
Andy Hungc88b0642018-04-27 15:42:35 -07001660 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001661
jiabine375d412019-02-26 12:54:53 -08001662 // Discard haptic channel mask when forcing muting haptic channels.
1663 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001664 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1665 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001666
Eric Laurente552edb2014-03-10 17:42:56 -07001667 // open a direct output if required by specified parameters
1668 //force direct flag if offload flag is set: offloading implies a direct output stream
1669 // and all common behaviors are driven by checking only the direct flag
1670 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001671 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1672 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001673 }
Nadav Bar766fb022018-01-07 12:18:03 +02001674 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1675 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001676 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001677
1678 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1679
Eric Laurente83b55d2014-11-14 10:06:21 -08001680 // only allow deep buffering for music stream type
1681 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001682 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001683 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov285c1732024-09-05 17:26:50 -07001684 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001685 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001686 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001687 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001688 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001689 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001690 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001691 audio_is_linear_pcm(config->format) &&
1692 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001693 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001694 AUDIO_OUTPUT_FLAG_DIRECT);
1695 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001696 }
Eric Laurente552edb2014-03-10 17:42:56 -07001697
Carter Hsua3abb402021-10-26 11:11:20 +08001698 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1699 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1700 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1701 }
1702
Eric Laurentf9230d52024-01-26 18:49:09 +01001703 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001704 // was specified and offload or direct playback is not explicitly requested, and there is no
1705 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001706 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001707 if (mSpatializerOutput != nullptr &&
1708 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1709 prefMixerConfigInfo == nullptr &&
1710 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1711 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001712 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001713 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001714 }
1715
Eric Laurentc529cf62020-04-17 18:19:10 -07001716 audio_config_t directConfig = *config;
1717 directConfig.channel_mask = channelMask;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001718
1719 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1720 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001721 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001722 return output;
1723 }
1724
Eric Laurent14cbfca2016-03-17 09:42:16 -07001725 // A request for HW A/V sync cannot fallback to a mixed output because time
1726 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001727 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001728 return AUDIO_IO_HANDLE_NONE;
1729 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001730 // A request for Tuner cannot fallback to a mixed output
1731 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1732 return AUDIO_IO_HANDLE_NONE;
1733 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001734
Eric Laurente552edb2014-03-10 17:42:56 -07001735 // ignoring channel mask due to downmix capability in mixer
1736
1737 // open a non direct output
1738
1739 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001740 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001741 // get which output is suitable for the specified stream. The actual
1742 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001743 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001744 if (prefMixerConfigInfo != nullptr) {
1745 for (audio_io_handle_t outputHandle : outputs) {
1746 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1747 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1748 output = outputHandle;
1749 break;
1750 }
1751 }
1752 if (output == AUDIO_IO_HANDLE_NONE) {
1753 // No output open with the preferred profile. Open a new one.
1754 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1755 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1756 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1757 config.format = prefMixerConfigInfo->getConfigBase().format;
1758 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1759 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1760 &config, prefMixerConfigInfo->getFlags());
1761 if (preferredOutput == nullptr) {
1762 ALOGE("%s failed to open output with preferred mixer config", __func__);
1763 } else {
1764 output = preferredOutput->mIoHandle;
1765 }
1766 }
1767 } else {
1768 // at this stage we should ignore the DIRECT flag as no direct output could be
1769 // found earlier
1770 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001771 if (com::android::media::audioserver::
1772 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1773 // If the preferred mixer attributes is null, do not select the bit-perfect output
1774 // unless the bit-perfect output is the only output.
1775 // The bit-perfect output can exist while the passed in preferred mixer attributes
1776 // info is null when it is a high priority client. The high priority clients are
1777 // ringtone or alarm, which is not a bit-perfect use case.
1778 size_t i = 0;
1779 while (i < outputs.size() && outputs.size() > 1) {
1780 auto desc = mOutputs.valueFor(outputs[i]);
1781 // The output descriptor must not be null here.
1782 if (desc->isBitPerfect()) {
1783 outputs.removeItemsAt(i);
1784 } else {
1785 i += 1;
1786 }
1787 }
1788 }
jiabina84c3d32022-12-02 18:59:55 +00001789 output = selectOutput(
1790 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1791 }
Eric Laurente552edb2014-03-10 17:42:56 -07001792 }
François Gaffie11d30102018-11-02 16:09:09 +01001793 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001794 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001795 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001796
Eric Laurente552edb2014-03-10 17:42:56 -07001797 return output;
1798}
1799
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001800sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001801 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1802 mAvailableInputDevices);
1803 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1804}
1805
1806DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1807 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1808 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001809}
1810
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001811const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001812 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001813 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1814 if (msdModule != 0) {
1815 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1816 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1817 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1818 const struct audio_port_config *source = &patch->mPatch.sources[j];
1819 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1820 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001821 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001822 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001823 }
1824 }
1825 }
1826 return msdPatches;
1827}
1828
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001829bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1830 ssize_t index = mAudioPatches.indexOfKey(handle);
1831 if (index < 0) {
1832 return false;
1833 }
1834 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1835 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1836 if (msdModule == nullptr) {
1837 return false;
1838 }
1839 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1840 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1841 return true;
1842 }
1843 index = getMsdOutputPatches().indexOfKey(handle);
1844 if (index < 0) {
1845 return false;
1846 }
1847 return true;
1848}
1849
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001850status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1851 const InputProfileCollection &inputProfiles,
1852 const OutputProfileCollection &outputProfiles,
1853 const sp<DeviceDescriptor> &sourceDevice,
1854 const sp<DeviceDescriptor> &sinkDevice,
1855 AudioProfileVector& sourceProfiles,
1856 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001857 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001858 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001859 return NO_INIT;
1860 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001861 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001862 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001863 return NO_INIT;
1864 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001865 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001866 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1867 inProfile->supportsDevice(sourceDevice)) {
1868 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001869 }
1870 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001871 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001872 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001873 outProfile->supportsDevice(sinkDevice)) {
1874 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001875 }
1876 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001877 return NO_ERROR;
1878}
1879
1880status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1881 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1882 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1883{
Dean Wheatley16809da2022-12-09 14:55:46 +11001884 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1885 static const std::vector<audio_format_t> formatsOrder = {{
1886 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001887 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1888 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001889 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1890 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1891 // preferred).
1892 std::vector<audio_channel_mask_t> masks = {{
1893 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1894 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1895 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1896 // insert index masks (higher counts most preferred) as preferred over position masks
1897 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1898 masks.insert(
1899 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1900 }
1901 return masks;
1902 }();
1903
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001904 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001905 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1906 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001908 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1909 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001910 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001911 }
1912 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1913 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1914 sinkConfig->format = bestSinkConfig.format;
1915 // For encoded streams force direct flag to prevent downstream mixing.
1916 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1917 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001918 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1919 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001920 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001921 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1922 // raw and IEC61937 framed streams.
1923 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1924 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1925 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001926 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1927 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001928 sourceConfig->channel_mask =
1929 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1930 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1931 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001932 sourceConfig->format = bestSinkConfig.format;
1933 // Copy input stream directly without any processing (e.g. resampling).
1934 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1935 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1936 if (hwAvSync) {
1937 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1938 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1939 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1940 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1941 }
1942 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1943 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1944 sinkConfig->config_mask |= config_mask;
1945 sourceConfig->config_mask |= config_mask;
1946 return NO_ERROR;
1947}
1948
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001949PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1950 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951{
1952 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001953 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1954 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1955 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1956 if (deviceModule == nullptr) {
1957 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1958 return patchBuilder;
1959 }
1960 const InputProfileCollection inputProfiles = msdIsSource ?
1961 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1962 const OutputProfileCollection outputProfiles = msdIsSource ?
1963 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1964
1965 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1966 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1967 device : getMsdAudioOutDevices().itemAt(0);
1968 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1969
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001970 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1971 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001972 AudioProfileVector sourceProfiles;
1973 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001974 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1975 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001976 for (auto hwAvSync : { true, false }) {
1977 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1978 sourceProfiles, sinkProfiles) != NO_ERROR) {
1979 continue;
1980 }
1981 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1982 &sinkConfig) == NO_ERROR) {
1983 // Found a matching config. Re-create PatchBuilder with this config.
1984 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1985 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001986 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001987 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001988 " supporting PCM format conversion.", __func__);
1989 return patchBuilder;
1990}
1991
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001992status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001993 DeviceVector devices;
1994 if (outputDevices != nullptr && outputDevices->size() > 0) {
1995 devices.add(*outputDevices);
1996 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001997 // Use media strategy for unspecified output device. This should only
1998 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1999 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002000 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002001 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002002 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002003 }
Michael Chan6fb34492020-12-08 15:44:49 +11002004 std::vector<PatchBuilder> patchesToCreate;
2005 for (auto i = 0u; i < devices.size(); ++i) {
2006 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002007 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002008 }
2009 // Retain only the MSD patches associated with outputDevices request.
2010 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002011 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002012 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2013 auto retainedPatch = false;
2014 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2015 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2016 patchesToRemove.removeItemsAt(i);
2017 retainedPatch = true;
2018 break;
2019 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002020 }
Michael Chan6fb34492020-12-08 15:44:49 +11002021 if (retainedPatch) {
2022 it = patchesToCreate.erase(it);
2023 continue;
2024 }
2025 ++it;
2026 }
2027 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2028 return NO_ERROR;
2029 }
2030 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2031 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002032 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002033 }
Michael Chan6fb34492020-12-08 15:44:49 +11002034 status_t status = NO_ERROR;
2035 for (const auto &p : patchesToCreate) {
2036 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2037 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2038 char message[256];
2039 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2040 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2041 currStatus == NO_ERROR ? "Success" : "Error",
2042 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2043 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2044 if (currStatus == NO_ERROR) {
2045 ALOGD("%s", message);
2046 } else {
2047 ALOGE("%s", message);
2048 if (status == NO_ERROR) {
2049 status = currStatus;
2050 }
2051 }
2052 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002053 return status;
2054}
2055
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002056void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2057 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002058 for (size_t i = 0; i < msdPatches.size(); i++) {
2059 const auto& patch = msdPatches[i];
2060 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2061 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2062 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2063 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2064 releaseAudioPatch(patch->getHandle(), mUidCached);
2065 break;
2066 }
2067 }
2068 }
2069}
2070
Dorin Drimus94d94412022-02-02 09:05:02 +01002071bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002072 DeviceVector devicesToCheck =
2073 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002074 AudioPatchCollection msdPatches = getMsdOutputPatches();
2075 for (size_t i = 0; i < msdPatches.size(); i++) {
2076 const auto& patch = msdPatches[i];
2077 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2078 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2079 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2080 const auto& foundDevice = devicesToCheck.getDevice(
2081 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2082 if (foundDevice != nullptr) {
2083 devicesToCheck.remove(foundDevice);
2084 if (devicesToCheck.isEmpty()) {
2085 return true;
2086 }
2087 }
2088 }
2089 }
2090 }
2091 return false;
2092}
2093
Eric Laurente0720872014-03-11 09:30:41 -07002094audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002095 audio_output_flags_t flags,
2096 audio_format_t format,
2097 audio_channel_mask_t channelMask,
2098 uint32_t samplingRate,
2099 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002100{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002101 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2102 "%s called with format %#x", __func__, format);
2103
jiabinebb6af42020-06-09 17:31:17 -07002104 // Return the output that haptic-generating attached to when 1) session id is specified,
2105 // 2) haptic-generating effect exists for given session id and 3) the output that
2106 // haptic-generating effect attached to is in given outputs.
2107 if (sessionId != AUDIO_SESSION_NONE) {
2108 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2109 sessionId, FX_IID_HAPTICGENERATOR);
2110 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2111 return hapticGeneratingOutput;
2112 }
2113 }
2114
Eric Laurent16c66dd2019-05-01 17:54:10 -07002115 // Flags disqualifying an output: the match must happen before calling selectOutput()
2116 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2117 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2118
2119 // Flags expressing a functional request: must be honored in priority over
2120 // other criteria
2121 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2122 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002123 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2124 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002125 // Flags expressing a performance request: have lower priority than serving
2126 // requested sampling rate or channel mask
2127 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2128 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2129 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2130
2131 const audio_output_flags_t functionalFlags =
2132 (audio_output_flags_t)(flags & kFunctionalFlags);
2133 const audio_output_flags_t performanceFlags =
2134 (audio_output_flags_t)(flags & kPerformanceFlags);
2135
2136 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2137
Eric Laurente552edb2014-03-10 17:42:56 -07002138 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002139 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002140 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002141 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002142 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002143 // with tiebreak preferring the minimum number of extra functional flags
2144 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002145 // 3: the output supporting the exact channel mask
2146 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002147 // 5: the output with the highest sampling rate if the requested sample rate is
2148 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002149 // 6: the output with the highest number of requested performance flags
2150 // 7: the output with the bit depth the closest to the requested one
2151 // 8: the primary output
2152 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002153
Eric Laurent16c66dd2019-05-01 17:54:10 -07002154 // matching criteria values in priority order for best matching output so far
2155 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002156
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002157 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002158 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2159 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2160 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002161
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002162 for (audio_io_handle_t output : outputs) {
2163 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002164 // matching criteria values in priority order for current output
2165 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002166
Eric Laurent16c66dd2019-05-01 17:54:10 -07002167 if (outputDesc->isDuplicated()) {
2168 continue;
2169 }
2170 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2171 continue;
2172 }
Eric Laurent8838a382014-09-08 16:44:28 -07002173
Eric Laurent16c66dd2019-05-01 17:54:10 -07002174 // If haptic channel is specified, use the haptic output if present.
2175 // When using haptic output, same audio format and sample rate are required.
2176 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002177 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002178 // skip if haptic channel specified but output does not support it, or output support haptic
2179 // but there is no haptic channel requested AND no orphan haptic effect exist
2180 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2181 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002182 continue;
2183 }
Shunkai Yao808da212024-04-05 22:50:56 +00002184 // In the case of audio-coupled-haptic playback, there is no format conversion and
2185 // resampling in the framework, same format/channel/sampleRate for client and the output
2186 // thread is required. In the case of HapticGenerator effect, do not require format
2187 // matching.
2188 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2189 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002190 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002191 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002192 }
2193
2194 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002195 const int matchingFunctionalFlags =
2196 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2197 const int totalFunctionalFlags =
2198 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2199 // Prefer matching functional flags, but subtract unnecessary functional flags.
2200 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002201
2202 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002203 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2204 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002205 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2206 channelCount <= outputChannelCount) {
2207 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002208 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2209 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002210 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002211 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002212 currentMatchCriteria[3] = outputChannelCount;
2213 }
2214
2215 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002216 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002217 int diff; // avoid unsigned integer overflow.
2218 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2219
2220 // prefer the closest output sampling rate greater than or equal to target
2221 // if none exists, prefer the closest output sampling rate less than target.
2222 //
2223 // criteria is offset to make non-negative.
2224 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002225 }
2226
2227 // performance flags match
2228 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2229
2230 // format match
2231 if (format != AUDIO_FORMAT_INVALID) {
2232 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002233 PolicyAudioPort::kFormatDistanceMax -
2234 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002235 }
2236
2237 // primary output match
2238 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2239
2240 // compare match criteria by priority then value
2241 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2242 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2243 bestMatchCriteria = currentMatchCriteria;
2244 bestOutput = output;
2245
2246 std::stringstream result;
2247 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2248 std::ostream_iterator<int>(result, " "));
2249 ALOGV("%s new bestOutput %d criteria %s",
2250 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002251 }
2252 }
2253
Eric Laurent16c66dd2019-05-01 17:54:10 -07002254 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002255}
2256
Eric Laurent8fc147b2018-07-22 19:13:55 -07002257status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002258{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002259 ALOGV("%s portId %d", __FUNCTION__, portId);
2260
2261 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2262 if (outputDesc == 0) {
2263 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002264 return BAD_VALUE;
2265 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002266 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002267
Eric Laurent8fc147b2018-07-22 19:13:55 -07002268 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002269 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002270
jiabin220eea12024-05-17 17:55:20 +00002271 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2272 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2273 && outputDesc->isBitPerfect()) {
2274 // Usually, APM selects bit-perfect output for high priority use cases only when
2275 // bit-perfect output is the only output that can be routed to the selected device.
2276 // However, here is no need to play high priority use cases such as ringtone and alarm
2277 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2278 // can attach to new output.
2279 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2280 __func__, client->stream());
2281 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2282 return DEAD_OBJECT;
2283 }
2284
Eric Laurent733ce942017-12-07 12:18:25 -08002285 status_t status = outputDesc->start();
2286 if (status != NO_ERROR) {
2287 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002288 }
2289
Eric Laurent97ac8712018-07-27 18:59:02 -07002290 uint32_t delayMs;
2291 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002292
2293 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002294 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002295 if (status == DEAD_OBJECT) {
2296 sp<SwAudioOutputDescriptor> desc =
2297 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2298 if (desc == nullptr) {
2299 // This is not common, it may indicate something wrong with the HAL.
2300 ALOGE("%s unable to open output with default config", __func__);
2301 return status;
2302 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002303 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002304 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002305 }
jiabina84c3d32022-12-02 18:59:55 +00002306
2307 // If the client is the first one active on preferred mixer parameters, reopen the output
2308 // if the current mixer parameters doesn't match the preferred one.
2309 if (outputDesc->devices().size() == 1) {
2310 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2311 outputDesc->devices()[0]->getId(), client->strategy());
2312 if (info != nullptr && info->getUid() == client->uid()) {
2313 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2314 info->getConfigBase(), info->getFlags())) {
2315 stopSource(outputDesc, client);
2316 outputDesc->stop();
2317 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2318 config.channel_mask = info->getConfigBase().channel_mask;
2319 config.sample_rate = info->getConfigBase().sample_rate;
2320 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002321 sp<SwAudioOutputDescriptor> desc =
2322 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2323 if (desc == nullptr) {
2324 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002325 }
jiabin220eea12024-05-17 17:55:20 +00002326 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002327 // Intentionally return error to let the client side resending request for
2328 // creating and starting.
2329 return DEAD_OBJECT;
2330 }
2331 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002332 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002333 // If it is first bit-perfect client, reroute all clients that will be routed to
2334 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2335 PortHandleVector clientsToInvalidate;
2336 for (size_t i = 0; i < mOutputs.size(); i++) {
2337 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002338 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002339 continue;
2340 }
2341 for (const auto& c : mOutputs[i]->getClientIterable()) {
2342 clientsToInvalidate.push_back(c->portId());
2343 }
2344 }
2345 if (!clientsToInvalidate.empty()) {
2346 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2347 __func__);
2348 mpClientInterface->invalidateTracks(clientsToInvalidate);
2349 }
2350 }
jiabina84c3d32022-12-02 18:59:55 +00002351 }
2352 }
2353
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002354 if (client->hasPreferredDevice()) {
2355 // playback activity with preferred device impacts routing occurred, inform upper layers
2356 mpClientInterface->onRoutingUpdated();
2357 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002358 if (delayMs != 0) {
2359 usleep(delayMs * 1000);
2360 }
2361
jiabin220eea12024-05-17 17:55:20 +00002362 if (status == NO_ERROR &&
2363 outputDesc->mPreferredAttrInfo != nullptr &&
2364 outputDesc->isBitPerfect() &&
2365 com::android::media::audioserver::
2366 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2367 // A new client is started on bit-perfect output, update all clients internal mute.
2368 updateClientsInternalMute(outputDesc);
2369 }
2370
Eric Laurentc75307b2015-03-17 15:29:32 -07002371 return status;
2372}
2373
Eric Laurent96d1dda2022-03-14 17:14:19 +01002374bool AudioPolicyManager::isLeUnicastActive() const {
2375 if (isInCall()) {
2376 return true;
2377 }
2378 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2379}
2380
2381bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2382 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2383 return false;
2384 }
2385 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2386 ALOGV("%s active %d", __func__, active);
2387 return active;
2388}
2389
Eric Laurent97ac8712018-07-27 18:59:02 -07002390status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2391 const sp<TrackClientDescriptor>& client,
2392 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002393{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002394 // cannot start playback of STREAM_TTS if any other output is being used
2395 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002396
2397 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002398 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002399 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002400 auto clientStrategy = client->strategy();
2401 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002402 if (stream == AUDIO_STREAM_TTS) {
2403 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002404 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002405 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002406 return INVALID_OPERATION;
2407 } else {
2408 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2409 }
2410 } else {
2411 // some playback other than beacon starts
2412 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2413 }
2414
Eric Laurent77305a62016-07-25 16:39:22 -07002415 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002416 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002417 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002418
François Gaffie11d30102018-11-02 16:09:09 +01002419 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002420 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002421 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002422 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002423 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002424 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002425 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002426 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002427 } else {
2428 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002429 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002430 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2431 AUDIO_FORMAT_DEFAULT);
2432 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2433 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002434 }
2435
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002436 // requiresMuteCheck is false when we can bypass mute strategy.
2437 // It covers a common case when there is no materially active audio
2438 // and muting would result in unnecessary delay and dropped audio.
2439 const uint32_t outputLatencyMs = outputDesc->latency();
2440 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002441 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002442
Eric Laurente552edb2014-03-10 17:42:56 -07002443 // increment usage count for this stream on the requested output:
2444 // NOTE that the usage count is the same for duplicated output and hardware output which is
2445 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002446 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002447
2448 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002449 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002450 // Preferred device may be exclusive, use only if no other active clients on this output
2451 devices = DeviceVector(
2452 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2453 } else {
2454 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2455 }
François Gaffie11d30102018-11-02 16:09:09 +01002456 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002457 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002458 }
2459 }
Eric Laurente552edb2014-03-10 17:42:56 -07002460
François Gaffiec005e562018-11-06 15:04:49 +01002461 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002462 selectOutputForMusicEffects();
2463 }
2464
François Gaffie1c878552018-11-22 16:53:21 +01002465 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002466 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002467 if (devices.isEmpty()) {
2468 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002469 }
François Gaffiec005e562018-11-06 15:04:49 +01002470 bool shouldWait =
2471 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2472 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2473 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002474 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002475 const bool needToCloseBitPerfectOutput =
2476 (com::android::media::audioserver::
2477 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2478 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2479 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002480 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002481 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002482 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002483 // An output has a shared device if
2484 // - managed by the same hw module
2485 // - supports the currently selected device
2486 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002487 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002488
Eric Laurent77305a62016-07-25 16:39:22 -07002489 // force a device change if any other output is:
2490 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002491 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002492 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002493 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002494 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002495 // change the device currently selected by the other output.
2496 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002497 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002498 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002499 force = true;
2500 }
2501 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002502 // a notification so that audio focus effect can propagate, or that a mute/unmute
2503 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002504 const uint32_t latencyMs = desc->latency();
2505 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2506
2507 if (shouldWait && isActive && (waitMs < latencyMs)) {
2508 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002509 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002510
2511 // Require mute check if another output is on a shared device
2512 // and currently active to have proper drain and avoid pops.
2513 // Note restoring AudioTracks onto this output needs to invoke
2514 // a volume ramp if there is no mute.
2515 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002516
2517 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2518 outputsToReopen.push_back(desc);
2519 }
Eric Laurente552edb2014-03-10 17:42:56 -07002520 }
2521 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002522
jiabin220eea12024-05-17 17:55:20 +00002523 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002524 // If the output is open with preferred mixer attributes, but the routed device is
2525 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2526 // changed.
2527 return DEAD_OBJECT;
2528 }
jiabin220eea12024-05-17 17:55:20 +00002529 for (auto& outputToReopen : outputsToReopen) {
2530 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2531 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002532 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302533 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2534 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002535
Eric Laurente552edb2014-03-10 17:42:56 -07002536 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002537 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002538 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002539 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002540 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002541 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002542 outputDesc->useHwGain() /*force*/)) {
2543 // request AudioService to reinitialize the volume curves asynchronously
2544 ALOGE("checkAndSetVolume failed, requesting volume range init");
2545 mpClientInterface->onVolumeRangeInitRequest();
2546 };
Eric Laurente552edb2014-03-10 17:42:56 -07002547
2548 // update the outputs if starting an output with a stream that can affect notification
2549 // routing
2550 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002551
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002552 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002553 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002554 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002555 }
Eric Laurentdc462862016-07-19 12:29:53 -07002556
2557 if (waitMs > muteWaitMs) {
2558 *delayMs = waitMs - muteWaitMs;
2559 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002560
2561 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2562 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2563 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2564 // change occurs after the MixerThread starts and causes a stream volume
2565 // glitch.
2566 //
2567 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002568 }
Eric Laurentdc462862016-07-19 12:29:53 -07002569
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002570 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002571 mEngine->getForceUse(
2572 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002573 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002574 }
2575
Eric Laurent97ac8712018-07-27 18:59:02 -07002576 // Automatically enable the remote submix input when output is started on a re routing mix
2577 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002578 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2579 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002580 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2581 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2582 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002583 "remote-submix",
2584 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002585 }
2586
Eric Laurent96d1dda2022-03-14 17:14:19 +01002587 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2588
Eric Laurente552edb2014-03-10 17:42:56 -07002589 return NO_ERROR;
2590}
2591
Eric Laurent96d1dda2022-03-14 17:14:19 +01002592void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2593 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2594 bool isUnicastActive = isLeUnicastActive();
2595
2596 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002597 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002598 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2599 for (size_t i = 0; i < mOutputs.size(); i++) {
2600 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2601 if (desc != ignoredOutput && desc->isActive()
2602 && ((isUnicastActive &&
2603 !desc->devices().
2604 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2605 || (wasUnicastActive &&
2606 !desc->devices().getDevicesFromTypes(
2607 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2608 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2609 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002610 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002611 // If the device is using preferred mixer attributes, the output need to reopen
2612 // with default configuration when the new selected devices are different from
2613 // current routing devices.
2614 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2615 continue;
2616 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302617 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002618 // re-apply device specific volume if not done by setOutputDevice()
2619 if (!force) {
2620 applyStreamVolumes(desc, newDevices.types(), delayMs);
2621 }
2622 }
2623 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002624 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002625 }
2626}
2627
Eric Laurent8fc147b2018-07-22 19:13:55 -07002628status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002629{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002630 ALOGV("%s portId %d", __FUNCTION__, portId);
2631
2632 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2633 if (outputDesc == 0) {
2634 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002635 return BAD_VALUE;
2636 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002637 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002638
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002639 if (client->hasPreferredDevice(true)) {
2640 // playback activity with preferred device impacts routing occurred, inform upper layers
2641 mpClientInterface->onRoutingUpdated();
2642 }
2643
Eric Laurent97ac8712018-07-27 18:59:02 -07002644 ALOGV("stopOutput() output %d, stream %d, session %d",
2645 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002646
Eric Laurent97ac8712018-07-27 18:59:02 -07002647 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002648
Eric Laurent733ce942017-12-07 12:18:25 -08002649 if (status == NO_ERROR ) {
2650 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002651 } else {
2652 return status;
2653 }
2654
2655 if (outputDesc->devices().size() == 1) {
2656 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2657 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002658 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002659 if (info != nullptr && info->getUid() == client->uid()) {
2660 info->decreaseActiveClient();
2661 if (info->getActiveClientCount() == 0) {
2662 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002663 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002664 }
2665 }
jiabin220eea12024-05-17 17:55:20 +00002666 if (com::android::media::audioserver::
2667 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2668 !outputReopened && outputDesc->isBitPerfect()) {
2669 // Only need to update the clients' internal mute when the output is bit-perfect and it
2670 // is not reopened.
2671 updateClientsInternalMute(outputDesc);
2672 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002673 }
2674 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002675}
2676
Eric Laurent97ac8712018-07-27 18:59:02 -07002677status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2678 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002679{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002680 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002681 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002682 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002683 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002684
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002685 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2686
François Gaffie1c878552018-11-22 16:53:21 +01002687 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2688 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002689 // Automatically disable the remote submix input when output is stopped on a
2690 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002691 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002692 if (isSingleDeviceType(
2693 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002694 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002695 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002696 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2697 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002698 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002699 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002700 }
2701 }
2702 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002703 if (client->hasPreferredDevice(true) &&
2704 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002705 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002706 forceDeviceUpdate = true;
2707 }
2708
Eric Laurente552edb2014-03-10 17:42:56 -07002709 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002710 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002711
Eric Laurente552edb2014-03-10 17:42:56 -07002712 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002713 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002714 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002715 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002716
2717 // If the routing does not change, if an output is routed on a device using HwGain
2718 // (aka setAudioPortConfig) and there are still active clients following different
2719 // volume group(s), force reapply volume
2720 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2721 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2722
Eric Laurente552edb2014-03-10 17:42:56 -07002723 // delay the device switch by twice the latency because stopOutput() is executed when
2724 // the track stop() command is received and at that time the audio track buffer can
2725 // still contain data that needs to be drained. The latency only covers the audio HAL
2726 // and kernel buffers. Also the latency does not always include additional delay in the
2727 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302728 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002729 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002730
2731 // force restoring the device selection on other active outputs if it differs from the
2732 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002733 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002734 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002735 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002736 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002737 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002738 desc->isActive() &&
2739 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002740 (newDevices != desc->devices())) {
2741 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2742 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002743
jiabin220eea12024-05-17 17:55:20 +00002744 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002745 // If the device is using preferred mixer attributes, the output need to
2746 // reopen with default configuration when the new selected devices are
2747 // different from current routing devices.
2748 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2749 continue;
2750 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302751 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002752
Eric Laurent57de36c2016-09-28 16:59:11 -07002753 // re-apply device specific volume if not done by setOutputDevice()
2754 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002755 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002756 }
Eric Laurente552edb2014-03-10 17:42:56 -07002757 }
2758 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002759 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002760 // update the outputs if stopping one with a stream that can affect notification routing
2761 handleNotificationRoutingForStream(stream);
2762 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002763
2764 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2765 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002766 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002767 }
2768
François Gaffiec005e562018-11-06 15:04:49 +01002769 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002770 selectOutputForMusicEffects();
2771 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002772
2773 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2774
Eric Laurente552edb2014-03-10 17:42:56 -07002775 return NO_ERROR;
2776 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002777 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002778 return INVALID_OPERATION;
2779 }
2780}
2781
jiabinbce0c1d2020-10-05 11:20:18 -07002782bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002783{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002784 ALOGV("%s portId %d", __FUNCTION__, portId);
2785
2786 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2787 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002788 // If an output descriptor is closed due to a device routing change,
2789 // then there are race conditions with releaseOutput from tracks
2790 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2791 // destroyed shortly thereafter.
2792 //
2793 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002794 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002795 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002796 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002797
2798 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002799
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302800 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2801 if (outputDesc->isClientActive(client)) {
2802 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2803 stopOutput(portId);
2804 }
2805
Eric Laurent8fc147b2018-07-22 19:13:55 -07002806 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2807 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002808 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002809 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002810 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002811 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002812 if (--outputDesc->mDirectOpenCount == 0) {
2813 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002814 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002815 }
2816 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302817
Andy Hung39efb7a2018-09-26 15:39:28 -07002818 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002819 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2820 // The output is pending reopened to query dynamic profiles and
2821 // there is no active clients
2822 closeOutput(outputDesc->mIoHandle);
2823 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2824 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2825 if (newOutputDesc == nullptr) {
2826 ALOGE("%s failed to open output", __func__);
2827 }
2828 return true;
2829 }
2830 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002831}
2832
Eric Laurentcaf7f482014-11-25 17:50:47 -08002833status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2834 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002835 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002836 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002837 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002838 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002839 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002840 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002841 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002842 audio_port_handle_t *portId,
2843 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002844{
François Gaffiec005e562018-11-06 15:04:49 +01002845 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002846 "flags %#x attributes=%s requested device ID %d",
2847 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2848 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002849
Eric Laurentad2e7b92017-09-14 20:06:42 -07002850 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002851 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002852 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002853 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002854 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002855 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002856 sp<RecordClientDescriptor> clientDesc;
2857 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002858 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002859 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860
2861 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2862 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2863 return INVALID_OPERATION;
2864 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002865
Francois Gaffie716e1432019-01-14 16:58:59 +01002866 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2867 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002868 }
2869
Paul McLean466dc8e2015-04-17 13:15:36 -06002870 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002871 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002872 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002873
Eric Laurentad2e7b92017-09-14 20:06:42 -07002874 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2875 // possible
2876 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2877 *input != AUDIO_IO_HANDLE_NONE) {
2878 ssize_t index = mInputs.indexOfKey(*input);
2879 if (index < 0) {
2880 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2881 status = BAD_VALUE;
2882 goto error;
2883 }
2884 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002885 RecordClientVector clients = inputDesc->getClientsForSession(session);
2886 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002887 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2888 status = BAD_VALUE;
2889 goto error;
2890 }
2891 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2892 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002893 // corresponds to a new client and is only permitted from the same UID.
2894 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002895 if (clients.size() > 1) {
2896 for (const auto& client : clients) {
2897 // The client map is ordered by key values (portId) and portIds are allocated
2898 // incrementaly. So the first client in this list is the one opened by audio flinger
2899 // when the mmap stream is created and should be ignored as it does not correspond
2900 // to an actual client
2901 if (client == *clients.cbegin()) {
2902 continue;
2903 }
2904 if (uid != client->uid() && !client->isSilenced()) {
2905 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2906 uid, client->portId(), client->uid());
2907 status = INVALID_OPERATION;
2908 goto error;
2909 }
Eric Laurent331679c2018-04-16 17:03:16 -07002910 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002911 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002912 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002913 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002914
Eric Laurentfecbceb2021-02-09 14:46:43 +01002915 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002916 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002917 }
2918
2919 *input = AUDIO_IO_HANDLE_NONE;
2920 *inputType = API_INPUT_INVALID;
2921
Francois Gaffie716e1432019-01-14 16:58:59 +01002922 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002923 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002924 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002925 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002926 ALOGW("%s could not find input mix for attr %s",
2927 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002928 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002929 }
jiabinc1de2df2019-05-07 14:26:40 -07002930 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2931 String8(attr->tags + strlen("addr=")),
2932 AUDIO_FORMAT_DEFAULT);
2933 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002934 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002935 __func__, attributes.source, attributes.tags);
2936 status = BAD_VALUE;
2937 goto error;
2938 }
2939
Kevin Rocard25f9b052019-02-27 15:08:54 -08002940 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2941 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2942 } else {
2943 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2944 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002945 if (virtualDeviceId) {
2946 *virtualDeviceId = policyMix->mVirtualDeviceId;
2947 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002948 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002949 if (explicitRoutingDevice != nullptr) {
2950 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002951 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002952 // Prevent from storing invalid requested device id in clients
2953 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002954 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002955 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2956 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002957 }
François Gaffie11d30102018-11-02 16:09:09 +01002958 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002959 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002960 status = BAD_VALUE;
2961 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002962 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002963 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2964 *inputType = API_INPUT_MIX_CAPTURE;
2965 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002966 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2967 // there is an external policy, but this input is attached to a mix of recorders,
2968 // meaning it receives audio injected into the framework, so the recorder doesn't
2969 // know about it and is therefore considered "legacy"
2970 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002971
2972 if (virtualDeviceId) {
2973 *virtualDeviceId = policyMix->mVirtualDeviceId;
2974 }
François Gaffie11d30102018-11-02 16:09:09 +01002975 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002976 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002977 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002978 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002979 } else {
2980 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002981 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002982
Eric Laurent599c7582015-12-07 18:05:55 -08002983 }
2984
François Gaffiec005e562018-11-06 15:04:49 +01002985 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002986 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002987 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002988 AudioProfileVector profiles;
2989 status_t ret = getProfilesForDevices(
2990 DeviceVector(device), profiles, flags, true /*isInput*/);
2991 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002992 const auto channels = profiles[0]->getChannels();
2993 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2994 config->channel_mask = *channels.begin();
2995 }
2996 const auto sampleRates = profiles[0]->getSampleRates();
2997 if (!sampleRates.empty() &&
2998 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2999 config->sample_rate = *sampleRates.begin();
3000 }
jiabinf1c73972022-04-14 16:28:52 -07003001 config->format = profiles[0]->getFormat();
3002 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003003 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003004 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003005
Marvin Ramine5a122d2023-12-07 13:57:59 +01003006
3007 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3008 *virtualDeviceId = policyMix->mVirtualDeviceId;
3009 }
3010
Eric Laurent8f42ea12018-08-08 09:08:25 -07003011exit:
3012
François Gaffiec005e562018-11-06 15:04:49 +01003013 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3014 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003015
Francois Gaffie716e1432019-01-14 16:58:59 +01003016 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003017 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003018 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003019
Mikhail Naganov2996f672019-04-18 12:29:59 -07003020 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003021 requestedDeviceId, attributes.source, flags,
3022 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003023 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003024 // Move (if found) effect for the client session to its input
3025 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003026 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003027
3028 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3029 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003030
Eric Laurent599c7582015-12-07 18:05:55 -08003031 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003032
3033error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003034 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003035}
3036
3037
François Gaffie11d30102018-11-02 16:09:09 +01003038audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003039 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003040 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003041 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003042 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003043 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003044{
3045 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003046 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003047 bool isSoundTrigger = false;
3048
François Gaffiec005e562018-11-06 15:04:49 +01003049 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003050 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3051 if (index >= 0) {
3052 input = mSoundTriggerSessions.valueFor(session);
3053 isSoundTrigger = true;
3054 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3055 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3056 } else {
3057 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003058 }
François Gaffiec005e562018-11-06 15:04:49 +01003059 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003060 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003061 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003062 }
3063
Carter Hsua3abb402021-10-26 11:11:20 +08003064 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3065 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3066 }
3067
Eric Laurentfe231122017-11-17 17:48:06 -08003068 // sampling rate and flags may be updated by getInputProfile
3069 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3070 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003071 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003072 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003073 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003074 // find a compatible input profile (not necessarily identical in parameters)
3075 sp<IOProfile> profile = getInputProfile(
3076 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3077 if (profile == nullptr) {
3078 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003079 }
jiabin2fd710d2022-05-02 23:20:22 +00003080
Glenn Kasten05ddca52016-02-11 08:17:12 -08003081 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003082 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003083 if (samplingRate == 0) {
3084 samplingRate = profileSamplingRate;
3085 }
Eric Laurente552edb2014-03-10 17:42:56 -07003086
Eric Laurent322b4d22015-04-03 15:57:54 -07003087 if (profile->getModuleHandle() == 0) {
3088 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003089 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003090 }
3091
Eric Laurentec376dc2021-04-08 20:41:22 +02003092 // Reuse an already opened input if a client with the same session ID already exists
3093 // on that input
3094 for (size_t i = 0; i < mInputs.size(); i++) {
3095 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3096 if (desc->mProfile != profile) {
3097 continue;
3098 }
3099 RecordClientVector clients = desc->clientsList();
3100 for (const auto &client : clients) {
3101 if (session == client->session()) {
3102 return desc->mIoHandle;
3103 }
3104 }
3105 }
3106
Eric Laurent3974e3b2017-12-07 17:58:43 -08003107 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003108 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003109 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003110 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003111 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003112 continue;
3113 }
3114 // if sound trigger, reuse input if used by other sound trigger on same session
3115 // else
3116 // reuse input if active client app is not in IDLE state
3117 //
3118 RecordClientVector clients = desc->clientsList();
3119 bool doClose = false;
3120 for (const auto& client : clients) {
3121 if (isSoundTrigger != client->isSoundTrigger()) {
3122 continue;
3123 }
3124 if (client->isSoundTrigger()) {
3125 if (session == client->session()) {
3126 return desc->mIoHandle;
3127 }
3128 continue;
3129 }
3130 if (client->active() && client->appState() != APP_STATE_IDLE) {
3131 return desc->mIoHandle;
3132 }
3133 doClose = true;
3134 }
3135 if (doClose) {
3136 closeInput(desc->mIoHandle);
3137 } else {
3138 i++;
3139 }
3140 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003141 }
3142
Eric Laurentfe231122017-11-17 17:48:06 -08003143 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003144
Eric Laurentfe231122017-11-17 17:48:06 -08003145 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3146 lConfig.sample_rate = profileSamplingRate;
3147 lConfig.channel_mask = profileChannelMask;
3148 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003149
François Gaffie11d30102018-11-02 16:09:09 +01003150 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003151
3152 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003153 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003154 (profileSamplingRate != lConfig.sample_rate) ||
3155 !audio_formats_match(profileFormat, lConfig.format) ||
3156 (profileChannelMask != lConfig.channel_mask)) {
3157 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003158 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003159 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003160 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003161 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003162 }
Eric Laurent599c7582015-12-07 18:05:55 -08003163 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003164 }
3165
Eric Laurentc722f302014-12-10 11:21:49 -08003166 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003167
Eric Laurent599c7582015-12-07 18:05:55 -08003168 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003169 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003170
Eric Laurent599c7582015-12-07 18:05:55 -08003171 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003172}
3173
Eric Laurent4eb58f12018-12-07 16:41:02 -08003174status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003175{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003176 ALOGV("%s portId %d", __FUNCTION__, portId);
3177
3178 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3179 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003180 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003181 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003182 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003183 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003184 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003185 if (client->active()) {
3186 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3187 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003188 }
3189
Eric Laurent8f42ea12018-08-08 09:08:25 -07003190 audio_session_t session = client->session();
3191
Eric Laurent4eb58f12018-12-07 16:41:02 -08003192 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003193
Eric Laurent4eb58f12018-12-07 16:41:02 -08003194 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003195
Eric Laurent4eb58f12018-12-07 16:41:02 -08003196 status_t status = inputDesc->start();
3197 if (status != NO_ERROR) {
3198 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003199 }
Eric Laurente552edb2014-03-10 17:42:56 -07003200
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003201 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003202 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003203 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003204
Eric Laurent8f42ea12018-08-08 09:08:25 -07003205 // indicate active capture to sound trigger service if starting capture from a mic on
3206 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003207 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003208 if (device != nullptr) {
3209 status = setInputDevice(input, device, true /* force */);
3210 } else {
3211 ALOGW("%s no new input device can be found for descriptor %d",
3212 __FUNCTION__, inputDesc->getId());
3213 status = BAD_VALUE;
3214 }
Eric Laurente552edb2014-03-10 17:42:56 -07003215
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003216 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003217 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003218 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003219 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003220 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3221 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003222 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003223 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003224
François Gaffie11d30102018-11-02 16:09:09 +01003225 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3226 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003227 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003228 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003229 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003230
Eric Laurent8f42ea12018-08-08 09:08:25 -07003231 // automatically enable the remote submix output when input is started if not
3232 // used by a policy mix of type MIX_TYPE_RECORDERS
3233 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003234 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003235 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003236 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003237 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003238 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3239 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003240 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003241 if (address != "") {
3242 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3243 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003244 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003245 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003246 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003247 } else if (status != NO_ERROR) {
3248 // Restore client activity state.
3249 inputDesc->setClientActive(client, false);
3250 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003251 }
3252
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003253 ALOGV("%s input %d source = %d status = %d exit",
3254 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003255
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003256 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003257}
3258
Eric Laurent8fc147b2018-07-22 19:13:55 -07003259status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003260{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003261 ALOGV("%s portId %d", __FUNCTION__, portId);
3262
3263 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3264 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003265 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003266 return BAD_VALUE;
3267 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003268 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003269 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003270 if (!client->active()) {
3271 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003272 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003273 }
Carter Hsue6139d52021-07-08 10:30:20 +08003274 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003275 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003276
Eric Laurent8f42ea12018-08-08 09:08:25 -07003277 inputDesc->stop();
3278 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003279 auto current_source = inputDesc->source();
3280 setInputDevice(input, getNewInputDevice(inputDesc),
3281 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003282 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003283 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003285 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003286 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3287 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003288 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003289 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003290
3291 // automatically disable the remote submix output when input is stopped if not
3292 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003293 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003294 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003295 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003296 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003297 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3298 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003299 }
3300 if (address != "") {
3301 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3302 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003303 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003304 }
3305 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003306 resetInputDevice(input);
3307
3308 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3309 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003310 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3311 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003312 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003313 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003314 }
3315 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003316 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003317 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003318}
3319
Eric Laurent8fc147b2018-07-22 19:13:55 -07003320void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003321{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003322 ALOGV("%s portId %d", __FUNCTION__, portId);
3323
3324 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3325 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003326 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003327 return;
3328 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003329 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003330 audio_io_handle_t input = inputDesc->mIoHandle;
3331
Eric Laurent8f42ea12018-08-08 09:08:25 -07003332 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003333
Andy Hung39efb7a2018-09-26 15:39:28 -07003334 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003335
3336 // If no more clients are present in this session, park effects to an orphan chain
3337 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3338 if (clientsOnSession.size() == 0) {
3339 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3340 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003341 if (inputDesc->getClientCount() > 0) {
3342 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003343 return;
3344 }
3345
Eric Laurent05b90f82014-08-27 15:32:29 -07003346 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003347 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003348 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003349}
3350
Eric Laurent8f42ea12018-08-08 09:08:25 -07003351void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003352{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003353 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003354
3355 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003356 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003357 }
3358}
3359
Eric Laurent8f42ea12018-08-08 09:08:25 -07003360void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3361{
3362 stopInput(portId);
3363 releaseInput(portId);
3364}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003365
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003366bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3367 if (input->clientsList().size() == 0
3368 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3369 return true;
3370 }
3371 for (const auto& client : input->clientsList()) {
3372 sp<DeviceDescriptor> device =
3373 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3374 client->session());
3375 if (!input->supportedDevices().contains(device)) {
3376 return true;
3377 }
3378 }
3379 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3380 return false;
3381}
3382
Eric Laurent0dd51852019-04-19 18:18:58 -07003383void AudioPolicyManager::checkCloseInputs() {
3384 // After connecting or disconnecting an input device, close input if:
3385 // - it has no client (was just opened to check profile) OR
3386 // - none of its supported devices are connected anymore OR
3387 // - one of its clients cannot be routed to one of its supported
3388 // devices anymore. Otherwise update device selection
3389 std::vector<audio_io_handle_t> inputsToClose;
3390 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003391 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003392 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003393 }
3394 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003395 for (const audio_io_handle_t handle : inputsToClose) {
3396 ALOGV("%s closing input %d", __func__, handle);
3397 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003398 }
Eric Laurentd4692962014-05-05 18:13:44 -07003399}
3400
Vlad Popa87e0e582024-05-20 18:49:20 -07003401status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3402 const char *address __unused,
3403 bool enabled,
3404 audio_stream_type_t streamToDriveAbs)
3405{
3406 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3407 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3408 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3409 toString(streamToDriveAbs).c_str());
3410 return BAD_VALUE;
3411 }
3412
3413 if (enabled) {
3414 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3415 } else {
3416 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3417 }
3418
3419 return NO_ERROR;
3420}
3421
François Gaffie251c7f02018-11-07 10:41:08 +01003422void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003423{
3424 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003425 if (indexMin < 0 || indexMax < 0) {
3426 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3427 return;
3428 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003429 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003430
3431 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003432 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3433 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003434 continue;
3435 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003436 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003437 }
Eric Laurente552edb2014-03-10 17:42:56 -07003438}
3439
Eric Laurente0720872014-03-11 09:30:41 -07003440status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003441 int index,
3442 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003443{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003444 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003445 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3446 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3447 return NO_ERROR;
3448 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303449 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3450 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003451 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003452}
3453
Eric Laurente0720872014-03-11 09:30:41 -07003454status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003455 int *index,
3456 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003457{
François Gaffiec005e562018-11-06 15:04:49 +01003458 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3459 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003460 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003461 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003462 deviceTypes = mEngine->getOutputDevicesForStream(
3463 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003464 }
jiabin9a3361e2019-10-01 09:38:30 -07003465 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003466}
3467
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003468status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003469 int index,
3470 audio_devices_t device)
3471{
3472 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003473 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3474 if (group == VOLUME_GROUP_NONE) {
3475 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003476 return BAD_VALUE;
3477 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003478 ALOGV("%s: group %d matching with %s index %d",
3479 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003480 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003481 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003482 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003483 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3484 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3485 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3486 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003487 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3488
3489 status = setVolumeCurveIndex(index, device, curves);
3490 if (status != NO_ERROR) {
3491 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3492 return status;
3493 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003494
jiabin9a3361e2019-10-01 09:38:30 -07003495 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003496 auto curCurvAttrs = curves.getAttributes();
3497 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3498 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003499 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003500 } else if (!curves.getStreamTypes().empty()) {
3501 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003502 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003503 } else {
3504 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3505 return BAD_VALUE;
3506 }
jiabin9a3361e2019-10-01 09:38:30 -07003507 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3508 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003509
François Gaffiecfe17322018-11-07 13:41:29 +01003510 // update volume on all outputs and streams matching the following:
3511 // - The requested stream (or a stream matching for volume control) is active on the output
3512 // - The device (or devices) selected by the engine for this stream includes
3513 // the requested device
3514 // - For non default requested device, currently selected device on the output is either the
3515 // requested device or one of the devices selected by the engine for this stream
3516 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3517 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003518 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003519 for (size_t i = 0; i < mOutputs.size(); i++) {
3520 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003521 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003522
jiabin9a3361e2019-10-01 09:38:30 -07003523 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3524 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003525 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003526
3527 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003528 continue;
3529 }
3530 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3531 curDevices.find(device) == curDevices.end()) {
3532 continue;
3533 }
3534 bool applyVolume = false;
3535 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3536 curSrcDevices.insert(device);
3537 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003538 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3539 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003540 } else {
3541 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3542 }
3543 if (!applyVolume) {
3544 continue; // next output
3545 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003546 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3547 // If a higher priority strategy is active, and the output is routed to a device with a
3548 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003549 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003550 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003551 // If the volume source is active with higher priority source, ensure at least Sw Muted
3552 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003553 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3554 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3555 false /*preferredDevice*/);
3556 if (activeClients.empty()) {
3557 continue;
3558 }
3559 bool isPreempted = false;
3560 bool isHigherPriority = productStrategy < strategy;
3561 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003562 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003563 ALOGV("%s: Strategy=%d (\nrequester:\n"
3564 " group %d, volumeGroup=%d attributes=%s)\n"
3565 " higher priority source active:\n"
3566 " volumeGroup=%d attributes=%s) \n"
3567 " on output %zu, bailing out", __func__, productStrategy,
3568 group, group, toString(attributes).c_str(),
3569 client->volumeSource(), toString(client->attributes()).c_str(), i);
3570 applyVolume = false;
3571 isPreempted = true;
3572 break;
3573 }
3574 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003575 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003576 applyVolume = true;
3577 }
3578 }
3579 if (isPreempted || applyVolume) {
3580 break;
3581 }
3582 }
3583 if (!applyVolume) {
3584 continue; // next output
3585 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003586 }
François Gaffieed91f582020-01-31 10:35:37 +01003587 //FIXME: workaround for truncated touch sounds
3588 // delayed volume change for system stream to be removed when the problem is
3589 // handled by system UI
3590 status_t volStatus = checkAndSetVolume(
3591 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003592 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003593 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3594 if (volStatus != NO_ERROR) {
3595 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003596 }
3597 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003598
3599 // update voice volume if the an active call route exists
3600 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3601 && (curSrcDevices.find(
3602 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3603 != curSrcDevices.end())) {
3604 bool isVoiceVolSrc;
3605 bool isBtScoVolSrc;
3606 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3607 isVoiceVolSrc, isBtScoVolSrc, __func__)
3608 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003609 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3610 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3611 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003612 }
3613 }
3614
François Gaffiecfe17322018-11-07 13:41:29 +01003615 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3616 return status;
3617}
3618
François Gaffieaaac0fd2018-11-22 17:56:39 +01003619status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003620 audio_devices_t device,
3621 IVolumeCurves &volumeCurves)
3622{
3623 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3624 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003625 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3626 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003627 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303628 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3629 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003630 return BAD_VALUE;
3631 }
3632 if (!audio_is_output_device(device)) {
3633 return BAD_VALUE;
3634 }
3635
3636 // Force max volume if stream cannot be muted
3637 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3638
François Gaffieaaac0fd2018-11-22 17:56:39 +01003639 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003640 volumeCurves.addCurrentVolumeIndex(device, index);
3641 return NO_ERROR;
3642}
3643
3644status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3645 int &index,
3646 audio_devices_t device)
3647{
3648 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3649 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003650 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003651 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003652 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003653 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003654 }
jiabin9a3361e2019-10-01 09:38:30 -07003655 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003656}
3657
3658status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3659 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003660 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003661{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003662 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003663 return BAD_VALUE;
3664 }
jiabin9a3361e2019-10-01 09:38:30 -07003665 index = curves.getVolumeIndex(deviceTypes);
3666 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003667 return NO_ERROR;
3668}
3669
3670status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3671 int &index)
3672{
3673 index = getVolumeCurves(attr).getVolumeIndexMin();
3674 return NO_ERROR;
3675}
3676
3677status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3678 int &index)
3679{
3680 index = getVolumeCurves(attr).getVolumeIndexMax();
3681 return NO_ERROR;
3682}
3683
Eric Laurent36829f92017-04-07 19:04:42 -07003684audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003685{
3686 // select one output among several suitable for global effects.
3687 // The priority is as follows:
3688 // 1: An offloaded output. If the effect ends up not being offloadable,
3689 // AudioFlinger will invalidate the track and the offloaded output
3690 // will be closed causing the effect to be moved to a PCM output.
3691 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003692 // 3: The primary output
3693 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003694
François Gaffiec005e562018-11-06 15:04:49 +01003695 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3696 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003697 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003698
Eric Laurent36829f92017-04-07 19:04:42 -07003699 if (outputs.size() == 0) {
3700 return AUDIO_IO_HANDLE_NONE;
3701 }
Eric Laurente552edb2014-03-10 17:42:56 -07003702
Eric Laurent36829f92017-04-07 19:04:42 -07003703 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3704 bool activeOnly = true;
3705
3706 while (output == AUDIO_IO_HANDLE_NONE) {
3707 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3708 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3709 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3710
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003711 for (audio_io_handle_t output : outputs) {
3712 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003713 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003714 continue;
3715 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003716 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3717 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003718 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003719 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003720 }
3721 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003722 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003723 }
3724 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003725 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003726 }
3727 }
3728 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3729 output = outputOffloaded;
3730 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3731 output = outputDeepBuffer;
3732 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3733 output = outputPrimary;
3734 } else {
3735 output = outputs[0];
3736 }
3737 activeOnly = false;
3738 }
3739
3740 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003741 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3742 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003743 mMusicEffectOutput = output;
3744 }
3745
3746 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003747 return output;
3748}
3749
Eric Laurent36829f92017-04-07 19:04:42 -07003750audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3751{
3752 return selectOutputForMusicEffects();
3753}
3754
Eric Laurente0720872014-03-11 09:30:41 -07003755status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003756 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003757 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003758 int session,
3759 int id)
3760{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003761 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003762 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003763 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003764 index = mInputs.indexOfKey(io);
3765 if (index < 0) {
3766 ALOGW("registerEffect() unknown io %d", io);
3767 return INVALID_OPERATION;
3768 }
Eric Laurente552edb2014-03-10 17:42:56 -07003769 }
3770 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003771 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3772 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3773 || strategy == PRODUCT_STRATEGY_NONE));
3774 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003775}
3776
Eric Laurentc241b0d2018-11-28 09:08:49 -08003777status_t AudioPolicyManager::unregisterEffect(int id)
3778{
3779 if (mEffects.getEffect(id) == nullptr) {
3780 return INVALID_OPERATION;
3781 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003782 if (mEffects.isEffectEnabled(id)) {
3783 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3784 setEffectEnabled(id, false);
3785 }
3786 return mEffects.unregisterEffect(id);
3787}
3788
3789status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3790{
3791 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3792 if (effect == nullptr) {
3793 return INVALID_OPERATION;
3794 }
3795
3796 status_t status = mEffects.setEffectEnabled(id, enabled);
3797 if (status == NO_ERROR) {
3798 mInputs.trackEffectEnabled(effect, enabled);
3799 }
3800 return status;
3801}
3802
Eric Laurent6c796322019-04-09 14:13:17 -07003803
3804status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3805{
3806 mEffects.moveEffects(ids, io);
3807 return NO_ERROR;
3808}
3809
Eric Laurentc75307b2015-03-17 15:29:32 -07003810bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3811{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003812 auto vs = toVolumeSource(stream, false);
3813 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003814}
3815
3816bool AudioPolicyManager::isStreamActiveRemotely(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.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003820}
3821
Eric Laurente0720872014-03-11 09:30:41 -07003822bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003823{
3824 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003825 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003826 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003827 return true;
3828 }
3829 }
3830 return false;
3831}
3832
Eric Laurent275e8e92014-11-30 15:14:47 -08003833// Register a list of custom mixes with their attributes and format.
3834// When a mix is registered, corresponding input and output profiles are
3835// added to the remote submix hw module. The profile contains only the
3836// parameters (sampling rate, format...) specified by the mix.
3837// The corresponding input remote submix device is also connected.
3838//
3839// When a remote submix device is connected, the address is checked to select the
3840// appropriate profile and the corresponding input or output stream is opened.
3841//
3842// When capture starts, getInputForAttr() will:
3843// - 1 look for a mix matching the address passed in attribtutes tags if any
3844// - 2 if none found, getDeviceForInputSource() will:
3845// - 2.1 look for a mix matching the attributes source
3846// - 2.2 if none found, default to device selection by policy rules
3847// At this time, the corresponding output remote submix device is also connected
3848// and active playback use cases can be transferred to this mix if needed when reconnecting
3849// after AudioTracks are invalidated
3850//
3851// When playback starts, getOutputForAttr() will:
3852// - 1 look for a mix matching the address passed in attribtutes tags if any
3853// - 2 if none found, look for a mix matching the attributes usage
3854// - 3 if none found, default to device and output selection by policy rules.
3855
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003856status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003857{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003858 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3859 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003860 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003861 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003862 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003863 // examine each mix's route type
3864 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003865 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003866 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3867 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3868 ALOGE("Unsupported Policy Mix %zu of %zu: "
3869 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3870 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003871 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003872 break;
3873 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003874 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3875 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003876 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003877 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3878 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003879 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003880 rSubmixModule = mHwModules.getModuleFromName(
3881 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3882 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003883 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003884 i);
3885 res = INVALID_OPERATION;
3886 break;
3887 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003888 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003889
Eric Laurent97ac8712018-07-27 18:59:02 -07003890 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003891 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003892 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003893 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003894 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3895 } else {
3896 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3897 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003898 }
François Gaffie036e1e92015-03-19 10:16:24 +01003899
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003900 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003901 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003902 res = INVALID_OPERATION;
3903 break;
3904 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003905 audio_config_t outputConfig = mix.mFormat;
3906 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003907 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3908 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003909 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3910 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003911 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003912 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3913 audio_is_linear_pcm(outputConfig.format)
3914 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003915 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003916 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3917 audio_is_linear_pcm(inputConfig.format)
3918 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003919
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003920 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003921 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003922 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003923 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003924 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003925 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003926 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003927 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3928 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003929 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003930 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003931 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003932
3933 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3934 mix.mDeviceType, mix.mDeviceAddress,
3935 String8(), AUDIO_FORMAT_DEFAULT);
3936 if (device == nullptr) {
3937 res = INVALID_OPERATION;
3938 break;
3939 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003940
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003941 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003942 // First try to find an already opened output supporting the device
3943 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003944 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003945
Eric Laurentc529cf62020-04-17 18:19:10 -07003946 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003947 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003948 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003949 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003950 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003951 } else {
3952 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003953 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003954 }
3955 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003956 // If no output found, try to find a direct output profile supporting the device
3957 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3958 sp<HwModule> module = mHwModules[i];
3959 for (size_t j = 0;
3960 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3961 j++) {
3962 sp<IOProfile> profile = module->getOutputProfiles()[j];
3963 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3964 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3965 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003966 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003967 res = INVALID_OPERATION;
3968 } else {
3969 foundOutput = true;
3970 }
3971 }
3972 }
3973 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003974 if (res != NO_ERROR) {
3975 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003976 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003977 res = INVALID_OPERATION;
3978 break;
3979 } else if (!foundOutput) {
3980 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003981 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003982 res = INVALID_OPERATION;
3983 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003984 } else {
3985 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003986 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003987 }
Eric Laurentc722f302014-12-10 11:21:49 -08003988 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003989 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003990 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003991 if (audio_flags::audio_mix_ownership()) {
3992 // Only unregister mixes that were actually registered to not accidentally unregister
3993 // mixes that already existed previously.
3994 unregisterPolicyMixes(registeredMixes);
3995 registeredMixes.clear();
3996 } else {
3997 unregisterPolicyMixes(mixes);
3998 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003999 } else if (checkOutputs) {
4000 checkForDeviceAndOutputChanges();
4001 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004002 }
4003 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004004}
4005
4006status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4007{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004008 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004009 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004010 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004011 sp<HwModule> rSubmixModule;
4012 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004013 for (const auto& mix : mixes) {
4014 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004015
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004016 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004017 rSubmixModule = mHwModules.getModuleFromName(
4018 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4019 if (rSubmixModule == 0) {
4020 res = INVALID_OPERATION;
4021 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004022 }
4023 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004024
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004025 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004026
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004027 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004028 res = INVALID_OPERATION;
4029 continue;
4030 }
4031
Marvin Ramin0783e202024-03-05 12:45:50 +01004032 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004033 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004034 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4035 status_t currentRes =
4036 setDeviceConnectionStateInt(device,
4037 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4038 address.c_str(),
4039 "remote-submix",
4040 AUDIO_FORMAT_DEFAULT);
4041 if (!audio_flags::audio_mix_ownership()) {
4042 res = currentRes;
4043 }
4044 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004045 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004046 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004047 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004048 }
4049 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004050 }
jiabin5740f082019-08-19 15:08:30 -07004051 rSubmixModule->removeOutputProfile(address.c_str());
4052 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004053
Kevin Rocard153f92d2018-12-18 18:33:28 -08004054 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004055 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004056 res = INVALID_OPERATION;
4057 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004058 } else {
4059 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004060 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004061 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004062 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004063
4064 if (res == NO_ERROR && checkOutputs) {
4065 checkForDeviceAndOutputChanges();
4066 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004067 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004068 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004069}
4070
Marvin Raminbdefaf02023-11-01 09:10:32 +01004071status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4072 if (!audio_flags::audio_mix_test_api()) {
4073 return INVALID_OPERATION;
4074 }
4075
4076 _aidl_return.clear();
4077 _aidl_return.reserve(mPolicyMixes.size());
4078 for (const auto &policyMix: mPolicyMixes) {
4079 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4080 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4081 policyMix->mCbFlags);
4082 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004083 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004084 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004085 }
4086
Vlad Popaa5d73f32024-03-08 16:05:38 -08004087 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004088 return OK;
4089}
4090
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004091status_t AudioPolicyManager::updatePolicyMix(
4092 const AudioMix& mix,
4093 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4094 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4095 if (res == NO_ERROR) {
4096 checkForDeviceAndOutputChanges();
4097 updateCallAndOutputRouting();
4098 }
4099 return res;
4100}
4101
Mikhail Naganov100f0122018-11-29 11:22:16 -08004102void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4103{
4104 size_t i = 0;
4105 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4106 for (const auto& fmt : mManualSurroundFormats) {
4107 if (i++ != 0) dst->append(", ");
4108 std::string sfmt;
4109 FormatConverter::toString(fmt, sfmt);
4110 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4111 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4112 }
4113}
4114
Eric Laurentc529cf62020-04-17 18:19:10 -07004115// Returns true if all devices types match the predicate and are supported by one HW module
4116bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004117 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004118 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004119 const char *context,
4120 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004121 for (size_t i = 0; i < devices.size(); i++) {
4122 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004123 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004124 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004125 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004126 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004127 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004128 return false;
4129 }
4130 }
4131 return true;
4132}
4133
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004134void AudioPolicyManager::changeOutputDevicesMuteState(
4135 const AudioDeviceTypeAddrVector& devices) {
4136 ALOGVV("%s() num devices %zu", __func__, devices.size());
4137
4138 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4139 getSoftwareOutputsForDevices(devices);
4140
4141 for (size_t i = 0; i < outputs.size(); i++) {
4142 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4143 DeviceVector prevDevices = outputDesc->devices();
4144 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4145 }
4146}
4147
4148std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4149 const AudioDeviceTypeAddrVector& devices) const
4150{
4151 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4152 DeviceVector deviceDescriptors;
4153 for (size_t j = 0; j < devices.size(); j++) {
4154 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4155 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4156 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4157 ALOGE("%s: device type %#x address %s not supported or not an output device",
4158 __func__, devices[j].mType, devices[j].getAddress());
4159 continue;
4160 }
4161 deviceDescriptors.add(desc);
4162 }
4163 for (size_t i = 0; i < mOutputs.size(); i++) {
4164 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4165 continue;
4166 }
4167 outputs.push_back(mOutputs.valueAt(i));
4168 }
4169 return outputs;
4170}
4171
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004172status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004173 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004174 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004175 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4176 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004177 }
4178 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004179 if (res != NO_ERROR) {
4180 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4181 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004182 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004183
4184 checkForDeviceAndOutputChanges();
4185 updateCallAndOutputRouting();
4186
4187 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004188}
4189
4190status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4191 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004192 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4193 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004194 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004195 __FUNCTION__, uid);
4196 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004197 }
4198
Eric Laurentc529cf62020-04-17 18:19:10 -07004199 checkForDeviceAndOutputChanges();
4200 updateCallAndOutputRouting();
4201
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004202 return res;
4203}
4204
Eric Laurent2517af32020-11-25 15:31:27 +01004205
jiabin0a488932020-08-07 17:32:40 -07004206status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4207 device_role_t role,
4208 const AudioDeviceTypeAddrVector &devices) {
4209 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4210 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004211
Eric Laurentc529cf62020-04-17 18:19:10 -07004212 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004213 return BAD_VALUE;
4214 }
jiabin0a488932020-08-07 17:32:40 -07004215 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004216 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004217 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4218 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004219 return status;
4220 }
4221
4222 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004223
4224 bool forceVolumeReeval = false;
4225 // FIXME: workaround for truncated touch sounds
4226 // to be removed when the problem is handled by system UI
4227 uint32_t delayMs = 0;
4228 if (strategy == mCommunnicationStrategy) {
4229 forceVolumeReeval = true;
4230 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4231 updateInputRouting();
4232 }
4233 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004234
4235 return NO_ERROR;
4236}
4237
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004238void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4239 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004240{
4241 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004242 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004243 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004244 // Only apply special touch sound delay once
4245 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004246 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004247 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004248 for (size_t i = 0; i < mOutputs.size(); i++) {
4249 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4250 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004251 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4252 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004253 // As done in setDeviceConnectionState, we could also fix default device issue by
4254 // preventing the force re-routing in case of default dev that distinguishes on address.
4255 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004256 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004257 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004258 // If the device is using preferred mixer attributes, the output need to reopen
4259 // with default configuration when the new selected devices are different from
4260 // current routing devices.
4261 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4262 continue;
4263 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304264
4265 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4266 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004267 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004268 // Only apply special touch sound delay once
4269 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004270 }
4271 if (forceVolumeReeval && !newDevices.isEmpty()) {
4272 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4273 }
4274 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004275 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004276 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004277}
4278
Eric Laurent2517af32020-11-25 15:31:27 +01004279void AudioPolicyManager::updateInputRouting() {
4280 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304281 // Skip for hotword recording as the input device switch
4282 // is handled within sound trigger HAL
4283 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4284 continue;
4285 }
Eric Laurent2517af32020-11-25 15:31:27 +01004286 auto newDevice = getNewInputDevice(activeDesc);
4287 // Force new input selection if the new device can not be reached via current input
4288 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4289 setInputDevice(activeDesc->mIoHandle, newDevice);
4290 } else {
4291 closeInput(activeDesc->mIoHandle);
4292 }
4293 }
4294}
4295
Paul Wang5d7cdb52022-11-22 09:45:06 +00004296status_t
4297AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4298 device_role_t role,
4299 const AudioDeviceTypeAddrVector &devices) {
4300 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4301 dumpAudioDeviceTypeAddrVector(devices).c_str());
4302
Eric Laurent78fedbf2023-03-09 14:40:44 +01004303 if (!areAllDevicesSupported(
4304 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004305 return BAD_VALUE;
4306 }
4307 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4308 if (status != NO_ERROR) {
4309 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4310 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4311 return status;
4312 }
4313
4314 checkForDeviceAndOutputChanges();
4315
4316 bool forceVolumeReeval = false;
4317 // TODO(b/263479999): workaround for truncated touch sounds
4318 // to be removed when the problem is handled by system UI
4319 uint32_t delayMs = 0;
4320 if (strategy == mCommunnicationStrategy) {
4321 forceVolumeReeval = true;
4322 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4323 updateInputRouting();
4324 }
4325 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4326
4327 return NO_ERROR;
4328}
4329
4330status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4331 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004332{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004333 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004334
Paul Wang5d7cdb52022-11-22 09:45:06 +00004335 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004336 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004337 ALOGW_IF(status != NAME_NOT_FOUND,
4338 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004339 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004340 return status;
4341 }
4342
4343 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004344
4345 bool forceVolumeReeval = false;
4346 // FIXME: workaround for truncated touch sounds
4347 // to be removed when the problem is handled by system UI
4348 uint32_t delayMs = 0;
4349 if (strategy == mCommunnicationStrategy) {
4350 forceVolumeReeval = true;
4351 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4352 updateInputRouting();
4353 }
4354 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004355
4356 return NO_ERROR;
4357}
4358
jiabin0a488932020-08-07 17:32:40 -07004359status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4360 device_role_t role,
4361 AudioDeviceTypeAddrVector &devices) {
4362 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004363}
4364
Jiabin Huang3b98d322020-09-03 17:54:16 +00004365status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4366 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4367 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4368 dumpAudioDeviceTypeAddrVector(devices).c_str());
4369
Mikhail Naganov55773032020-10-01 15:08:13 -07004370 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004371 return BAD_VALUE;
4372 }
4373 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4374 ALOGW_IF(status != NO_ERROR,
4375 "Engine could not set preferred devices %s for audio source %d role %d",
4376 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4377
4378 return status;
4379}
4380
4381status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4382 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4383 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4384 dumpAudioDeviceTypeAddrVector(devices).c_str());
4385
Mikhail Naganov55773032020-10-01 15:08:13 -07004386 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004387 return BAD_VALUE;
4388 }
4389 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4390 ALOGW_IF(status != NO_ERROR,
4391 "Engine could not add preferred devices %s for audio source %d role %d",
4392 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4393
Eric Laurent2517af32020-11-25 15:31:27 +01004394 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004395 return status;
4396}
4397
4398status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4399 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4400{
4401 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4402 dumpAudioDeviceTypeAddrVector(devices).c_str());
4403
Eric Laurent78fedbf2023-03-09 14:40:44 +01004404 if (!areAllDevicesSupported(
4405 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004406 return BAD_VALUE;
4407 }
4408
4409 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4410 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004411 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004412 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004413 if (status == NO_ERROR) {
4414 updateInputRouting();
4415 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004416 return status;
4417}
4418
4419status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4420 device_role_t role) {
4421 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4422
4423 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004424 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004425 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004426 if (status == NO_ERROR) {
4427 updateInputRouting();
4428 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004429 return status;
4430}
4431
4432status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4433 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4434 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4435}
4436
Oscar Azucena90e77632019-11-27 17:12:28 -08004437status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004438 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004439 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004440 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4441 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004442 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004443 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4444 if (status != NO_ERROR) {
4445 ALOGE("%s() could not set device affinity for userId %d",
4446 __FUNCTION__, userId);
4447 return status;
4448 }
4449
4450 // reevaluate outputs for all devices
4451 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004452 changeOutputDevicesMuteState(devices);
4453 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4454 true /* skipDelays */);
4455 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004456
4457 return NO_ERROR;
4458}
4459
4460status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004461 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004462 AudioDeviceTypeAddrVector devices;
4463 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004464 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4465 if (status != NO_ERROR) {
4466 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4467 __FUNCTION__, userId);
4468 return status;
4469 }
4470
4471 // reevaluate outputs for all devices
4472 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004473 changeOutputDevicesMuteState(devices);
4474 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4475 true /* skipDelays */);
4476 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004477
4478 return NO_ERROR;
4479}
4480
Andy Hungc29d82b2018-10-05 12:23:17 -07004481void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004482{
Andy Hungc29d82b2018-10-05 12:23:17 -07004483 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004484 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004485 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004486 std::string stateLiteral;
4487 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004488 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004489 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4490 "communications", "media", "record", "dock", "system",
4491 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4492 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4493 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004494 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4495 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4496 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4497 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4498 dst->append(" (MANUAL: ");
4499 dumpManualSurroundFormats(dst);
4500 dst->append(")");
4501 }
4502 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004503 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004504 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4505 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004506 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004507 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004508
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004509 dst->append("\n");
4510 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4511 dst->append("\n");
4512 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004513 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004514 mOutputs.dump(dst);
4515 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004516 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004517 mAudioPatches.dump(dst);
4518 mPolicyMixes.dump(dst);
4519 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004520
Kevin Rocardb99cc752019-03-21 20:52:24 -07004521 dst->appendFormat(" AllowedCapturePolicies:\n");
4522 for (auto& policy : mAllowedCapturePolicies) {
4523 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4524 }
4525
jiabina84c3d32022-12-02 18:59:55 +00004526 dst->appendFormat(" Preferred mixer audio configuration:\n");
4527 for (const auto it : mPreferredMixerAttrInfos) {
4528 dst->appendFormat(" - device port id: %d\n", it.first);
4529 for (const auto preferredMixerInfoIt : it.second) {
4530 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4531 preferredMixerInfoIt.second->dump(dst);
4532 }
4533 }
4534
François Gaffiec005e562018-11-06 15:04:49 +01004535 dst->appendFormat("\nPolicy Engine dump:\n");
4536 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004537
4538 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4539 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4540 dst->appendFormat(" - device type: %s, driving stream %d\n",
4541 dumpDeviceTypes({it.first}).c_str(),
4542 mEngine->getVolumeGroupForAttributes(it.second));
4543 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004544}
4545
4546status_t AudioPolicyManager::dump(int fd)
4547{
4548 String8 result;
4549 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004550 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004551 return NO_ERROR;
4552}
4553
Kevin Rocardb99cc752019-03-21 20:52:24 -07004554status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4555{
4556 mAllowedCapturePolicies[uid] = capturePolicy;
4557 return NO_ERROR;
4558}
4559
Eric Laurente552edb2014-03-10 17:42:56 -07004560// This function checks for the parameters which can be offloaded.
4561// This can be enhanced depending on the capability of the DSP and policy
4562// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004563audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004564{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004565 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004566 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004567 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004568 offloadInfo.format,
4569 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4570 offloadInfo.has_video);
4571
jiabin2b9d5a12021-12-10 01:06:29 +00004572 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004573 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004574 }
4575
4576 // See if there is a profile to support this.
4577 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004578 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004579 offloadInfo.sample_rate,
4580 offloadInfo.format,
4581 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004582 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4583 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004584 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4585 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4586 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004587 if (profile == nullptr) {
4588 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4589 }
4590 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4591 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4592 }
4593 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004594}
4595
Michael Chana94fbb22018-04-24 14:31:19 +10004596bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4597 const audio_attributes_t& attributes) {
4598 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004599 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004600 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4601 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004602 config.sample_rate,
4603 config.format,
4604 config.channel_mask,
4605 output_flags,
4606 true /* directOnly */);
4607 ALOGV("%s() profile %sfound with name: %s, "
4608 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4609 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004610 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004611 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004612
4613 // also try the MSD module if compatible profile not found
4614 if (profile == nullptr) {
4615 profile = getMsdProfileForOutput(outputDevices,
4616 config.sample_rate,
4617 config.format,
4618 config.channel_mask,
4619 output_flags,
4620 true /* directOnly */);
4621 ALOGV("%s() MSD profile %sfound with name: %s, "
4622 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4623 __FUNCTION__, profile != 0 ? "" : "NOT ",
4624 (profile != 0 ? profile->getTagName().c_str() : "null"),
4625 config.sample_rate, config.format, config.channel_mask, output_flags);
4626 }
4627 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004628}
4629
jiabin2b9d5a12021-12-10 01:06:29 +00004630bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4631 bool durationIgnored) {
4632 if (mMasterMono) {
4633 return false; // no offloading if mono is set.
4634 }
4635
4636 // Check if offload has been disabled
4637 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4638 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4639 return false;
4640 }
4641
4642 // Check if stream type is music, then only allow offload as of now.
4643 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4644 {
4645 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4646 return false;
4647 }
4648
4649 //TODO: enable audio offloading with video when ready
4650 const bool allowOffloadWithVideo =
4651 property_get_bool("audio.offload.video", false /* default_value */);
4652 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4653 ALOGV("%s: has_video == true, returning false", __func__);
4654 return false;
4655 }
4656
4657 //If duration is less than minimum value defined in property, return false
4658 const int min_duration_secs = property_get_int32(
4659 "audio.offload.min.duration.secs", -1 /* default_value */);
4660 if (!durationIgnored) {
4661 if (min_duration_secs >= 0) {
4662 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4663 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4664 __func__, min_duration_secs);
4665 return false;
4666 }
4667 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4668 ALOGV("%s: Offload denied by duration < default min(=%u)",
4669 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4670 return false;
4671 }
4672 }
4673
4674 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4675 // creating an offloaded track and tearing it down immediately after start when audioflinger
4676 // detects there is an active non offloadable effect.
4677 // FIXME: We should check the audio session here but we do not have it in this context.
4678 // This may prevent offloading in rare situations where effects are left active by apps
4679 // in the background.
4680 if (mEffects.isNonOffloadableEffectEnabled()) {
4681 return false;
4682 }
4683
4684 return true;
4685}
4686
4687audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4688 const audio_config_t *config) {
4689 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4690 offloadInfo.format = config->format;
4691 offloadInfo.sample_rate = config->sample_rate;
4692 offloadInfo.channel_mask = config->channel_mask;
4693 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4694 offloadInfo.has_video = false;
4695 offloadInfo.is_streaming = false;
4696 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4697
4698 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4699 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4700 audio_flags_to_audio_output_flags(attr->flags, &flags);
4701 // only retain flags that will drive compressed offload or passthrough
4702 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4703 if (offloadPossible) {
4704 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4705 }
4706 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4707
Dorin Drimusfae3c642022-03-17 18:36:30 +01004708 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004709 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004710 DeviceVector outputDevices = engineOutputDevices;
4711 // the MSD module checks for different conditions and output devices
4712 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4713 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4714 continue;
4715 }
4716 outputDevices = getMsdAudioOutDevices();
4717 }
jiabin2b9d5a12021-12-10 01:06:29 +00004718 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004719 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004720 config->sample_rate, nullptr /*updatedSamplingRate*/,
4721 config->format, nullptr /*updatedFormat*/,
4722 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004723 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004724 continue;
4725 }
4726 // reject profiles not corresponding to a device currently available
4727 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4728 continue;
4729 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004730 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4731 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004732 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004733 != AUDIO_DIRECT_NOT_SUPPORTED) {
4734 // Already reports offload gapless supported. No need to report offload support.
4735 continue;
4736 }
4737 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4738 != AUDIO_OUTPUT_FLAG_NONE) {
4739 // If offload gapless is reported, no need to report offload support.
4740 directMode = (audio_direct_mode_t) ((directMode &
4741 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4742 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4743 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004744 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004745 }
4746 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004747 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004748 }
4749 }
4750 }
4751 return directMode;
4752}
4753
Dorin Drimusf2196d82022-01-03 12:11:18 +01004754status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4755 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004756 if (mEffects.isNonOffloadableEffectEnabled()) {
4757 return OK;
4758 }
jiabinf1c73972022-04-14 16:28:52 -07004759 DeviceVector devices;
4760 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004761 if (status != OK) {
4762 return status;
4763 }
4764 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4765 if (devices.empty()) {
4766 return OK; // no output devices for the attributes
4767 }
jiabinf1c73972022-04-14 16:28:52 -07004768 return getProfilesForDevices(devices, audioProfilesVector,
4769 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004770}
4771
jiabina84c3d32022-12-02 18:59:55 +00004772status_t AudioPolicyManager::getSupportedMixerAttributes(
4773 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4774 ALOGV("%s, portId=%d", __func__, portId);
4775 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4776 if (deviceDescriptor == nullptr) {
4777 ALOGE("%s the requested device is currently unavailable", __func__);
4778 return BAD_VALUE;
4779 }
jiabin96daffc2023-05-11 17:51:55 +00004780 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4781 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4782 deviceDescriptor->type());
4783 return BAD_VALUE;
4784 }
jiabina84c3d32022-12-02 18:59:55 +00004785 for (const auto& hwModule : mHwModules) {
4786 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4787 if (curProfile->supportsDevice(deviceDescriptor)) {
4788 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4789 }
4790 }
4791 }
4792 return NO_ERROR;
4793}
4794
4795status_t AudioPolicyManager::setPreferredMixerAttributes(
4796 const audio_attributes_t *attr,
4797 audio_port_handle_t portId,
4798 uid_t uid,
4799 const audio_mixer_attributes_t *mixerAttributes) {
4800 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4801 "mixerBehavior=%d}, uid=%d, portId=%u",
4802 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4803 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4804 mixerAttributes->mixer_behavior, uid, portId);
4805 if (attr->usage != AUDIO_USAGE_MEDIA) {
4806 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4807 return BAD_VALUE;
4808 }
4809 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4810 if (deviceDescriptor == nullptr) {
4811 ALOGE("%s the requested device is currently unavailable", __func__);
4812 return BAD_VALUE;
4813 }
4814 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4815 ALOGE("%s(%d), type=%d, is not a usb output device",
4816 __func__, portId, deviceDescriptor->type());
4817 return BAD_VALUE;
4818 }
4819
4820 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4821 audio_flags_to_audio_output_flags(attr->flags, &flags);
4822 flags = (audio_output_flags_t) (flags |
4823 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4824 sp<IOProfile> profile = nullptr;
4825 DeviceVector devices(deviceDescriptor);
4826 for (const auto& hwModule : mHwModules) {
4827 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4828 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004829 && curProfile->getCompatibilityScore(
4830 devices,
4831 mixerAttributes->config.sample_rate,
4832 nullptr /*updatedSamplingRate*/,
4833 mixerAttributes->config.format,
4834 nullptr /*updatedFormat*/,
4835 mixerAttributes->config.channel_mask,
4836 nullptr /*updatedChannelMask*/,
4837 flags,
4838 false /*exactMatchRequiredForInputFlags*/)
4839 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004840 profile = curProfile;
4841 break;
4842 }
4843 }
4844 }
4845 if (profile == nullptr) {
4846 ALOGE("%s, there is no compatible profile found", __func__);
4847 return BAD_VALUE;
4848 }
4849
4850 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4851 sp<PreferredMixerAttributesInfo>::make(
4852 uid, portId, profile, flags, *mixerAttributes);
4853 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4854 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4855
4856 // If 1) there is any client from the preferred mixer configuration owner that is currently
4857 // active and matches the strategy and 2) current output is on the preferred device and the
4858 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4859 // configuration.
4860 std::vector<audio_io_handle_t> outputsToReopen;
4861 for (size_t i = 0; i < mOutputs.size(); i++) {
4862 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004863 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4864 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004865 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004866 } else {
4867 for (const auto &client: output->getActiveClients()) {
4868 if (client->uid() == uid && client->strategy() == strategy) {
4869 client->setIsInvalid();
4870 outputsToReopen.push_back(output->mIoHandle);
4871 }
jiabina84c3d32022-12-02 18:59:55 +00004872 }
4873 }
4874 }
4875 }
4876 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4877 config.sample_rate = mixerAttributes->config.sample_rate;
4878 config.channel_mask = mixerAttributes->config.channel_mask;
4879 config.format = mixerAttributes->config.format;
4880 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004881 sp<SwAudioOutputDescriptor> desc =
4882 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4883 if (desc == nullptr) {
4884 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4885 continue;
4886 }
jiabin220eea12024-05-17 17:55:20 +00004887 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004888 }
4889
4890 return NO_ERROR;
4891}
4892
4893sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004894 audio_port_handle_t devicePortId,
4895 product_strategy_t strategy,
4896 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004897 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4898 if (it == mPreferredMixerAttrInfos.end()) {
4899 return nullptr;
4900 }
jiabind9a58d32023-06-01 17:57:30 +00004901 if (activeBitPerfectPreferred) {
4902 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004903 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004904 return info;
4905 }
4906 }
jiabina84c3d32022-12-02 18:59:55 +00004907 }
jiabind9a58d32023-06-01 17:57:30 +00004908 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4909 return strategyMatchedMixerAttrInfoIt == it->second.end()
4910 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004911}
4912
4913status_t AudioPolicyManager::getPreferredMixerAttributes(
4914 const audio_attributes_t *attr,
4915 audio_port_handle_t portId,
4916 audio_mixer_attributes_t* mixerAttributes) {
4917 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4918 portId, mEngine->getProductStrategyForAttributes(*attr));
4919 if (info == nullptr) {
4920 return NAME_NOT_FOUND;
4921 }
4922 *mixerAttributes = info->getMixerAttributes();
4923 return NO_ERROR;
4924}
4925
4926status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4927 audio_port_handle_t portId,
4928 uid_t uid) {
4929 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4930 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4931 if (preferredMixerAttrInfo == nullptr) {
4932 return NAME_NOT_FOUND;
4933 }
4934 if (preferredMixerAttrInfo->getUid() != uid) {
4935 ALOGE("%s, requested uid=%d, owned uid=%d",
4936 __func__, uid, preferredMixerAttrInfo->getUid());
4937 return PERMISSION_DENIED;
4938 }
4939 mPreferredMixerAttrInfos[portId].erase(strategy);
4940 if (mPreferredMixerAttrInfos[portId].empty()) {
4941 mPreferredMixerAttrInfos.erase(portId);
4942 }
4943
4944 // Reconfig existing output
4945 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4946 for (size_t i = 0; i < mOutputs.size(); i++) {
4947 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4948 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4949 }
4950 }
4951 for (const auto output : potentialOutputsToReopen) {
4952 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4953 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4954 preferredMixerAttrInfo->getFlags())) {
4955 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4956 }
4957 }
4958 return NO_ERROR;
4959}
4960
Eric Laurent6a94d692014-05-20 11:18:06 -07004961status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4962 audio_port_type_t type,
4963 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004964 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 unsigned int *generation)
4966{
jiabin19cdba52020-11-24 11:28:58 -08004967 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4968 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004969 return BAD_VALUE;
4970 }
4971 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004972 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004973 *num_ports = 0;
4974 }
4975
4976 size_t portsWritten = 0;
4977 size_t portsMax = *num_ports;
4978 *num_ports = 0;
4979 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004980 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4981 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004983 for (const auto& dev : mAvailableOutputDevices) {
4984 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004985 continue;
4986 }
4987 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004988 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004989 }
4990 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004991 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 }
4993 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004994 for (const auto& dev : mAvailableInputDevices) {
4995 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004996 continue;
4997 }
4998 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004999 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005000 }
5001 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005003 }
5004 }
5005 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5006 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5007 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5008 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5009 }
5010 *num_ports += mInputs.size();
5011 }
5012 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005013 size_t numOutputs = 0;
5014 for (size_t i = 0; i < mOutputs.size(); i++) {
5015 if (!mOutputs[i]->isDuplicated()) {
5016 numOutputs++;
5017 if (portsWritten < portsMax) {
5018 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5019 }
5020 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 }
Eric Laurent84c70242014-06-23 08:46:27 -07005022 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005023 }
5024 }
jiabina84c3d32022-12-02 18:59:55 +00005025
Eric Laurent6a94d692014-05-20 11:18:06 -07005026 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005027 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005028 return NO_ERROR;
5029}
5030
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005031status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5032 std::vector<media::AudioPortFw>* _aidl_return) {
5033 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5034 audio_port_v7 port;
5035 dev->toAudioPort(&port);
5036 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5037 _aidl_return->push_back(std::move(aidlPort));
5038 return OK;
5039 };
5040
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005041 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005042 for (const auto& dev : module->getDeclaredDevices()) {
5043 if (role == media::AudioPortRole::NONE ||
5044 ((role == media::AudioPortRole::SOURCE)
5045 == audio_is_input_device(dev->type()))) {
5046 RETURN_STATUS_IF_ERROR(pushPort(dev));
5047 }
5048 }
5049 }
5050 return OK;
5051}
5052
jiabin19cdba52020-11-24 11:28:58 -08005053status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005054{
Eric Laurent99fcae42018-05-17 16:59:18 -07005055 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5056 return BAD_VALUE;
5057 }
5058 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5059 if (dev != 0) {
5060 dev->toAudioPort(port);
5061 return NO_ERROR;
5062 }
5063 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5064 if (dev != 0) {
5065 dev->toAudioPort(port);
5066 return NO_ERROR;
5067 }
5068 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5069 if (out != 0) {
5070 out->toAudioPort(port);
5071 return NO_ERROR;
5072 }
5073 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5074 if (in != 0) {
5075 in->toAudioPort(port);
5076 return NO_ERROR;
5077 }
5078 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005079}
5080
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005081status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5082 audio_patch_handle_t *handle,
5083 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005084{
François Gaffieafd4cea2019-11-18 15:50:22 +01005085 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005086 if (handle == NULL || patch == NULL) {
5087 return BAD_VALUE;
5088 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005089 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005090 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005091 return BAD_VALUE;
5092 }
5093 // only one source per audio patch supported for now
5094 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005095 return INVALID_OPERATION;
5096 }
Eric Laurent874c42872014-08-08 15:13:39 -07005097 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005098 return INVALID_OPERATION;
5099 }
Eric Laurent874c42872014-08-08 15:13:39 -07005100 for (size_t i = 0; i < patch->num_sinks; i++) {
5101 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5102 return INVALID_OPERATION;
5103 }
5104 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005105
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005106 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5107 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5108 if (srcDevice == nullptr || sinkDevice == nullptr) {
5109 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5110 return BAD_VALUE;
5111 }
5112 ALOGV("%s between source %s and sink %s", __func__,
5113 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5114 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5115 // Default attributes, default volume priority, not to infer with non raw audio patches.
5116 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5117 const struct audio_port_config *source = &patch->sources[0];
5118 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005119 new SourceClientDescriptor(
5120 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5121 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005122 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005123 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005124
5125 status_t status =
5126 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5127
5128 if (status != NO_ERROR) {
5129 return INVALID_OPERATION;
5130 }
5131 mAudioSources.add(portId, sourceDesc);
5132 return NO_ERROR;
5133}
5134
5135status_t AudioPolicyManager::connectAudioSourceToSink(
5136 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5137 const struct audio_patch *patch,
5138 audio_patch_handle_t &handle,
5139 uid_t uid, uint32_t delayMs)
5140{
5141 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5142 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5143 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5144 return INVALID_OPERATION;
5145 }
5146 sourceDesc->connect(handle, sinkDevice);
5147 if (isMsdPatch(handle)) {
5148 return NO_ERROR;
5149 }
5150 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5151 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5152 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5153 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5154 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5155 goto FailurePatchAdded;
5156 }
5157 status = swOutput->start();
5158 if (status != NO_ERROR) {
5159 goto FailureSourceAdded;
5160 }
5161 swOutput->addClient(sourceDesc);
5162 status = startSource(swOutput, sourceDesc, &delayMs);
5163 if (status != NO_ERROR) {
5164 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5165 goto FailureSourceActive;
5166 }
5167 if (delayMs != 0) {
5168 usleep(delayMs * 1000);
5169 }
5170 return NO_ERROR;
5171
5172FailureSourceActive:
5173 swOutput->stop();
5174 releaseOutput(sourceDesc->portId());
5175FailureSourceAdded:
5176 sourceDesc->setSwOutput(nullptr);
5177FailurePatchAdded:
5178 releaseAudioPatchInternal(handle);
5179 return INVALID_OPERATION;
5180}
5181
5182status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5183 audio_patch_handle_t *handle,
5184 uid_t uid, uint32_t delayMs,
5185 const sp<SourceClientDescriptor>& sourceDesc)
5186{
5187 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 sp<AudioPatch> patchDesc;
5189 ssize_t index = mAudioPatches.indexOfKey(*handle);
5190
François Gaffieafd4cea2019-11-18 15:50:22 +01005191 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5192 patch->sources[0].role,
5193 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005194#if LOG_NDEBUG == 0
5195 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005196 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5197 patch->sinks[i].role,
5198 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005199 }
5200#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005201
5202 if (index >= 0) {
5203 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005204 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5205 __func__, mUidCached, patchDesc->getUid(), uid);
5206 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 return INVALID_OPERATION;
5208 }
5209 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005210 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005211 }
5212
5213 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005214 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005216 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 return BAD_VALUE;
5218 }
Eric Laurent84c70242014-06-23 08:46:27 -07005219 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5220 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005221 if (patchDesc != 0) {
5222 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005223 ALOGV("%s source id differs for patch current id %d new id %d",
5224 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005225 return BAD_VALUE;
5226 }
5227 }
Eric Laurent874c42872014-08-08 15:13:39 -07005228 DeviceVector devices;
5229 for (size_t i = 0; i < patch->num_sinks; i++) {
5230 // Only support mix to devices connection
5231 // TODO add support for mix to mix connection
5232 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005233 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005234 return INVALID_OPERATION;
5235 }
5236 sp<DeviceDescriptor> devDesc =
5237 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5238 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005239 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005240 return BAD_VALUE;
5241 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005242
jiabin66acc432024-02-06 00:57:36 +00005243 if (outputDesc->mProfile->getCompatibilityScore(
5244 DeviceVector(devDesc),
5245 patch->sources[0].sample_rate,
5246 nullptr, // updatedSamplingRate
5247 patch->sources[0].format,
5248 nullptr, // updatedFormat
5249 patch->sources[0].channel_mask,
5250 nullptr, // updatedChannelMask
5251 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005252 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005253 return INVALID_OPERATION;
5254 }
5255 devices.add(devDesc);
5256 }
5257 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 return INVALID_OPERATION;
5259 }
Eric Laurent874c42872014-08-08 15:13:39 -07005260
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005262 ALOGV("%s setting device %s on output %d",
5263 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305264 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005265 index = mAudioPatches.indexOfKey(*handle);
5266 if (index >= 0) {
5267 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005268 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 }
5270 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005271 patchDesc->setUid(uid);
5272 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005273 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005274 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 return INVALID_OPERATION;
5276 }
5277 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5278 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5279 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005280 // only one sink supported when connecting an input device to a mix
5281 if (patch->num_sinks > 1) {
5282 return INVALID_OPERATION;
5283 }
François Gaffie53615e22015-03-19 09:24:12 +01005284 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 if (inputDesc == NULL) {
5286 return BAD_VALUE;
5287 }
5288 if (patchDesc != 0) {
5289 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5290 return BAD_VALUE;
5291 }
5292 }
François Gaffie11d30102018-11-02 16:09:09 +01005293 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005295 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 return BAD_VALUE;
5297 }
5298
jiabin66acc432024-02-06 00:57:36 +00005299 if (inputDesc->mProfile->getCompatibilityScore(
5300 DeviceVector(device),
5301 patch->sinks[0].sample_rate,
5302 nullptr, /*updatedSampleRate*/
5303 patch->sinks[0].format,
5304 nullptr, /*updatedFormat*/
5305 patch->sinks[0].channel_mask,
5306 nullptr, /*updatedChannelMask*/
5307 // FIXME for the parameter type,
5308 // and the NONE
5309 (audio_output_flags_t)
5310 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 return INVALID_OPERATION;
5312 }
5313 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005314 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005315 device->toString().c_str(), inputDesc->mIoHandle);
5316 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005317 index = mAudioPatches.indexOfKey(*handle);
5318 if (index >= 0) {
5319 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005320 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 }
5322 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005323 patchDesc->setUid(uid);
5324 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005325 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005326 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005327 return INVALID_OPERATION;
5328 }
5329 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5330 // device to device connection
5331 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005332 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005333 return BAD_VALUE;
5334 }
5335 }
François Gaffie11d30102018-11-02 16:09:09 +01005336 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005337 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005338 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005339 return BAD_VALUE;
5340 }
Eric Laurent874c42872014-08-08 15:13:39 -07005341
Eric Laurent6a94d692014-05-20 11:18:06 -07005342 //update source and sink with our own data as the data passed in the patch may
5343 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005344 PatchBuilder patchBuilder;
5345 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005346
5347 // if first sink is to MSD, establish single MSD patch
5348 if (getMsdAudioOutDevices().contains(
5349 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5350 ALOGV("%s patching to MSD", __FUNCTION__);
5351 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5352 goto installPatch;
5353 }
5354
François Gaffieafd4cea2019-11-18 15:50:22 +01005355 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5356 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005357
Eric Laurent874c42872014-08-08 15:13:39 -07005358 for (size_t i = 0; i < patch->num_sinks; i++) {
5359 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005360 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005361 return INVALID_OPERATION;
5362 }
François Gaffie11d30102018-11-02 16:09:09 +01005363 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005364 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005365 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005366 return BAD_VALUE;
5367 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005368 audio_port_config sinkPortConfig = {};
5369 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5370 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005371
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005372 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5373 // volume management purpose (tracking activity)
5374 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5375 // in config XML to reach the sink so that is can be declared as available.
5376 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005377 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005378 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005379 // take care of dynamic routing for SwOutput selection,
5380 audio_attributes_t attributes = sourceDesc->attributes();
5381 audio_stream_type_t stream = sourceDesc->stream();
5382 audio_attributes_t resultAttr;
5383 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5384 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005385 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5386 config.channel_mask =
5387 (audio_channel_mask_get_representation(sourceMask)
5388 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5389 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005390 config.format = sourceDesc->config().format;
5391 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5392 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5393 bool isRequestedDeviceForExclusiveUse = false;
5394 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005395 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005396 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005397 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5398 &stream, sourceDesc->uid(), &config, &flags,
5399 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005400 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005401 if (output == AUDIO_IO_HANDLE_NONE) {
5402 ALOGV("%s no output for device %s",
5403 __FUNCTION__, sinkDevice->toString().c_str());
5404 return INVALID_OPERATION;
5405 }
5406 outputDesc = mOutputs.valueFor(output);
5407 if (outputDesc->isDuplicated()) {
5408 ALOGE("%s output is duplicated", __func__);
5409 return INVALID_OPERATION;
5410 }
François Gaffie7e39df22022-04-26 12:48:49 +02005411 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5412 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005413 } else {
5414 // Same for "raw patches" aka created from createAudioPatch API
5415 SortedVector<audio_io_handle_t> outputs =
5416 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5417 // if the sink device is reachable via an opened output stream, request to
5418 // go via this output stream by adding a second source to the patch
5419 // description
5420 output = selectOutput(outputs);
5421 if (output == AUDIO_IO_HANDLE_NONE) {
5422 ALOGE("%s no output available for internal patch sink", __func__);
5423 return INVALID_OPERATION;
5424 }
5425 outputDesc = mOutputs.valueFor(output);
5426 if (outputDesc->isDuplicated()) {
5427 ALOGV("%s output for device %s is duplicated",
5428 __func__, sinkDevice->toString().c_str());
5429 return INVALID_OPERATION;
5430 }
François Gaffie7e39df22022-04-26 12:48:49 +02005431 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005432 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005433 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005434 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005435 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005436 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005437 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5438 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005439 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5440 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005441 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005442 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005443 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005444 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005445 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005446 return INVALID_OPERATION;
5447 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005448 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005449 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005450 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005451 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005452 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005453 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005454 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005455 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5456 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005457 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005458 }
Eric Laurent83b88082014-06-20 18:31:16 -07005459 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005460 }
5461 // TODO: check from routing capabilities in config file and other conflicting patches
5462
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005463installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005464 status_t status = installPatch(
5465 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005466 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005467 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005468 return INVALID_OPERATION;
5469 }
5470 } else {
5471 return BAD_VALUE;
5472 }
5473 } else {
5474 return BAD_VALUE;
5475 }
5476 return NO_ERROR;
5477}
5478
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005479status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005480{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005481 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005482 ssize_t index = mAudioPatches.indexOfKey(handle);
5483
5484 if (index < 0) {
5485 return BAD_VALUE;
5486 }
5487 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005488 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5489 __func__, mUidCached, patchDesc->getUid(), uid);
5490 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005491 return INVALID_OPERATION;
5492 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005493 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5494 for (size_t i = 0; i < mAudioSources.size(); i++) {
5495 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5496 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5497 portId = sourceDesc->portId();
5498 break;
5499 }
5500 }
5501 return portId != AUDIO_PORT_HANDLE_NONE ?
5502 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005503}
Eric Laurent6a94d692014-05-20 11:18:06 -07005504
François Gaffieafd4cea2019-11-18 15:50:22 +01005505status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005506 uint32_t delayMs,
5507 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005508{
5509 ALOGV("%s patch %d", __func__, handle);
5510 if (mAudioPatches.indexOfKey(handle) < 0) {
5511 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5512 return BAD_VALUE;
5513 }
5514 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005515 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005516 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005517 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005518 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005519 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005520 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005521 return BAD_VALUE;
5522 }
5523
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305524 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005525 getNewOutputDevices(outputDesc, true /*fromCache*/),
5526 true,
5527 0,
5528 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005529 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5530 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005531 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005532 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005533 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005534 return BAD_VALUE;
5535 }
5536 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005537 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005538 true,
5539 NULL);
5540 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005541 status_t status =
5542 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5543 ALOGV("%s patch panel returned %d patchHandle %d",
5544 __func__, status, patchDesc->getAfHandle());
5545 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005546 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005547 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005548 // SW or HW Bridge
5549 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5550 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005551 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005552 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5553 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5554 outputDesc = sourceDesc->swOutput().promote();
5555 }
5556 if (outputDesc == nullptr) {
5557 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5558 // releaseOutput has already called closeOutput in case of direct output
5559 return NO_ERROR;
5560 }
François Gaffie7e39df22022-04-26 12:48:49 +02005561 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005562 // While using a HwBridge, force reconsidering device only if not reusing an existing
5563 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005564 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005565 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5566 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5567 // Reconsider device only for cases:
5568 // 1 / Active Output
5569 // 2 / Inactive Output previously hosting HwBridge
5570 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5571 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5572 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305573 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005574 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5575 outputDesc->devices(),
5576 force,
5577 0,
5578 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005579 } else {
5580 return BAD_VALUE;
5581 }
5582 } else {
5583 return BAD_VALUE;
5584 }
5585 return NO_ERROR;
5586}
5587
5588status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5589 struct audio_patch *patches,
5590 unsigned int *generation)
5591{
François Gaffie53615e22015-03-19 09:24:12 +01005592 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005593 return BAD_VALUE;
5594 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005595 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005596 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005597}
5598
Eric Laurente1715a42014-05-20 11:30:42 -07005599status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005600{
Eric Laurente1715a42014-05-20 11:30:42 -07005601 ALOGV("setAudioPortConfig()");
5602
5603 if (config == NULL) {
5604 return BAD_VALUE;
5605 }
5606 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5607 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005608 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5609 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005610 }
5611
Eric Laurenta121f902014-06-03 13:32:54 -07005612 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005613 if (config->type == AUDIO_PORT_TYPE_MIX) {
5614 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005615 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005616 if (outputDesc == NULL) {
5617 return BAD_VALUE;
5618 }
Eric Laurent84c70242014-06-23 08:46:27 -07005619 ALOG_ASSERT(!outputDesc->isDuplicated(),
5620 "setAudioPortConfig() called on duplicated output %d",
5621 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005622 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005623 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005624 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005625 if (inputDesc == NULL) {
5626 return BAD_VALUE;
5627 }
Eric Laurenta121f902014-06-03 13:32:54 -07005628 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005629 } else {
5630 return BAD_VALUE;
5631 }
5632 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5633 sp<DeviceDescriptor> deviceDesc;
5634 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5635 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5636 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5637 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5638 } else {
5639 return BAD_VALUE;
5640 }
5641 if (deviceDesc == NULL) {
5642 return BAD_VALUE;
5643 }
Eric Laurenta121f902014-06-03 13:32:54 -07005644 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005645 } else {
5646 return BAD_VALUE;
5647 }
5648
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005649 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005650 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5651 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005652 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005653 audioPortConfig->toAudioPortConfig(&newConfig, config);
5654 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005655 }
Eric Laurenta121f902014-06-03 13:32:54 -07005656 if (status != NO_ERROR) {
5657 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005658 }
Eric Laurente1715a42014-05-20 11:30:42 -07005659
5660 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005661}
5662
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005663void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5664{
Eric Laurentd60560a2015-04-10 11:31:20 -07005665 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005666 clearAudioPatches(uid);
5667 clearSessionRoutes(uid);
5668}
5669
Eric Laurent6a94d692014-05-20 11:18:06 -07005670void AudioPolicyManager::clearAudioPatches(uid_t uid)
5671{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005672 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005673 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005674 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005675 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005676 }
5677 }
5678}
5679
François Gaffiec005e562018-11-06 15:04:49 +01005680void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005681{
François Gaffiec005e562018-11-06 15:04:49 +01005682 // Take the first attributes following the product strategy as it is used to retrieve the routed
5683 // device. All attributes wihin a strategy follows the same "routing strategy"
5684 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5685 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005686 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005687 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005688 for (size_t j = 0; j < mOutputs.size(); j++) {
5689 if (mOutputs.keyAt(j) == ouptutToSkip) {
5690 continue;
5691 }
5692 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005693 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005694 continue;
5695 }
5696 // If the default device for this strategy is on another output mix,
5697 // invalidate all tracks in this strategy to force re connection.
5698 // Otherwise select new device on the output mix.
5699 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005700 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005701 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005702 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005703 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005704 // If the device is using preferred mixer attributes, the output need to reopen
5705 // with default configuration when the new selected devices are different from
5706 // current routing devices.
5707 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5708 continue;
5709 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305710 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005711 }
5712 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005713 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005714}
5715
5716void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5717{
5718 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005719 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005720 for (size_t i = 0; i < mOutputs.size(); i++) {
5721 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005722 for (const auto& client : outputDesc->getClientIterable()) {
5723 if (client->hasPreferredDevice() && client->uid() == uid) {
5724 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005725 auto clientStrategy = client->strategy();
5726 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5727 end(affectedStrategies)) {
5728 continue;
5729 }
5730 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005731 }
5732 }
5733 }
5734 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005735 for (const auto& strategy : affectedStrategies) {
5736 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005737 }
5738
5739 // remove input routes associated with this uid
5740 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005741 for (size_t i = 0; i < mInputs.size(); i++) {
5742 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005743 for (const auto& client : inputDesc->getClientIterable()) {
5744 if (client->hasPreferredDevice() && client->uid() == uid) {
5745 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5746 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005747 }
5748 }
5749 }
5750 // reroute inputs if necessary
5751 SortedVector<audio_io_handle_t> inputsToClose;
5752 for (size_t i = 0; i < mInputs.size(); i++) {
5753 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005754 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005755 inputsToClose.add(inputDesc->mIoHandle);
5756 }
5757 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005758 for (const auto& input : inputsToClose) {
5759 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005760 }
5761}
5762
Eric Laurentd60560a2015-04-10 11:31:20 -07005763void AudioPolicyManager::clearAudioSources(uid_t uid)
5764{
5765 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005766 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5767 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005768 stopAudioSource(mAudioSources.keyAt(i));
5769 }
5770 }
5771}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005772
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005773status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5774 audio_io_handle_t *ioHandle,
5775 audio_devices_t *device)
5776{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005777 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5778 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005779 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005780 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5781 if (deviceDesc == nullptr) {
5782 return INVALID_OPERATION;
5783 }
5784 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005785
François Gaffiedf372692015-03-19 10:43:27 +01005786 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005787}
5788
Eric Laurentd60560a2015-04-10 11:31:20 -07005789status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005790 const audio_attributes_t *attributes,
5791 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005792 uid_t uid) {
5793 return startAudioSourceInternal(source, attributes, portId, uid,
David Li48b6a832024-07-01 13:14:10 +00005794 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurent963dbcc2024-06-20 12:34:15 +00005795}
5796
5797status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5798 const audio_attributes_t *attributes,
5799 audio_port_handle_t *portId,
David Li48b6a832024-07-01 13:14:10 +00005800 uid_t uid, bool internal, bool isCallRx,
5801 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005802{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005803 ALOGV("%s", __FUNCTION__);
5804 *portId = AUDIO_PORT_HANDLE_NONE;
5805
5806 if (source == NULL || attributes == NULL || portId == NULL) {
5807 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5808 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005809 return BAD_VALUE;
5810 }
5811
Eric Laurentd60560a2015-04-10 11:31:20 -07005812 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5813 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005814 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5815 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005816 return INVALID_OPERATION;
5817 }
5818
François Gaffie11d30102018-11-02 16:09:09 +01005819 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005820 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005821 String8(source->ext.device.address),
5822 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005823 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005824 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005825 return BAD_VALUE;
5826 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005827
jiabin4ef93452019-09-10 14:29:54 -07005828 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005829
François Gaffieaaac0fd2018-11-22 17:56:39 +01005830 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005831 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005832 mEngine->getStreamTypeForAttributes(*attributes),
5833 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005834 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005835
David Li48b6a832024-07-01 13:14:10 +00005836 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005837 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005838 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005839 }
5840 return status;
5841}
5842
David Li48b6a832024-07-01 13:14:10 +00005843status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5844 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005845{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005846 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005847
5848 // make sure we only have one patch per source.
5849 disconnectAudioSource(sourceDesc);
5850
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005851 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005852 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5853 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5854 sourceDesc->srcDevice()->type(),
5855 String8(sourceDesc->srcDevice()->address().c_str()),
5856 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005857 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005858 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005859 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005860 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005861 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5862 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5863 return INVALID_OPERATION;
5864 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005865 PatchBuilder patchBuilder;
5866 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5867 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005868
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005869 return connectAudioSourceToSink(
David Li48b6a832024-07-01 13:14:10 +00005870 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005871}
5872
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005873status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005874{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005875 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5876 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005877 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005878 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005879 return BAD_VALUE;
5880 }
5881 status_t status = disconnectAudioSource(sourceDesc);
5882
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005883 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005884 return status;
5885}
5886
Andy Hung2ddee192015-12-18 17:34:44 -08005887status_t AudioPolicyManager::setMasterMono(bool mono)
5888{
5889 if (mMasterMono == mono) {
5890 return NO_ERROR;
5891 }
5892 mMasterMono = mono;
5893 // if enabling mono we close all offloaded devices, which will invalidate the
5894 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5895 // for recreating the new AudioTrack as non-offloaded PCM.
5896 //
5897 // If disabling mono, we leave all tracks as is: we don't know which clients
5898 // and tracks are able to be recreated as offloaded. The next "song" should
5899 // play back offloaded.
5900 if (mMasterMono) {
5901 Vector<audio_io_handle_t> offloaded;
5902 for (size_t i = 0; i < mOutputs.size(); ++i) {
5903 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5904 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5905 offloaded.push(desc->mIoHandle);
5906 }
5907 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005908 for (const auto& handle : offloaded) {
5909 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005910 }
5911 }
5912 // update master mono for all remaining outputs
5913 for (size_t i = 0; i < mOutputs.size(); ++i) {
5914 updateMono(mOutputs.keyAt(i));
5915 }
5916 return NO_ERROR;
5917}
5918
5919status_t AudioPolicyManager::getMasterMono(bool *mono)
5920{
5921 *mono = mMasterMono;
5922 return NO_ERROR;
5923}
5924
Eric Laurentac9cef52017-06-09 15:46:26 -07005925float AudioPolicyManager::getStreamVolumeDB(
5926 audio_stream_type_t stream, int index, audio_devices_t device)
5927{
jiabin9a3361e2019-10-01 09:38:30 -07005928 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005929}
5930
jiabin81772902018-04-02 17:52:27 -07005931status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5932 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005933 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005934{
Kriti Dang6537def2021-03-02 13:46:59 +01005935 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5936 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005937 return BAD_VALUE;
5938 }
Kriti Dang6537def2021-03-02 13:46:59 +01005939 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5940 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005941
5942 size_t formatsWritten = 0;
5943 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005944
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005945 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005946 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5947 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005948 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005949 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005950 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005951 bool formatEnabled = true;
5952 switch (forceUse) {
5953 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005954 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005955 break;
5956 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5957 formatEnabled = false;
5958 break;
5959 default: // AUTO or ALWAYS => true
5960 break;
jiabin81772902018-04-02 17:52:27 -07005961 }
5962 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5963 }
jiabin81772902018-04-02 17:52:27 -07005964 }
5965 return NO_ERROR;
5966}
5967
Kriti Dang6537def2021-03-02 13:46:59 +01005968status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5969 audio_format_t *surroundFormats) {
5970 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5971 return BAD_VALUE;
5972 }
5973 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5974 __func__, *numSurroundFormats, surroundFormats);
5975
5976 size_t formatsWritten = 0;
5977 size_t formatsMax = *numSurroundFormats;
5978 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5979
5980 // Return formats from all device profiles that have already been resolved by
5981 // checkOutputsForDevice().
5982 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5983 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5984 audio_devices_t deviceType = device->type();
5985 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5986 // returns formats reported by HDMI devices.
5987 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5988 continue;
5989 }
5990 // Formats reported by sink devices
5991 std::unordered_set<audio_format_t> formatset;
5992 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5993 formatset.insert(it->second.begin(), it->second.end());
5994 }
5995
5996 // Formats hard-coded in the in policy configuration file (if any).
5997 FormatVector encodedFormats = device->encodedFormats();
5998 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5999 // Filter the formats which are supported by the vendor hardware.
6000 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006001 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006002 formats.insert(*it);
6003 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006004 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006005 if (pair.second.count(*it) != 0) {
6006 formats.insert(pair.first);
6007 break;
6008 }
6009 }
6010 }
6011 }
6012 }
6013 *numSurroundFormats = formats.size();
6014 for (const auto& format: formats) {
6015 if (formatsWritten < formatsMax) {
6016 surroundFormats[formatsWritten++] = format;
6017 }
6018 }
6019 return NO_ERROR;
6020}
6021
jiabin81772902018-04-02 17:52:27 -07006022status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6023{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006024 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006025 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6026 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006027 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006028 return BAD_VALUE;
6029 }
6030
Mikhail Naganov100f0122018-11-29 11:22:16 -08006031 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6032 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006033 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006034 return INVALID_OPERATION;
6035 }
6036
Mikhail Naganov100f0122018-11-29 11:22:16 -08006037 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006038 return NO_ERROR;
6039 }
6040
Mikhail Naganov100f0122018-11-29 11:22:16 -08006041 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006042 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006043 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006044 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006045 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006046 }
6047 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006048 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006049 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006050 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006051 }
6052 }
6053
6054 sp<SwAudioOutputDescriptor> outputDesc;
6055 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006056 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6057 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006058 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6059 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006060 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006061 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006062 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6063 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6064 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006065 name.c_str(),
6066 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006067 if (status != NO_ERROR) {
6068 continue;
6069 }
6070 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6071 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6072 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006073 name.c_str(),
6074 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006075 profileUpdated |= (status == NO_ERROR);
6076 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006077 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006078 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006079 AUDIO_DEVICE_IN_HDMI);
6080 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6081 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006082 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006083 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006084 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6085 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6086 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006087 name.c_str(),
6088 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006089 if (status != NO_ERROR) {
6090 continue;
6091 }
6092 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6093 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6094 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006095 name.c_str(),
6096 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006097 profileUpdated |= (status == NO_ERROR);
6098 }
6099
jiabin81772902018-04-02 17:52:27 -07006100 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006101 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006102 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006103 }
6104
6105 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6106}
6107
Eric Laurent5ada82e2019-08-29 17:53:54 -07006108void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006109{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006110 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006111 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006112 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006113 }
6114}
6115
jiabin6012f912018-11-02 17:06:30 -07006116bool AudioPolicyManager::isHapticPlaybackSupported()
6117{
6118 for (const auto& hwModule : mHwModules) {
6119 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6120 for (const auto &outProfile : outputProfiles) {
6121 struct audio_port audioPort;
6122 outProfile->toAudioPort(&audioPort);
6123 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6124 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6125 return true;
6126 }
6127 }
6128 }
6129 }
6130 return false;
6131}
6132
Carter Hsu325a8eb2022-01-19 19:56:51 +08006133bool AudioPolicyManager::isUltrasoundSupported()
6134{
6135 bool hasUltrasoundOutput = false;
6136 bool hasUltrasoundInput = false;
6137 for (const auto& hwModule : mHwModules) {
6138 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6139 if (!hasUltrasoundOutput) {
6140 for (const auto &outProfile : outputProfiles) {
6141 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6142 hasUltrasoundOutput = true;
6143 break;
6144 }
6145 }
6146 }
6147
6148 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6149 if (!hasUltrasoundInput) {
6150 for (const auto &inputProfile : inputProfiles) {
6151 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6152 hasUltrasoundInput = true;
6153 break;
6154 }
6155 }
6156 }
6157
6158 if (hasUltrasoundOutput && hasUltrasoundInput)
6159 return true;
6160 }
6161 return false;
6162}
6163
Atneya Nair698f5ef2022-12-15 16:15:09 -08006164bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6165{
6166 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6167 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6168 for (const auto& hwModule : mHwModules) {
6169 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6170 for (const auto &inputProfile : inputProfiles) {
6171 if ((inputProfile->getFlags() & mask) == mask) {
6172 return true;
6173 }
6174 }
6175 }
6176 return false;
6177}
6178
Eric Laurent8340e672019-11-06 11:01:08 -08006179bool AudioPolicyManager::isCallScreenModeSupported()
6180{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006181 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006182}
6183
6184
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006185status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006186{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006187 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006188 if (!sourceDesc->isConnected()) {
6189 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6190 return NO_ERROR;
6191 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006192 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6193 if (swOutput != 0) {
6194 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006195 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006196 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006197 }
jiabinbce0c1d2020-10-05 11:20:18 -07006198 if (releaseOutput(sourceDesc->portId())) {
6199 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6200 // no need to release audio patch here but just return NO_ERROR.
6201 return NO_ERROR;
6202 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006203 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006204 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006205 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006206 // close Hwoutput and remove from mHwOutputs
6207 } else {
6208 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6209 }
6210 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006211 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006212 sourceDesc->disconnect();
6213 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006214}
6215
François Gaffiec005e562018-11-06 15:04:49 +01006216sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6217 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006218{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006219 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006220 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006221 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006222 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006223 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6224 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006225 source = sourceDesc;
6226 break;
6227 }
6228 }
6229 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006230}
6231
Eric Laurentb4f42a92022-01-17 17:37:31 +01006232bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006233 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006234 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006235{
6236 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6237 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006238 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006239 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006240 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6241 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6242 return false;
6243 }
6244 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6245 return false;
6246 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006247 }
6248
Eric Laurentd332bc82023-08-04 11:45:23 +02006249 // The caller can have the audio config criteria ignored by either passing a null ptr or
6250 // the AUDIO_CONFIG_INITIALIZER value.
6251 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006252 // some positional channel masks and PCM format and for stereo if low latency performance
6253 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006254
6255 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006256 static const bool stereo_spatialization_enabled =
6257 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006258 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006259 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006260 ? audio_channel_mask_contains_stereo(config->channel_mask)
6261 : audio_is_channel_mask_spatialized(config->channel_mask);
6262 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006263 return false;
6264 }
6265 if (!audio_is_linear_pcm(config->format)) {
6266 return false;
6267 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006268 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6269 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6270 return false;
6271 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006272 }
6273
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006274 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006275 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006276 if (profile == nullptr) {
6277 return false;
6278 }
6279
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006280 return true;
6281}
6282
Shunkai Yao57b93392024-04-26 04:12:21 +00006283// The Spatializer output is compatible with Haptic use cases if:
6284// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6285// with client if client haptic channel bits were set, or
6286// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6287// including the haptic bits or creating the HapticGenerator effect for same session.
6288bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6289 const audio_config_t* config, audio_session_t sessionId) const {
6290 const auto clientHapticChannel =
6291 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6292 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6293 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6294
6295 if (threadOutputHapticChannel) {
6296 // check format and sampleRate match if client haptic channel mask exist
6297 if (clientHapticChannel) {
6298 return mSpatializerOutput->getFormat() == config->format &&
6299 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6300 }
6301 return true;
6302 } else {
6303 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6304 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6305 // HapticGenerator effect for this session) are not supported.
6306 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006307 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006308 }
6309}
6310
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006311void AudioPolicyManager::checkVirtualizerClientRoutes() {
6312 std::set<audio_stream_type_t> streamsToInvalidate;
6313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006314 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6315 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006316 audio_attributes_t attr = client->attributes();
6317 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6318 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6319 audio_config_base_t clientConfig = client->config();
6320 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006321 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006322 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006323 streamsToInvalidate.insert(client->stream());
6324 }
6325 }
6326 }
6327
jiabinc44b3462022-12-08 12:52:31 -08006328 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006329}
6330
Eric Laurente191d1b2022-04-15 11:59:25 +02006331
6332bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6333 const sp<SwAudioOutputDescriptor>& outputDesc) {
6334 if (outputDesc->isDuplicated()) {
6335 return false;
6336 }
6337 DeviceVector devices = outputDesc->supportedDevices();
6338 for (size_t i = 0; i < mOutputs.size(); i++) {
6339 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6340 if (desc == outputDesc || desc->isDuplicated()) {
6341 continue;
6342 }
6343 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6344 if (!sharedDevices.isEmpty()
6345 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6346 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6347 return false;
6348 }
6349 }
6350 return true;
6351}
6352
6353
Eric Laurentfa0f6742021-08-17 18:39:44 +02006354status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006355 const audio_attributes_t *attr,
6356 audio_io_handle_t *output) {
6357 *output = AUDIO_IO_HANDLE_NONE;
6358
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006359 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6360 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6361 audio_config_t *configPtr = nullptr;
6362 audio_config_t config;
6363 if (mixerConfig != nullptr) {
6364 config = audio_config_initializer(mixerConfig);
6365 configPtr = &config;
6366 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006367 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006368 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006369 return BAD_VALUE;
6370 }
6371
6372 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006373 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006374 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006375 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006376 return BAD_VALUE;
6377 }
6378
Eric Laurente191d1b2022-04-15 11:59:25 +02006379 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006380 for (size_t i = 0; i < mOutputs.size(); i++) {
6381 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006382 if (!desc->isDuplicated()
6383 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6384 spatializerOutputs.push_back(desc);
6385 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006386 }
6387 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006388 mSpatializerOutput.clear();
6389 bool outputsChanged = false;
6390 for (const auto& desc : spatializerOutputs) {
6391 if (desc->mProfile == profile
6392 && (configPtr == nullptr
6393 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6394 mSpatializerOutput = desc;
6395 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6396 } else {
6397 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6398 " and devices %s", __func__, desc->mIoHandle,
6399 configPtr != nullptr ? configPtr->channel_mask : 0,
6400 devices.toString().c_str());
6401 closeOutput(desc->mIoHandle);
6402 outputsChanged = true;
6403 }
Eric Laurent39095982021-08-24 18:29:27 +02006404 }
6405
Eric Laurente191d1b2022-04-15 11:59:25 +02006406 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006407 sp<SwAudioOutputDescriptor> desc =
6408 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006409 if (desc != nullptr) {
6410 mSpatializerOutput = desc;
6411 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006412 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006413 }
6414
6415 checkVirtualizerClientRoutes();
6416
Eric Laurente191d1b2022-04-15 11:59:25 +02006417 if (outputsChanged) {
6418 mPreviousOutputs = mOutputs;
6419 mpClientInterface->onAudioPortListUpdate();
6420 }
6421
6422 if (mSpatializerOutput == nullptr) {
6423 ALOGV("%s could not open spatializer output with requested config", __func__);
6424 return BAD_VALUE;
6425 }
Eric Laurent39095982021-08-24 18:29:27 +02006426 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006427 ALOGV("%s returning new spatializer output %d", __func__, *output);
6428 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006429}
6430
Eric Laurentfa0f6742021-08-17 18:39:44 +02006431status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6432 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006433 return INVALID_OPERATION;
6434 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006435 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006436 return BAD_VALUE;
6437 }
Eric Laurent39095982021-08-24 18:29:27 +02006438
Eric Laurente191d1b2022-04-15 11:59:25 +02006439 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6440 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6441 closeOutput(mSpatializerOutput->mIoHandle);
6442 //from now on mSpatializerOutput is null
6443 checkVirtualizerClientRoutes();
6444 }
Eric Laurent39095982021-08-24 18:29:27 +02006445
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006446 return NO_ERROR;
6447}
6448
Eric Laurente552edb2014-03-10 17:42:56 -07006449// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006450// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006451// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006452uint32_t AudioPolicyManager::nextAudioPortGeneration()
6453{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006454 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006455}
6456
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006457AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006458 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006459 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006460 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006461 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006462 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006463 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006464 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006465 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006466 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006467 mAudioPortGeneration(1),
6468 mBeaconMuteRefCount(0),
6469 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006470 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006471 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006472 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006473 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006474{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006475}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006476
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006477status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006478 if (mEngine == nullptr) {
6479 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006480 }
6481 mEngine->setObserver(this);
6482 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006483 if (status != NO_ERROR) {
6484 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6485 return status;
6486 }
François Gaffie2110e042015-03-24 08:41:51 +01006487
jiabin29230182023-04-04 21:02:36 +00006488 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6489 // at the end of this function.
6490 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006491 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6492 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6493
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006494 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006495 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006496 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006497
Eric Laurent3a4311c2014-03-17 12:00:47 -07006498 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006499 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6500 defaultOutputDevice == nullptr ||
6501 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6502 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6503 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006504 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006505 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006506 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006507
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006508 // Silence ALOGV statements
6509 property_set("log.tag." LOG_TAG, "D");
6510
Eric Laurente552edb2014-03-10 17:42:56 -07006511 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006512 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006513}
6514
Eric Laurente0720872014-03-11 09:30:41 -07006515AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006516{
Eric Laurente552edb2014-03-10 17:42:56 -07006517 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006518 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006519 }
6520 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006521 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006522 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006523 mAvailableOutputDevices.clear();
6524 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006525 mOutputs.clear();
6526 mInputs.clear();
6527 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006528 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006529 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006530}
6531
Eric Laurente0720872014-03-11 09:30:41 -07006532status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006533{
Eric Laurent87ffa392015-05-22 10:32:38 -07006534 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006535}
6536
Eric Laurente552edb2014-03-10 17:42:56 -07006537// ---
6538
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006539void AudioPolicyManager::onNewAudioModulesAvailable()
6540{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006541 DeviceVector newDevices;
6542 onNewAudioModulesAvailableInt(&newDevices);
6543 if (!newDevices.empty()) {
6544 nextAudioPortGeneration();
6545 mpClientInterface->onAudioPortListUpdate();
6546 }
6547}
6548
6549void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6550{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006551 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006552 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6553 continue;
6554 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006555 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006556 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6557 handle != AUDIO_MODULE_HANDLE_NONE) {
6558 hwModule->setHandle(handle);
6559 } else {
6560 ALOGW("could not load HW module %s", hwModule->getName());
6561 continue;
6562 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006563 }
6564 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006565 // open all output streams needed to access attached devices.
6566 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006567 // This also validates mAvailableOutputDevices list
6568 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6569 if (!outProfile->canOpenNewIo()) {
6570 ALOGE("Invalid Output profile max open count %u for profile %s",
6571 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6572 continue;
6573 }
6574 if (!outProfile->hasSupportedDevices()) {
6575 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6576 continue;
6577 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006578 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6579 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006580 mTtsOutputAvailable = true;
6581 }
6582
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006583 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006584 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006585 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006586 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6587 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006588 } else {
6589 // choose first device present in profile's SupportedDevices also part of
6590 // mAvailableOutputDevices.
6591 if (availProfileDevices.isEmpty()) {
6592 continue;
6593 }
6594 supportedDevice = availProfileDevices.itemAt(0);
6595 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006596 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006597 continue;
6598 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306599
6600 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6601 && availProfileDevices.areAllDevicesAttached()) {
6602 ALOGV("%s skip opening output for mmap profile %s", __func__,
6603 outProfile->getTagName().c_str());
6604 continue;
6605 }
6606
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006607 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6608 mpClientInterface);
6609 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006610 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006611 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6612 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006613 AUDIO_STREAM_DEFAULT,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006614 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006615 if (status != NO_ERROR) {
6616 ALOGW("Cannot open output stream for devices %s on hw module %s",
6617 supportedDevice->toString().c_str(), hwModule->getName());
6618 continue;
6619 }
6620 for (const auto &device : availProfileDevices) {
6621 // give a valid ID to an attached device once confirmed it is reachable
6622 if (!device->isAttached()) {
6623 device->attach(hwModule);
6624 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006625 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006626 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006627 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6628 }
6629 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006630 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006631 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6632 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006633 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006634 }
Eric Laurent39095982021-08-24 18:29:27 +02006635 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006636 outputDesc->close();
6637 } else {
6638 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306639 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006640 DeviceVector(supportedDevice),
6641 true,
6642 0,
6643 NULL);
6644 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006645 }
6646 // open input streams needed to access attached devices to validate
6647 // mAvailableInputDevices list
6648 for (const auto& inProfile : hwModule->getInputProfiles()) {
6649 if (!inProfile->canOpenNewIo()) {
6650 ALOGE("Invalid Input profile max open count %u for profile %s",
6651 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6652 continue;
6653 }
6654 if (!inProfile->hasSupportedDevices()) {
6655 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6656 continue;
6657 }
6658 // chose first device present in profile's SupportedDevices also part of
6659 // available input devices
6660 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006661 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006662 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006663 ALOGV("%s: Input device list is empty! for profile %s",
6664 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006665 continue;
6666 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306667
6668 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6669 && availProfileDevices.areAllDevicesAttached()) {
6670 ALOGV("%s skip opening input for mmap profile %s", __func__,
6671 inProfile->getTagName().c_str());
6672 continue;
6673 }
6674
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006675 sp<AudioInputDescriptor> inputDesc =
6676 new AudioInputDescriptor(inProfile, mpClientInterface);
6677
6678 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6679 status_t status = inputDesc->open(nullptr,
6680 availProfileDevices.itemAt(0),
6681 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006682 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006683 &input);
6684 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306685 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6686 __func__, availProfileDevices.toString().c_str(),
6687 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006688 continue;
6689 }
6690 for (const auto &device : availProfileDevices) {
6691 // give a valid ID to an attached device once confirmed it is reachable
6692 if (!device->isAttached()) {
6693 device->attach(hwModule);
6694 device->importAudioPortAndPickAudioProfile(inProfile, true);
6695 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006696 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006697 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6698 }
6699 }
6700 inputDesc->close();
6701 }
6702 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006703
6704 // Check if spatializer outputs can be closed until used.
6705 // mOutputs vector never contains duplicated outputs at this point.
6706 std::vector<audio_io_handle_t> outputsClosed;
6707 for (size_t i = 0; i < mOutputs.size(); i++) {
6708 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6709 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6710 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6711 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006712 nextAudioPortGeneration();
6713 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6714 if (index >= 0) {
6715 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6716 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6717 patchDesc->getAfHandle(), 0);
6718 mAudioPatches.removeItemsAt(index);
6719 mpClientInterface->onAudioPatchListUpdate();
6720 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006721 desc->close();
6722 }
6723 }
6724 for (auto output : outputsClosed) {
6725 removeOutput(output);
6726 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006727}
6728
Eric Laurent98e38192018-02-15 18:31:53 -08006729void AudioPolicyManager::addOutput(audio_io_handle_t output,
6730 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006731{
Eric Laurent1c333e22014-05-20 10:48:17 -07006732 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006733 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006734 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006735 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006736 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006737}
6738
François Gaffie53615e22015-03-19 09:24:12 +01006739void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6740{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006741 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6742 ALOGV("%s: removing primary output", __func__);
6743 mPrimaryOutput = nullptr;
6744 }
François Gaffie53615e22015-03-19 09:24:12 +01006745 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006746 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006747}
6748
Eric Laurent98e38192018-02-15 18:31:53 -08006749void AudioPolicyManager::addInput(audio_io_handle_t input,
6750 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006751{
Eric Laurent1c333e22014-05-20 10:48:17 -07006752 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006753 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006754}
Eric Laurente552edb2014-03-10 17:42:56 -07006755
François Gaffie11d30102018-11-02 16:09:09 +01006756status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006757 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006758 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006759{
François Gaffie11d30102018-11-02 16:09:09 +01006760 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006761 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006762 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006763
François Gaffie11d30102018-11-02 16:09:09 +01006764 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006765 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006766 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006767 }
Eric Laurente552edb2014-03-10 17:42:56 -07006768
Eric Laurent3b73df72014-03-11 09:06:29 -07006769 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006770 // first call getAudioPort to get the supported attributes from the HAL
6771 struct audio_port_v7 port = {};
6772 device->toAudioPort(&port);
6773 status_t status = mpClientInterface->getAudioPort(&port);
6774 if (status == NO_ERROR) {
6775 device->importAudioPort(port);
6776 }
6777
6778 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006779 for (size_t i = 0; i < mOutputs.size(); i++) {
6780 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006781 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006782 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006783 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6784 mOutputs.keyAt(i), device->toString().c_str());
6785 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006786 }
6787 }
6788 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006789 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006790 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006791 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6792 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006793 if (profile->supportsDevice(device)) {
6794 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306795 ALOGV("%s(): adding profile %s from module %s",
6796 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006797 }
6798 }
6799 }
6800
Eric Laurent7b279bb2015-12-14 10:18:23 -08006801 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006802
Eric Laurente552edb2014-03-10 17:42:56 -07006803 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006804 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006805 return BAD_VALUE;
6806 }
6807
6808 // open outputs for matching profiles if needed. Direct outputs are also opened to
6809 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6810 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006811 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006812
6813 // nothing to do if one output is already opened for this profile
6814 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006815 for (j = 0; j < outputs.size(); j++) {
6816 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006817 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006818 // matching profile: save the sample rates, format and channel masks supported
6819 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006820 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006821 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006822 }
Eric Laurente552edb2014-03-10 17:42:56 -07006823 break;
6824 }
6825 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006826 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006827 continue;
6828 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306829 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6830 ALOGV("%s skip opening output for mmap profile %s",
6831 __func__, profile->getTagName().c_str());
6832 continue;
6833 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006834 if (!profile->canOpenNewIo()) {
6835 ALOGW("Max Output number %u already opened for this profile %s",
6836 profile->maxOpenCount, profile->getTagName().c_str());
6837 continue;
6838 }
6839
Eric Laurent83efe1c2017-07-09 16:51:08 -07006840 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006841 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006842 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6843 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006844 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006845 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006846 profiles.removeAt(profile_index);
6847 profile_index--;
6848 } else {
6849 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006850 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006851 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006852 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6853 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006854 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006855 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006856
François Gaffie11d30102018-11-02 16:09:09 +01006857 if (device_distinguishes_on_address(deviceType)) {
6858 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6859 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306860 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6861 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006862 }
Eric Laurente552edb2014-03-10 17:42:56 -07006863 ALOGV("checkOutputsForDevice(): adding output %d", output);
6864 }
6865 }
6866
6867 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006868 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006869 return BAD_VALUE;
6870 }
Eric Laurentd4692962014-05-05 18:13:44 -07006871 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006872 // check if one opened output is not needed any more after disconnecting one device
6873 for (size_t i = 0; i < mOutputs.size(); i++) {
6874 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006875 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006876 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006877 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006878 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006879 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006880 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006881 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6882 mOutputs.keyAt(i));
6883 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006884 }
Eric Laurente552edb2014-03-10 17:42:56 -07006885 }
6886 }
Eric Laurentd4692962014-05-05 18:13:44 -07006887 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006888 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006889 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6890 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006891 if (!profile->supportsDevice(device)) {
6892 continue;
6893 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306894 ALOGV("%s(): clearing direct output profile %s on module %s",
6895 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006896 profile->clearAudioProfiles();
6897 if (!profile->hasDynamicAudioProfile()) {
6898 continue;
6899 }
6900 // When a device is disconnected, if there is an IOProfile that contains dynamic
6901 // profiles and supports the disconnected device, call getAudioPort to repopulate
6902 // the capabilities of the devices that is supported by the IOProfile.
6903 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6904 if (supportedDevice == device ||
6905 !mAvailableOutputDevices.contains(supportedDevice)) {
6906 continue;
6907 }
6908 struct audio_port_v7 port;
6909 supportedDevice->toAudioPort(&port);
6910 status_t status = mpClientInterface->getAudioPort(&port);
6911 if (status == NO_ERROR) {
6912 supportedDevice->importAudioPort(port);
6913 }
Eric Laurente552edb2014-03-10 17:42:56 -07006914 }
6915 }
6916 }
6917 }
6918 return NO_ERROR;
6919}
6920
François Gaffie11d30102018-11-02 16:09:09 +01006921status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006922 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006923{
François Gaffie11d30102018-11-02 16:09:09 +01006924 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006925 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006926 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006927 }
6928
Eric Laurentd4692962014-05-05 18:13:44 -07006929 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006930 sp<AudioInputDescriptor> desc;
6931
jiabinbf5f4262023-04-12 21:48:34 +00006932 // first call getAudioPort to get the supported attributes from the HAL
6933 struct audio_port_v7 port = {};
6934 device->toAudioPort(&port);
6935 status_t status = mpClientInterface->getAudioPort(&port);
6936 if (status == NO_ERROR) {
6937 device->importAudioPort(port);
6938 }
6939
Eric Laurent0dd51852019-04-19 18:18:58 -07006940 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006941 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006942 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006943 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006944 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006945 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006946 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006947
François Gaffie11d30102018-11-02 16:09:09 +01006948 if (profile->supportsDevice(device)) {
6949 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306950 ALOGV("%s : adding profile %s from module %s", __func__,
6951 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006952 }
6953 }
6954 }
6955
Eric Laurent0dd51852019-04-19 18:18:58 -07006956 if (profiles.isEmpty()) {
6957 ALOGW("%s: No input profile available for device %s",
6958 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006959 return BAD_VALUE;
6960 }
6961
6962 // open inputs for matching profiles if needed. Direct inputs are also opened to
6963 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6964 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6965
Eric Laurent1c333e22014-05-20 10:48:17 -07006966 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006967
Eric Laurentd4692962014-05-05 18:13:44 -07006968 // nothing to do if one input is already opened for this profile
6969 size_t input_index;
6970 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6971 desc = mInputs.valueAt(input_index);
6972 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006973 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006974 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006975 }
Eric Laurentd4692962014-05-05 18:13:44 -07006976 break;
6977 }
6978 }
6979 if (input_index != mInputs.size()) {
6980 continue;
6981 }
6982
Jaideep Sharma44824a22024-06-18 16:32:34 +05306983 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6984 ALOGV("%s skip opening input for mmap profile %s",
6985 __func__, profile->getTagName().c_str());
6986 continue;
6987 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006988 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306989 ALOGW("%s Max Input number %u already opened for this profile %s",
6990 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08006991 continue;
6992 }
6993
Eric Laurentfe231122017-11-17 17:48:06 -08006994 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006995 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306996 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00006997 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
6998 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006999
Eric Laurentcf2c0212014-07-25 16:20:43 -07007000 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007001 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007002 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007003 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007004 mpClientInterface->setParameters(input, String8(param));
7005 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007006 }
jiabin12537fc2023-10-12 17:56:08 +00007007 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007008 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307009 ALOGW("%s direct input missing param for profile %s", __func__,
7010 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007011 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007012 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007013 }
7014
Eric Laurent0dd51852019-04-19 18:18:58 -07007015 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007016 addInput(input, desc);
7017 }
7018 } // endif input != 0
7019
Eric Laurentcf2c0212014-07-25 16:20:43 -07007020 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307021 ALOGW("%s could not open input for device %s on profile %s", __func__,
7022 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007023 profiles.removeAt(profile_index);
7024 profile_index--;
7025 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007026 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007027 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007028 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307029 ALOGV("%s: adding input %d for profile %s", __func__,
7030 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007031
7032 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307033 ALOGV("%s: closing input %d for profile %s", __func__,
7034 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007035 closeInput(input);
7036 }
Eric Laurentd4692962014-05-05 18:13:44 -07007037 }
7038 } // end scan profiles
7039
7040 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007041 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007042 return BAD_VALUE;
7043 }
7044 } else {
7045 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007046 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007047 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007048 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007049 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007050 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007051 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007052 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307053 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7054 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007055 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007056 }
7057 }
7058 }
7059 } // end disconnect
7060
7061 return NO_ERROR;
7062}
7063
7064
Eric Laurente0720872014-03-11 09:30:41 -07007065void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007066{
7067 ALOGV("closeOutput(%d)", output);
7068
François Gaffie1c878552018-11-22 16:53:21 +01007069 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7070 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007071 ALOGW("closeOutput() unknown output %d", output);
7072 return;
7073 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007074 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007075 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007076
Eric Laurente552edb2014-03-10 17:42:56 -07007077 // look for duplicated outputs connected to the output being removed.
7078 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007079 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7080 if (dupOutput->isDuplicated() &&
7081 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7082 sp<SwAudioOutputDescriptor> remainingOutput =
7083 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007084 // As all active tracks on duplicated output will be deleted,
7085 // and as they were also referenced on the other output, the reference
7086 // count for their stream type must be adjusted accordingly on
7087 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007088 const bool wasActive = remainingOutput->isActive();
7089 // Note: no-op on the closing output where all clients has already been set inactive
7090 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007091 // stop() will be a no op if the output is still active but is needed in case all
7092 // active streams refcounts where cleared above
7093 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007094 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007095 }
Eric Laurente552edb2014-03-10 17:42:56 -07007096 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7097 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7098
7099 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007100 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007101 }
7102 }
7103
Eric Laurent05b90f82014-08-27 15:32:29 -07007104 nextAudioPortGeneration();
7105
François Gaffie1c878552018-11-22 16:53:21 +01007106 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007107 if (index >= 0) {
7108 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007109 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7110 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007111 mAudioPatches.removeItemsAt(index);
7112 mpClientInterface->onAudioPatchListUpdate();
7113 }
7114
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007115 if (closingOutputWasActive) {
7116 closingOutput->stop();
7117 }
François Gaffie1c878552018-11-22 16:53:21 +01007118 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007119 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007120 for (const auto device : closingOutput->devices()) {
7121 device->setPreferredConfig(nullptr);
7122 }
7123 }
Eric Laurente552edb2014-03-10 17:42:56 -07007124
François Gaffie53615e22015-03-19 09:24:12 +01007125 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007126 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007127 if (closingOutput == mSpatializerOutput) {
7128 mSpatializerOutput.clear();
7129 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007130
7131 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7132 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007133 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007134 bool directOutputOpen = false;
7135 for (size_t i = 0; i < mOutputs.size(); i++) {
7136 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7137 directOutputOpen = true;
7138 break;
7139 }
7140 }
7141 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007142 ALOGV("no direct outputs open, reset MSD patches");
7143 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7144 // how output devices for patching are resolved. Avoid by caching and reusing the
7145 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7146 // devices to patch to. This may be complicated by the fact that devices may become
7147 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007148 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007149 }
7150 }
jiabin220eea12024-05-17 17:55:20 +00007151
7152 if (closingOutput->mPreferredAttrInfo != nullptr) {
7153 closingOutput->mPreferredAttrInfo->resetActiveClient();
7154 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007155}
7156
7157void AudioPolicyManager::closeInput(audio_io_handle_t input)
7158{
7159 ALOGV("closeInput(%d)", input);
7160
7161 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7162 if (inputDesc == NULL) {
7163 ALOGW("closeInput() unknown input %d", input);
7164 return;
7165 }
7166
Eric Laurent6a94d692014-05-20 11:18:06 -07007167 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007168
François Gaffie11d30102018-11-02 16:09:09 +01007169 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007170 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007171 if (index >= 0) {
7172 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007173 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7174 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007175 mAudioPatches.removeItemsAt(index);
7176 mpClientInterface->onAudioPatchListUpdate();
7177 }
7178
François Gaffie6ebbce02023-07-19 13:27:53 +02007179 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007180 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007181 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007182
François Gaffie11d30102018-11-02 16:09:09 +01007183 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7184 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007185 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007186 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007187 }
Eric Laurente552edb2014-03-10 17:42:56 -07007188}
7189
François Gaffie11d30102018-11-02 16:09:09 +01007190SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7191 const DeviceVector &devices,
7192 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007193{
7194 SortedVector<audio_io_handle_t> outputs;
7195
François Gaffie11d30102018-11-02 16:09:09 +01007196 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007197 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007198 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007199 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007200 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007201 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007202 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007203 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007204 outputs.add(openOutputs.keyAt(i));
7205 }
7206 }
7207 return outputs;
7208}
7209
Mikhail Naganov37977152018-07-11 15:54:44 -07007210void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7211{
7212 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7213 // output is suspended before any tracks are moved to it
7214 checkA2dpSuspend();
7215 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007216 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007217 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007218 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007219 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007220 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7221 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7222 // configuration changes will ultimately be rerouted correctly. We can still avoid
7223 // unnecessary rerouting by caching and reusing the arguments to
7224 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7225 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007226 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007227 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007228 // an event that changed routing likely occurred, inform upper layers
7229 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007230}
7231
François Gaffiec005e562018-11-06 15:04:49 +01007232bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7233 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007234{
François Gaffiec005e562018-11-06 15:04:49 +01007235 return mEngine->getProductStrategyForAttributes(lAttr) ==
7236 mEngine->getProductStrategyForAttributes(rAttr);
7237}
7238
Francois Gaffieff1eb522020-05-06 18:37:04 +02007239void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7240{
7241 for (size_t i = 0; i < mAudioSources.size(); i++) {
7242 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7243 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007244 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007245 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007246 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007247 }
7248 }
7249}
7250
7251void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7252{
7253 for (size_t i = 0; i < mAudioSources.size(); i++) {
7254 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7255 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7256 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7257 disconnectAudioSource(sourceDesc);
7258 }
7259 }
7260}
7261
François Gaffiec005e562018-11-06 15:04:49 +01007262void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7263{
7264 auto psId = mEngine->getProductStrategyForAttributes(attr);
7265
7266 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7267 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007268
François Gaffie11d30102018-11-02 16:09:09 +01007269 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7270 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007271
Eric Laurentc209fe42020-06-05 18:11:23 -07007272 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007273 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007274 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007275 // take into account dynamic audio policies related changes: if a client is now associated
7276 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007277 // invalidate clients on outputs that do not support all the newly selected devices for the
7278 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007279 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007280 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007281 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007282 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007283 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007284
Eric Laurentc209fe42020-06-05 18:11:23 -07007285 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7286 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7287 continue;
7288 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007289 if (!desc->supportsAllDevices(newDevices)) {
7290 invalidatedOutputs.push_back(desc);
7291 break;
7292 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007293 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007294 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007295 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7296 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7297 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007298 if (status == OK) {
7299 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7300 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7301 maxLatency = desc->latency();
7302 }
7303 invalidatedOutputs.push_back(desc);
7304 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007305 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007306 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007307 }
7308 }
7309
Eric Laurent56ed8842022-11-15 16:04:41 +01007310 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007311 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7312 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007313 for (audio_io_handle_t srcOut : srcOutputs) {
7314 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007315 if (desc == nullptr) continue;
7316
7317 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007318 maxLatency = desc->latency();
7319 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007320
Eric Laurent56ed8842022-11-15 16:04:41 +01007321 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007322 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007323 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007324 // a client on a non direct outputs has necessarily a linear PCM format
7325 // so we can call selectOutput() safely
7326 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7327 client->flags(),
7328 client->config().format,
7329 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007330 client->config().sample_rate,
7331 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007332 if (newOutput != srcOut) {
7333 invalidate = true;
7334 break;
7335 }
7336 } else {
7337 sp<IOProfile> profile = getProfileForOutput(newDevices,
7338 client->config().sample_rate,
7339 client->config().format,
7340 client->config().channel_mask,
7341 client->flags(),
7342 true /* directOnly */);
7343 if (profile != desc->mProfile) {
7344 invalidate = true;
7345 break;
7346 }
7347 }
7348 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007349 // mute strategy while moving tracks from one output to another
7350 if (invalidate) {
7351 invalidatedOutputs.push_back(desc);
7352 if (desc->isStrategyActive(psId)) {
7353 setStrategyMute(psId, true, desc);
7354 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7355 newDevices.types());
7356 }
Eric Laurente552edb2014-03-10 17:42:56 -07007357 }
François Gaffiec005e562018-11-06 15:04:49 +01007358 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007359 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007360 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007361 }
Eric Laurente552edb2014-03-10 17:42:56 -07007362 }
7363
Eric Laurent56ed8842022-11-15 16:04:41 +01007364 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7365 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7366 std::to_string(srcOutputs[0]).c_str(),
7367 std::to_string(dstOutputs[0]).c_str());
7368
François Gaffiec005e562018-11-06 15:04:49 +01007369 // Move effects associated to this stream from previous output to new output
7370 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007371 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007372 }
François Gaffiec005e562018-11-06 15:04:49 +01007373 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007374 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007375 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007376 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007377 desc->setTracksInvalidatedStatusByStrategy(psId);
7378 }
Eric Laurente552edb2014-03-10 17:42:56 -07007379 }
7380 }
7381}
7382
Eric Laurente0720872014-03-11 09:30:41 -07007383void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007384{
François Gaffiec005e562018-11-06 15:04:49 +01007385 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7386 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7387 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007388 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007389 }
Eric Laurente552edb2014-03-10 17:42:56 -07007390}
7391
Kevin Rocard153f92d2018-12-18 18:33:28 -08007392void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007393 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007394 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007395 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007396 for (size_t i = 0; i < mOutputs.size(); i++) {
7397 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7398 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007399 sp<AudioPolicyMix> primaryMix;
7400 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007401 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007402 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7403 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7404 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007405 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7406 for (auto &secondaryMix : secondaryMixes) {
7407 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7408 if (outputDesc != nullptr &&
7409 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7410 secondaryDescs.push_back(outputDesc);
7411 }
7412 }
7413
jiabinc44b3462022-12-08 12:52:31 -08007414 if (status != OK &&
7415 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7416 // When it failed to query secondary output, only invalidate the client that is not
7417 // MMAP. The reason is that MMAP stream will not support secondary output.
7418 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007419 } else if (!std::equal(
7420 client->getSecondaryOutputs().begin(),
7421 client->getSecondaryOutputs().end(),
7422 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007423 if (!audio_is_linear_pcm(client->config().format)) {
7424 // If the format is not PCM, the tracks should be invalidated to get correct
7425 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007426 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007427 } else {
7428 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7429 std::vector<audio_io_handle_t> secondaryOutputIds;
7430 for (const auto &secondaryDesc: secondaryDescs) {
7431 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7432 weakSecondaryDescs.push_back(secondaryDesc);
7433 }
7434 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7435 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007436 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007437 }
7438 }
7439 }
jiabin10a03f12021-05-07 23:46:28 +00007440 if (!trackSecondaryOutputs.empty()) {
7441 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7442 }
jiabinc44b3462022-12-08 12:52:31 -08007443 if (!clientsToInvalidate.empty()) {
7444 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7445 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007446 }
7447}
7448
Eric Laurent2517af32020-11-25 15:31:27 +01007449bool AudioPolicyManager::isScoRequestedForComm() const {
7450 AudioDeviceTypeAddrVector devices;
7451 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7452 for (const auto &device : devices) {
7453 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7454 return true;
7455 }
7456 }
7457 return false;
7458}
7459
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007460bool AudioPolicyManager::isHearingAidUsedForComm() const {
7461 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7462 true /*fromCache*/);
7463 for (const auto &device : devices) {
7464 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7465 return true;
7466 }
7467 }
7468 return false;
7469}
7470
7471
Eric Laurente0720872014-03-11 09:30:41 -07007472void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007473{
François Gaffie53615e22015-03-19 09:24:12 +01007474 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007475 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007476 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007477 return;
7478 }
7479
Eric Laurent3a4311c2014-03-17 12:00:47 -07007480 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007481 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7482 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007483 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007484
7485 // if suspended, restore A2DP output if:
7486 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007487 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007488 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007489 //
Eric Laurentf732e072016-08-03 19:30:28 -07007490 // if not suspended, suspend A2DP output if:
7491 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007492 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007493 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007494 //
7495 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007496 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007497 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007498 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007499 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007500
7501 mpClientInterface->restoreOutput(a2dpOutput);
7502 mA2dpSuspended = false;
7503 }
7504 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007505 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007506 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007507 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007508 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007509
7510 mpClientInterface->suspendOutput(a2dpOutput);
7511 mA2dpSuspended = true;
7512 }
7513 }
7514}
7515
François Gaffie11d30102018-11-02 16:09:09 +01007516DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7517 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007518{
François Gaffiedb1755b2023-09-01 11:50:35 +02007519 if (outputDesc == nullptr) {
7520 return DeviceVector{};
7521 }
François Gaffie11d30102018-11-02 16:09:09 +01007522
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007523 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007524 if (index >= 0) {
7525 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007526 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007527 ALOGV("%s device %s forced by patch %d", __func__,
7528 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7529 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007530 }
7531 }
7532
Dean Wheatley514b4312020-06-17 21:45:00 +10007533 // Do not retrieve engine device for outputs through MSD
7534 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7535 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7536 return outputDesc->devices();
7537 }
7538
Eric Laurent97ac8712018-07-27 18:59:02 -07007539 // Honor explicit routing requests only if no client using default routing is active on this
7540 // input: a specific app can not force routing for other apps by setting a preferred device.
7541 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007542 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007543 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007544 if (device != nullptr) {
7545 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007546 }
7547
François Gaffiea807ef92018-11-05 10:44:33 +01007548 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7549 // of setForceUse / Default Bus device here
7550 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7551 if (device != nullptr) {
7552 return DeviceVector(device);
7553 }
7554
François Gaffiedb1755b2023-09-01 11:50:35 +02007555 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007556 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7557 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307558 auto hasStreamActive = [&](auto stream) {
7559 return hasStream(streams, stream) && isStreamActive(stream, 0);
7560 };
Eric Laurent484e9272018-06-07 17:29:23 -07007561
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307562 auto doGetOutputDevicesForVoice = [&]() {
7563 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007564 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307565 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007566 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7567 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307568 };
7569
7570 // With low-latency playing on speaker, music on WFD, when the first low-latency
7571 // output is stopped, getNewOutputDevices checks for a product strategy
7572 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007573 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307574 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7575 // stream is associated to the output descriptor.
7576 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7577 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7578 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7579 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007580 // Retrieval of devices for voice DL is done on primary output profile, cannot
7581 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007582 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007583 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7584 break;
7585 }
Eric Laurente552edb2014-03-10 17:42:56 -07007586 }
François Gaffiec005e562018-11-06 15:04:49 +01007587 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007588 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007589}
7590
François Gaffie11d30102018-11-02 16:09:09 +01007591sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7592 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007593{
François Gaffie11d30102018-11-02 16:09:09 +01007594 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007595
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007596 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007597 if (index >= 0) {
7598 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007599 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007600 ALOGV("getNewInputDevice() device %s forced by patch %d",
7601 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7602 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007603 }
7604 }
7605
Eric Laurent97ac8712018-07-27 18:59:02 -07007606 // Honor explicit routing requests only if no client using default routing is active on this
7607 // input: a specific app can not force routing for other apps by setting a preferred device.
7608 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007609 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7610 if (device != nullptr) {
7611 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007612 }
7613
Eric Laurentdc95a252018-04-12 12:46:56 -07007614 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007615 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007616 audio_attributes_t attributes;
7617 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007618 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007619 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7620 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007621 attributes = topClient->attributes();
7622 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007623 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007624 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007625 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7626 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007627 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007628 }
7629
Francois Gaffie716e1432019-01-14 16:58:59 +01007630 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7631 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007632 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007633 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007634 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007635 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007636
Eric Laurente552edb2014-03-10 17:42:56 -07007637 return device;
7638}
7639
Eric Laurent794fde22016-03-11 09:50:45 -08007640bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7641 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007642 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007643}
7644
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007645status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007646 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007647 if (devices == nullptr) {
7648 return BAD_VALUE;
7649 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007650
Andy Hung6d23c0f2022-02-16 09:37:15 -08007651 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007652 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7653 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007654 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007655 for (const auto& device : curDevices) {
7656 devices->push_back(device->getDeviceTypeAddr());
7657 }
7658 return NO_ERROR;
7659}
7660
Eric Laurente0720872014-03-11 09:30:41 -07007661void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007662 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007663 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007664 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007665 updateDevicesAndOutputs();
7666 break;
7667 default:
7668 break;
7669 }
7670}
7671
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007672uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007673
7674 // skip beacon mute management if a dedicated TTS output is available
7675 if (mTtsOutputAvailable) {
7676 return 0;
7677 }
7678
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007679 switch(event) {
7680 case STARTING_OUTPUT:
7681 mBeaconMuteRefCount++;
7682 break;
7683 case STOPPING_OUTPUT:
7684 if (mBeaconMuteRefCount > 0) {
7685 mBeaconMuteRefCount--;
7686 }
7687 break;
7688 case STARTING_BEACON:
7689 mBeaconPlayingRefCount++;
7690 break;
7691 case STOPPING_BEACON:
7692 if (mBeaconPlayingRefCount > 0) {
7693 mBeaconPlayingRefCount--;
7694 }
7695 break;
7696 }
7697
7698 if (mBeaconMuteRefCount > 0) {
7699 // any playback causes beacon to be muted
7700 return setBeaconMute(true);
7701 } else {
7702 // no other playback: unmute when beacon starts playing, mute when it stops
7703 return setBeaconMute(mBeaconPlayingRefCount == 0);
7704 }
7705}
7706
7707uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7708 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7709 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7710 // keep track of muted state to avoid repeating mute/unmute operations
7711 if (mBeaconMuted != mute) {
7712 // mute/unmute AUDIO_STREAM_TTS on all outputs
7713 ALOGV("\t muting %d", mute);
7714 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007715 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7716 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7717 ALOGV("\t no tts volume source available");
7718 return 0;
7719 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007720 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007721 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007722 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007723 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007724 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007725 maxLatency = latency;
7726 }
7727 }
7728 mBeaconMuted = mute;
7729 return maxLatency;
7730 }
7731 return 0;
7732}
7733
Eric Laurente0720872014-03-11 09:30:41 -07007734void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007735{
François Gaffiec005e562018-11-06 15:04:49 +01007736 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007737 mPreviousOutputs = mOutputs;
7738}
7739
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007740uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007741 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007742 uint32_t delayMs)
7743{
7744 // mute/unmute strategies using an incompatible device combination
7745 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7746 // if unmuting, unmute only after the specified delay
7747 if (outputDesc->isDuplicated()) {
7748 return 0;
7749 }
7750
7751 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007752 DeviceVector devices = outputDesc->devices();
7753 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007754
François Gaffiec005e562018-11-06 15:04:49 +01007755 auto productStrategies = mEngine->getOrderedProductStrategies();
7756 for (const auto &productStrategy : productStrategies) {
7757 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7758 DeviceVector curDevices =
7759 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7760 curDevices = curDevices.filter(outputDesc->supportedDevices());
7761 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007762 bool doMute = false;
7763
François Gaffiec005e562018-11-06 15:04:49 +01007764 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007765 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007766 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7767 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007768 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007769 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007770 }
Eric Laurent99401132014-05-07 19:48:15 -07007771 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007772 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007773 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007774 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007775 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007776 continue;
7777 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307778 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007779 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7780 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7781 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007782 if (mute) {
7783 // FIXME: should not need to double latency if volume could be applied
7784 // immediately by the audioflinger mixer. We must account for the delay
7785 // between now and the next time the audioflinger thread for this output
7786 // will process a buffer (which corresponds to one buffer size,
7787 // usually 1/2 or 1/4 of the latency).
7788 if (muteWaitMs < desc->latency() * 2) {
7789 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007790 }
7791 }
7792 }
7793 }
7794 }
7795 }
7796
Eric Laurent99401132014-05-07 19:48:15 -07007797 // temporary mute output if device selection changes to avoid volume bursts due to
7798 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007799 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007800 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007801
Eric Laurentdc462862016-07-19 12:29:53 -07007802 if (muteWaitMs < tempMuteWaitMs) {
7803 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007804 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007805
7806 // If recommended duration is defined, replace temporary mute duration to avoid
7807 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7808 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7809 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7810 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7811 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7812
François Gaffieaaac0fd2018-11-22 17:56:39 +01007813 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7814 // make sure that we do not start the temporary mute period too early in case of
7815 // delayed device change
7816 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7817 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007818 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007819 }
7820 }
7821
Eric Laurente552edb2014-03-10 17:42:56 -07007822 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7823 if (muteWaitMs > delayMs) {
7824 muteWaitMs -= delayMs;
7825 usleep(muteWaitMs * 1000);
7826 return muteWaitMs;
7827 }
7828 return 0;
7829}
7830
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307831uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7832 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007833 const DeviceVector &devices,
7834 bool force,
7835 int delayMs,
7836 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007837 bool requiresMuteCheck, bool requiresVolumeCheck,
7838 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007839{
jiabin3ff8d7d2022-12-13 06:27:44 +00007840 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307841 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7842 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7843 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007844 uint32_t muteWaitMs;
7845
7846 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307847 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007848 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307849 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007850 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007851 return muteWaitMs;
7852 }
Eric Laurente552edb2014-03-10 17:42:56 -07007853
7854 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007855 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007856 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007857 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007858
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307859 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7860 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007861
7862 if (!filteredDevices.isEmpty()) {
7863 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007864 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007865
7866 // if the outputs are not materially active, there is no need to mute.
7867 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007868 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007869 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307870 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7871 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007872 muteWaitMs = 0;
7873 }
Eric Laurente552edb2014-03-10 17:42:56 -07007874
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007875 bool outputRouted = outputDesc->isRouted();
7876
Eric Laurent79ea9582020-06-11 18:49:24 -07007877 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7878 // output profile or if new device is not supported AND previous device(s) is(are) still
7879 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007880 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307881 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7882 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007883 // restore previous device after evaluating strategy mute state
7884 outputDesc->setDevices(prevDevices);
7885 return muteWaitMs;
7886 }
7887
Eric Laurente552edb2014-03-10 17:42:56 -07007888 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007889 // the requested device is AUDIO_DEVICE_NONE
7890 // OR the requested device is the same as current device
7891 // AND force is not specified
7892 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007893 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007894 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307895 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7896 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7897 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007898 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307899 ALOGV("%s %s setting same device on routed output, force apply volumes",
7900 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007901 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7902 }
Eric Laurente552edb2014-03-10 17:42:56 -07007903 return muteWaitMs;
7904 }
7905
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307906 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7907 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007908
Eric Laurente552edb2014-03-10 17:42:56 -07007909 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007910 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007911 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007912 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007913 PatchBuilder patchBuilder;
7914 patchBuilder.addSource(outputDesc);
7915 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7916 for (const auto &filteredDevice : filteredDevices) {
7917 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007918 }
7919
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007920 // Add half reported latency to delayMs when muteWaitMs is null in order
7921 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007922 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7923 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7924 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007925 }
Eric Laurente552edb2014-03-10 17:42:56 -07007926
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007927 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7928 if (!skipMuteDelay) {
7929 // update stream volumes according to new device
7930 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7931 }
Eric Laurente552edb2014-03-10 17:42:56 -07007932
7933 return muteWaitMs;
7934}
7935
Eric Laurentc75307b2015-03-17 15:29:32 -07007936status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007937 int delayMs,
7938 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007939{
Eric Laurent6a94d692014-05-20 11:18:06 -07007940 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007941 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7942 return INVALID_OPERATION;
7943 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007944 if (patchHandle) {
7945 index = mAudioPatches.indexOfKey(*patchHandle);
7946 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007947 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007948 }
7949 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007950 return INVALID_OPERATION;
7951 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007952 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007953 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007954 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007955 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007956 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007957 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007958 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007959 return status;
7960}
7961
7962status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007963 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007964 bool force,
7965 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007966{
7967 status_t status = NO_ERROR;
7968
Eric Laurent1f2f2232014-06-02 12:01:23 -07007969 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007970 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7971 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007972
François Gaffie11d30102018-11-02 16:09:09 +01007973 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007974 PatchBuilder patchBuilder;
7975 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007976 // AUDIO_SOURCE_HOTWORD is for internal use only:
7977 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007978 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7979 auto result = usecase;
7980 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7981 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7982 }
7983 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007984 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007985 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007986 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007987 }
7988 }
7989 return status;
7990}
7991
Eric Laurent6a94d692014-05-20 11:18:06 -07007992status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7993 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007994{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007995 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007996 ssize_t index;
7997 if (patchHandle) {
7998 index = mAudioPatches.indexOfKey(*patchHandle);
7999 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008000 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008001 }
8002 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008003 return INVALID_OPERATION;
8004 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008005 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008006 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008007 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008008 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008009 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008010 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008011 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008012 return status;
8013}
8014
François Gaffie11d30102018-11-02 16:09:09 +01008015sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008016 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008017 audio_format_t& format,
8018 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008019 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008020{
8021 // Choose an input profile based on the requested capture parameters: select the first available
8022 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008023 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008024
Atneya Nair0f0a8032022-12-12 16:20:12 -08008025 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8026 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8027 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8028
8029 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008030
jiabin2fd710d2022-05-02 23:20:22 +00008031 for (;;) {
8032 sp<IOProfile> firstInexact = nullptr;
8033 uint32_t updatedSamplingRate = 0;
8034 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8035 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8036 for (const auto& hwModule : mHwModules) {
8037 for (const auto& profile : hwModule->getInputProfiles()) {
8038 // profile->log();
8039 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008040 if (profile->getCompatibilityScore(
8041 DeviceVector(device),
8042 samplingRate,
8043 &updatedSamplingRate,
8044 format,
8045 &updatedFormat,
8046 channelMask,
8047 &updatedChannelMask,
8048 // FIXME ugly cast
8049 (audio_output_flags_t) flags,
8050 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8051 samplingRate = updatedSamplingRate;
8052 format = updatedFormat;
8053 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008054 return profile;
8055 }
jiabin66acc432024-02-06 00:57:36 +00008056 if (firstInexact == nullptr
8057 && profile->getCompatibilityScore(
8058 DeviceVector(device),
8059 samplingRate,
8060 &updatedSamplingRate,
8061 format,
8062 &updatedFormat,
8063 channelMask,
8064 &updatedChannelMask,
8065 // FIXME ugly cast
8066 (audio_output_flags_t) flags,
8067 false /*exactMatchRequiredForInputFlags*/)
8068 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008069 firstInexact = profile;
8070 }
8071 }
8072 }
8073
8074 if (firstInexact != nullptr) {
8075 samplingRate = updatedSamplingRate;
8076 format = updatedFormat;
8077 channelMask = updatedChannelMask;
8078 return firstInexact;
8079 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8080 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8081 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8082 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8083 flags = AUDIO_INPUT_FLAG_NONE;
8084 } else { // fail
8085 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8086 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8087 samplingRate, format, channelMask, oriFlags);
8088 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008089 }
8090 }
jiabin2fd710d2022-05-02 23:20:22 +00008091
8092 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008093}
8094
Vlad Popa87e0e582024-05-20 18:49:20 -07008095float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8096 VolumeSource volumeSource,
8097 int index,
8098 const DeviceTypeSet &deviceTypes)
8099{
8100 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8101 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8102 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8103
8104 if (com_android_media_audio_abs_volume_index_fix()) {
8105 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8106 mAbsoluteVolumeDrivingStreams.end()) {
8107 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8108 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8109 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8110 ALOGD("%s: no group matching with %s", __FUNCTION__,
8111 toString(attributesToDriveAbs).c_str());
8112 return volumeDb;
8113 }
8114
8115 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8116 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8117 if (vsToDriveAbs == volumeSource) {
8118 // attenuation is applied by the abs volume controller
8119 return volumeDbMax;
8120 } else {
8121 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8122 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8123 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8124 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8125 curvesAbs.getVolumeIndexMax());
8126 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8127 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8128 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8129 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8130 return newVolumeDb;
8131 }
8132 }
8133 return volumeDb;
8134 } else {
8135 return volumeDb;
8136 }
8137}
8138
François Gaffieaaac0fd2018-11-22 17:56:39 +01008139float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8140 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008141 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008142 const DeviceTypeSet& deviceTypes,
8143 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008144{
Vlad Popa87e0e582024-05-20 18:49:20 -07008145 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008146 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8147 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8148
8149 if (!computeInternalInteraction) {
8150 return volumeDb;
8151 }
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008152
8153 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8154 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8155 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8156 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008157 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8158 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8159 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8160 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8161 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008162 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008163 mOutputs.isActive(ringVolumeSrc, 0)) {
8164 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008165 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8166 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008167 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008168 }
8169
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008170 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008171 if ((volumeSource != callVolumeSrc && (isInCall() ||
8172 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008173 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008174 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8175 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008176 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8177 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8178 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008179 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008180 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008181 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008182 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008183 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8184 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008185 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008186 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8187 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8188 // programmatically muted.
8189 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8190 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8191 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008192 bool exemptFromCapping =
8193 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8194 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008195 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8196 volumeSource, volumeDb);
8197 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008198 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8199 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8200 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008201 }
8202 }
Eric Laurente552edb2014-03-10 17:42:56 -07008203 // if a headset is connected, apply the following rules to ring tones and notifications
8204 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008205 // - always attenuate notifications volume by 6dB
8206 // - attenuate ring tones volume by 6dB unless music is not playing and
8207 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008208 // - if music is playing, always limit the volume to current music volume,
8209 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008210 if (!Intersection(deviceTypes,
8211 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8212 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008213 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8214 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008215 ((volumeSource == alarmVolumeSrc ||
8216 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008217 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8218 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8219 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008220 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8221 curves.canBeMuted()) {
8222
Eric Laurente552edb2014-03-10 17:42:56 -07008223 // when the phone is ringing we must consider that music could have been paused just before
8224 // by the music application and behave as if music was active if the last music track was
8225 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008226 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8227 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008228 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008229 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008230 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8231 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008232 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008233 float musicVolDb = computeVolume(musicCurves,
8234 musicVolumeSrc,
8235 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008236 musicDevice,
8237 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008238 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8239 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8240 if (volumeDb > minVolDb) {
8241 volumeDb = minVolDb;
8242 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008243 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008244 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8245 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008246 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8247 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8248 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8249 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008250 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008251 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008252 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8253 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008254 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8255 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008256 }
8257 }
jiabin9a3361e2019-10-01 09:38:30 -07008258 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008259 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008260 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008261 }
8262 }
8263
François Gaffie43c73442018-11-08 08:21:55 +01008264 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008265}
8266
Eric Laurent3839bc02018-07-10 18:33:34 -07008267int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008268 VolumeSource fromVolumeSource,
8269 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008270{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008271 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008272 return srcIndex;
8273 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008274 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8275 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008276 float minSrc = (float)srcCurves.getVolumeIndexMin();
8277 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8278 float minDst = (float)dstCurves.getVolumeIndexMin();
8279 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008280
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008281 // preserve mute request or correct range
8282 if (srcIndex < minSrc) {
8283 if (srcIndex == 0) {
8284 return 0;
8285 }
8286 srcIndex = minSrc;
8287 } else if (srcIndex > maxSrc) {
8288 srcIndex = maxSrc;
8289 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008290 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8291}
8292
François Gaffieaaac0fd2018-11-22 17:56:39 +01008293status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8294 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008295 int index,
8296 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008297 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008298 int delayMs,
8299 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008300{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008301 // APM is single threaded, and single instance.
8302 static std::set<IVolumeCurves*> invalidCurvesReported;
8303
François Gaffieaaac0fd2018-11-22 17:56:39 +01008304 // do not change actual attributes volume if the attributes is muted
8305 if (outputDesc->isMuted(volumeSource)) {
8306 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8307 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008308 return NO_ERROR;
8309 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008310
Eric Laurent5baf07c2024-01-11 16:57:27 +00008311 bool isVoiceVolSrc;
8312 bool isBtScoVolSrc;
8313 if (!isVolumeConsistentForCalls(
8314 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008315 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008316 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008317 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008318 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008319
jiabin9a3361e2019-10-01 09:38:30 -07008320 if (deviceTypes.empty()) {
8321 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008322 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008323 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008324 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008325 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008326
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008327 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008328 if (!invalidCurvesReported.count(&curves)) {
8329 invalidCurvesReported.insert(&curves);
8330 String8 dump;
8331 curves.dump(&dump);
8332 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8333 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008334 return BAD_VALUE;
8335 }
8336
jiabin9a3361e2019-10-01 09:38:30 -07008337 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8338 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008339 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008340 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008341 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8342 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008343 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008344 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008345 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008346 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8347 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008348
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008349 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008350 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8351 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8352 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008353 }
Eric Laurente552edb2014-03-10 17:42:56 -07008354 return NO_ERROR;
8355}
8356
Eric Laurent5baf07c2024-01-11 16:57:27 +00008357void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008358 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008359 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008360 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008361 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008362 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008363 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8364 } else {
8365 voiceVolume = index == 0 ? 0.0 : 1.0;
8366 }
8367 if (voiceVolume != mLastVoiceVolume) {
8368 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8369 mLastVoiceVolume = voiceVolume;
8370 }
8371}
8372
8373bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8374 const DeviceTypeSet& deviceTypes,
8375 bool& isVoiceVolSrc,
8376 bool& isBtScoVolSrc,
8377 const char* caller) {
8378 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8379 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8380 const bool isScoRequested = isScoRequestedForComm();
8381 const bool isHAUsed = isHearingAidUsedForComm();
8382
8383 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8384 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8385
8386 if ((callVolSrc != btScoVolSrc) &&
8387 ((isVoiceVolSrc && isScoRequested) ||
8388 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8389 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8390 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8391 volumeSource, isScoRequested ? " " : " not ");
8392 return false;
8393 }
8394 return true;
8395}
8396
Eric Laurentc75307b2015-03-17 15:29:32 -07008397void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008398 const DeviceTypeSet& deviceTypes,
8399 int delayMs,
8400 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008401{
jiabincd510522020-01-22 09:40:55 -08008402 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008403 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8404 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8405 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008406 curves.getVolumeIndex(deviceTypes),
8407 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008408 }
8409}
8410
François Gaffiec005e562018-11-06 15:04:49 +01008411void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8412 bool on,
8413 const sp<AudioOutputDescriptor>& outputDesc,
8414 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008415 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008416{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008417 std::vector<VolumeSource> sourcesToMute;
8418 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8419 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8420 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008421 VolumeSource source = toVolumeSource(attributes, false);
8422 if ((source != VOLUME_SOURCE_NONE) &&
8423 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8424 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008425 sourcesToMute.push_back(source);
8426 }
Eric Laurente552edb2014-03-10 17:42:56 -07008427 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008428 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008429 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008430 }
8431
Eric Laurente552edb2014-03-10 17:42:56 -07008432}
8433
François Gaffieaaac0fd2018-11-22 17:56:39 +01008434void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8435 bool on,
8436 const sp<AudioOutputDescriptor>& outputDesc,
8437 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008438 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008439{
jiabin9a3361e2019-10-01 09:38:30 -07008440 if (deviceTypes.empty()) {
8441 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008442 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008443 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008444 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008445 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008446 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008447 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008448 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8449 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008450 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008451 }
8452 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008453 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8454 // ignored
8455 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008456 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008457 if (!outputDesc->isMuted(volumeSource)) {
8458 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008459 return;
8460 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008461 if (outputDesc->decMuteCount(volumeSource) == 0) {
8462 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008463 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008464 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008465 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008466 delayMs);
8467 }
8468 }
8469}
8470
François Gaffie53615e22015-03-19 09:24:12 +01008471bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8472{
François Gaffiec005e562018-11-06 15:04:49 +01008473 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008474 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8475 return true;
8476 }
8477
8478 // has known usage?
8479 switch (paa->usage) {
8480 case AUDIO_USAGE_UNKNOWN:
8481 case AUDIO_USAGE_MEDIA:
8482 case AUDIO_USAGE_VOICE_COMMUNICATION:
8483 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8484 case AUDIO_USAGE_ALARM:
8485 case AUDIO_USAGE_NOTIFICATION:
8486 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8487 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8488 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8489 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8490 case AUDIO_USAGE_NOTIFICATION_EVENT:
8491 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8492 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8493 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8494 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008495 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008496 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008497 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008498 case AUDIO_USAGE_EMERGENCY:
8499 case AUDIO_USAGE_SAFETY:
8500 case AUDIO_USAGE_VEHICLE_STATUS:
8501 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008502 break;
8503 default:
8504 return false;
8505 }
8506 return true;
8507}
8508
François Gaffie2110e042015-03-24 08:41:51 +01008509audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8510{
8511 return mEngine->getForceUse(usage);
8512}
8513
Eric Laurent96d1dda2022-03-14 17:14:19 +01008514bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008515 return isStateInCall(mEngine->getPhoneState());
8516}
8517
Eric Laurent96d1dda2022-03-14 17:14:19 +01008518bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008519 return is_state_in_call(state);
8520}
8521
Eric Laurentf9cccec2022-11-16 19:12:00 +01008522bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008523 audio_mode_t mode = mEngine->getPhoneState();
8524 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008525 || (mode == AUDIO_MODE_CALL_SCREEN)
8526 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008527}
8528
Eric Laurentf9cccec2022-11-16 19:12:00 +01008529bool AudioPolicyManager::isInCallOrScreening() const {
8530 audio_mode_t mode = mEngine->getPhoneState();
8531 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8532}
8533
Eric Laurentd60560a2015-04-10 11:31:20 -07008534void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8535{
8536 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008537 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008538 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008539 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008540 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008541 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008542 }
8543 }
8544
8545 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8546 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8547 bool release = false;
8548 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8549 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8550 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8551 source->ext.device.type == deviceDesc->type()) {
8552 release = true;
8553 }
8554 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008555 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008556 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8557 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8558 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008559 sink->ext.device.type == deviceDesc->type() &&
8560 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8561 || strncmp(sink->ext.device.address, address,
8562 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008563 release = true;
8564 }
8565 }
8566 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008567 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8568 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008569 }
8570 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008571
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008572 mInputs.clearSessionRoutesForDevice(deviceDesc);
8573
Francois Gaffie716e1432019-01-14 16:58:59 +01008574 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008575}
8576
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008577void AudioPolicyManager::modifySurroundFormats(
8578 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008579 std::unordered_set<audio_format_t> enforcedSurround(
8580 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008581 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008582 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008583 allSurround.insert(pair.first);
8584 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8585 }
Phil Burk09bc4612016-02-24 15:58:15 -08008586
8587 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8588 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008589 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008590 // This is the resulting set of formats depending on the surround mode:
8591 // 'all surround' = allSurround
8592 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8593 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8594 // 'manual surround' = mManualSurroundFormats
8595 // AUTO: formats v 'enforced surround'
8596 // ALWAYS: formats v 'all surround' v 'enforced surround'
8597 // NEVER: formats ^ 'non-surround'
8598 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008599
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008600 std::unordered_set<audio_format_t> formatSet;
8601 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8602 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008603 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008604 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008605 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008606 formatSet.insert(*formatIter);
8607 }
8608 }
8609 } else {
8610 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8611 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008612 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008613
jiabin81772902018-04-02 17:52:27 -07008614 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008615 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008616 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8617 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8618 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008619 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008620 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8621 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8622 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008623 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008624 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008625 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008626 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008627 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008628 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008629}
8630
jiabin06e4bab2019-07-29 10:13:34 -07008631void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8632 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008633 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8634 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8635
8636 // If NEVER, then remove support for channelMasks > stereo.
8637 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008638 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8639 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008640 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008641 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008642 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008643 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008644 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008645 }
8646 }
jiabin81772902018-04-02 17:52:27 -07008647 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8648 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8649 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008650 bool supports5dot1 = false;
8651 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008652 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008653 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8654 supports5dot1 = true;
8655 break;
8656 }
8657 }
8658 // If not then add 5.1 support.
8659 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008660 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008661 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008662 }
Phil Burk09bc4612016-02-24 15:58:15 -08008663 }
8664}
8665
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008666void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008667 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008668 const sp<IOProfile>& profile) {
8669 if (!profile->hasDynamicAudioProfile()) {
8670 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008671 }
François Gaffie112b0af2015-11-19 16:13:25 +01008672
jiabin12537fc2023-10-12 17:56:08 +00008673 audio_port_v7 devicePort;
8674 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008675
jiabin12537fc2023-10-12 17:56:08 +00008676 audio_port_v7 mixPort;
8677 profile->toAudioPort(&mixPort);
8678 mixPort.ext.mix.handle = ioHandle;
8679
8680 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8681 if (status != NO_ERROR) {
8682 ALOGE("%s failed to query the attributes of the mix port", __func__);
8683 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008684 }
jiabin12537fc2023-10-12 17:56:08 +00008685
8686 std::set<audio_format_t> supportedFormats;
8687 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8688 supportedFormats.insert(mixPort.audio_profiles[i].format);
8689 }
8690 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8691 mReportedFormatsMap[devDesc] = formats;
8692
8693 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8694 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8695 modifySurroundFormats(devDesc, &formats);
8696 size_t modifiedNumProfiles = 0;
8697 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8698 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8699 formats.end()) {
8700 // Skip the format that is not present after modifying surround formats.
8701 continue;
8702 }
8703 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8704 sizeof(struct audio_profile));
8705 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8706 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8707 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8708 modifySurroundChannelMasks(&channels);
8709 std::copy(channels.begin(), channels.end(),
8710 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8711 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8712 }
8713 mixPort.num_audio_profiles = modifiedNumProfiles;
8714 }
8715 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008716}
Eric Laurentd60560a2015-04-10 11:31:20 -07008717
Mikhail Naganovdc769682018-05-04 15:34:08 -07008718status_t AudioPolicyManager::installPatch(const char *caller,
8719 audio_patch_handle_t *patchHandle,
8720 AudioIODescriptorInterface *ioDescriptor,
8721 const struct audio_patch *patch,
8722 int delayMs)
8723{
8724 ssize_t index = mAudioPatches.indexOfKey(
8725 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8726 *patchHandle : ioDescriptor->getPatchHandle());
8727 sp<AudioPatch> patchDesc;
8728 status_t status = installPatch(
8729 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8730 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008731 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008732 }
8733 return status;
8734}
8735
8736status_t AudioPolicyManager::installPatch(const char *caller,
8737 ssize_t index,
8738 audio_patch_handle_t *patchHandle,
8739 const struct audio_patch *patch,
8740 int delayMs,
8741 uid_t uid,
8742 sp<AudioPatch> *patchDescPtr)
8743{
8744 sp<AudioPatch> patchDesc;
8745 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8746 if (index >= 0) {
8747 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008748 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008749 }
8750
8751 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8752 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8753 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8754 if (status == NO_ERROR) {
8755 if (index < 0) {
8756 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008757 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008758 } else {
8759 patchDesc->mPatch = *patch;
8760 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008761 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008762 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008763 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008764 }
8765 nextAudioPortGeneration();
8766 mpClientInterface->onAudioPatchListUpdate();
8767 }
8768 if (patchDescPtr) *patchDescPtr = patchDesc;
8769 return status;
8770}
8771
jiabinbce0c1d2020-10-05 11:20:18 -07008772bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8773{
8774 const TrackClientVector activeClients = output->getActiveClients();
8775 if (activeClients.empty()) {
8776 return true;
8777 }
8778 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8779 if (index < 0) {
8780 ALOGE("%s, no audio patch found while there are active clients on output %d",
8781 __func__, output->getId());
8782 return false;
8783 }
8784 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8785 DeviceVector routedDevices;
8786 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8787 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8788 patchDesc->mPatch.sinks[i].id);
8789 if (device == nullptr) {
8790 ALOGE("%s, no audio device found with id(%d)",
8791 __func__, patchDesc->mPatch.sinks[i].id);
8792 return false;
8793 }
8794 routedDevices.add(device);
8795 }
8796 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008797 if (client->isInvalid()) {
8798 // No need to take care about invalidated clients.
8799 continue;
8800 }
jiabinbce0c1d2020-10-05 11:20:18 -07008801 sp<DeviceDescriptor> preferredDevice =
8802 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8803 if (mEngine->getOutputDevicesForAttributes(
8804 client->attributes(), preferredDevice, false) == routedDevices) {
8805 return false;
8806 }
8807 }
8808 return true;
8809}
8810
8811sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008812 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008813 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8814 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008815{
8816 for (const auto& device : devices) {
8817 // TODO: This should be checking if the profile supports the device combo.
8818 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008819 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8820 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008821 return nullptr;
8822 }
8823 }
8824 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8825 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008826 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008827 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008828 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008829 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008830 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008831 return nullptr;
8832 }
jiabin14b50cc2023-12-13 19:01:52 +00008833 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8834 auto portConfig = desc->getConfig();
8835 for (const auto& device : devices) {
8836 device->setPreferredConfig(&portConfig);
8837 }
8838 }
jiabinbce0c1d2020-10-05 11:20:18 -07008839
8840 // Here is where the out_set_parameters() for card & device gets called
8841 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8842 const audio_devices_t deviceType = device->type();
8843 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008844 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008845 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8846 mpClientInterface->setParameters(output, String8(param));
8847 free(param);
8848 }
jiabin12537fc2023-10-12 17:56:08 +00008849 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008850 if (!profile->hasValidAudioProfile()) {
8851 ALOGW("%s() missing param", __func__);
8852 desc->close();
8853 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008854 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8855 // Reopen the output with the best audio profile picked by APM when the profile supports
8856 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008857 desc->close();
8858 output = AUDIO_IO_HANDLE_NONE;
8859 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8860 profile->pickAudioProfile(
8861 config.sample_rate, config.channel_mask, config.format);
8862 config.offload_info.sample_rate = config.sample_rate;
8863 config.offload_info.channel_mask = config.channel_mask;
8864 config.offload_info.format = config.format;
8865
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008866 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
8867 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008868 if (status != NO_ERROR) {
8869 return nullptr;
8870 }
8871 }
8872
8873 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008874 setOutputDevices(__func__, desc,
8875 devices,
8876 true,
8877 0,
8878 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008879 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8880 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8881
jiabinbce0c1d2020-10-05 11:20:18 -07008882 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8883 sp<AudioPolicyMix> policyMix;
8884 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8885 policyMix->setOutput(desc);
8886 desc->mPolicyMix = policyMix;
8887 } else {
8888 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008889 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008890 }
8891
baek.kim -61c20122022-07-27 10:05:32 +00008892 } else if (hasPrimaryOutput() && speaker != nullptr
8893 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008894 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8895 // no duplicated output for:
8896 // - direct outputs
8897 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008898 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008899 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8900
8901 //TODO: configure audio effect output stage here
8902
8903 // open a duplicating output thread for the new output and the primary output
8904 sp<SwAudioOutputDescriptor> dupOutputDesc =
8905 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8906 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8907 if (status == NO_ERROR) {
8908 // add duplicated output descriptor
8909 addOutput(duplicatedOutput, dupOutputDesc);
8910 } else {
8911 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8912 mPrimaryOutput->mIoHandle, output);
8913 desc->close();
8914 removeOutput(output);
8915 nextAudioPortGeneration();
8916 return nullptr;
8917 }
8918 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008919 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8920 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8921 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008922 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008923 }
jiabinbce0c1d2020-10-05 11:20:18 -07008924 return desc;
8925}
8926
jiabinf1c73972022-04-14 16:28:52 -07008927status_t AudioPolicyManager::getDevicesForAttributes(
8928 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8929 // Devices are determined in the following precedence:
8930 //
8931 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8932 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8933 //
8934 // If no such dynamic policy then
8935 // 2) Devices containing an active client using setPreferredDevice
8936 // with same strategy as the attributes.
8937 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8938 //
8939 // If no corresponding active client with setPreferredDevice then
8940 // 3) Devices associated with the strategy determined by the attributes
8941 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8942 //
8943 // See related getOutputForAttrInt().
8944
8945 // check dynamic policies but only for primary descriptors (secondary not used for audible
8946 // audio routing, only used for duplication for playback capture)
8947 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008948 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008949 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008950 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8951 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8952 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008953 if (status != OK) {
8954 return status;
8955 }
8956
8957 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8958 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8959 // as they are unaffected by device/stream volume
8960 // (per SwAudioOutputDescriptor::isFixedVolume()).
8961 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8962 ) {
8963 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8964 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8965 devices.add(deviceDesc);
8966 } else {
8967 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8968 // which selects setPreferredDevice if active. This means forVolume call
8969 // will take an active setPreferredDevice, if such exists.
8970
8971 devices = mEngine->getOutputDevicesForAttributes(
8972 attr, nullptr /* preferredDevice */, false /* fromCache */);
8973 }
8974
8975 if (forVolume) {
8976 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8977 // for single volume control in AudioService (such relationship should exist if
8978 // SPEAKER_SAFE is present).
8979 //
8980 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8981 DeviceVector speakerSafeDevices =
8982 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8983 if (!speakerSafeDevices.isEmpty()) {
8984 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8985 devices.remove(speakerSafeDevices);
8986 }
8987 }
8988
8989 return NO_ERROR;
8990}
8991
8992status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8993 AudioProfileVector& audioProfiles,
8994 uint32_t flags,
8995 bool isInput) {
8996 for (const auto& hwModule : mHwModules) {
8997 // the MSD module checks for different conditions
8998 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8999 continue;
9000 }
9001 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9002 : hwModule->getOutputProfiles();
9003 for (const auto& profile : ioProfiles) {
9004 if (!profile->areAllDevicesSupported(devices) ||
9005 !profile->isCompatibleProfileForFlags(
9006 flags, false /*exactMatchRequiredForInputFlags*/)) {
9007 continue;
9008 }
9009 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9010 }
9011 }
9012
9013 if (!isInput) {
9014 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9015 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9016 if (msdModule != nullptr) {
9017 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9018 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9019 for (const auto &profile: msdModule->getOutputProfiles()) {
9020 if (!profile->asAudioPort()->isDirectOutput()) {
9021 continue;
9022 }
9023 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9024 }
9025 } else {
9026 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9027 }
9028 }
9029 }
9030
9031 return NO_ERROR;
9032}
9033
jiabin3ff8d7d2022-12-13 06:27:44 +00009034sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9035 const audio_config_t *config,
9036 audio_output_flags_t flags,
9037 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009038 closeOutput(outputDesc->mIoHandle);
9039 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9040 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9041 if (preferredOutput == nullptr) {
9042 ALOGE("%s failed to reopen output device=%d, caller=%s",
9043 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009044 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009045 return preferredOutput;
9046}
9047
9048void AudioPolicyManager::reopenOutputsWithDevices(
9049 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9050 for (const auto& [output, devices] : outputsToReopen) {
9051 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9052 closeOutput(output);
9053 openOutputWithProfileAndDevice(desc->mProfile, devices);
9054 }
jiabina84c3d32022-12-02 18:59:55 +00009055}
9056
jiabinc44b3462022-12-08 12:52:31 -08009057PortHandleVector AudioPolicyManager::getClientsForStream(
9058 audio_stream_type_t streamType) const {
9059 PortHandleVector clients;
9060 for (size_t i = 0; i < mOutputs.size(); ++i) {
9061 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9062 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9063 }
9064 return clients;
9065}
9066
9067void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9068 PortHandleVector clients;
9069 for (auto stream : streams) {
9070 PortHandleVector clientsForStream = getClientsForStream(stream);
9071 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9072 }
9073 mpClientInterface->invalidateTracks(clients);
9074}
9075
jiabin220eea12024-05-17 17:55:20 +00009076void AudioPolicyManager::updateClientsInternalMute(
9077 const sp<android::SwAudioOutputDescriptor> &desc) {
9078 if (!desc->isBitPerfect() ||
9079 !com::android::media::audioserver::
9080 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9081 // This is only used for bit perfect output now.
9082 return;
9083 }
9084 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9085 bool bitPerfectClientInternalMute = false;
9086 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9087 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9088 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9089 bitPerfectClient = client;
9090 continue;
9091 }
9092 bool muted = false;
9093 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9094 // System sound is muted.
9095 muted = true;
9096 } else {
9097 bitPerfectClientInternalMute = true;
9098 }
9099 if (client->setInternalMute(muted)) {
9100 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9101 if (!result.ok()) {
9102 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9103 continue;
9104 }
9105 media::TrackInternalMuteInfo info;
9106 info.portId = result.value();
9107 info.muted = client->getInternalMute();
9108 clientsInternalMute.push_back(std::move(info));
9109 }
9110 }
9111 if (bitPerfectClient != nullptr &&
9112 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9113 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9114 if (result.ok()) {
9115 media::TrackInternalMuteInfo info;
9116 info.portId = result.value();
9117 info.muted = bitPerfectClient->getInternalMute();
9118 clientsInternalMute.push_back(std::move(info));
9119 } else {
9120 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9121 __func__, bitPerfectClient->portId());
9122 }
9123 }
9124 if (!clientsInternalMute.empty()) {
9125 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9126 status != NO_ERROR) {
9127 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9128 }
9129 }
9130}
9131
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009132} // namespace android