blob: f36d8d57ad1f5d868057970817aa0ea34768bcc2 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
131 status != OK) {
132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganov3754b642024-04-17 18:31:04 +0000222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530377 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700378 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } // end if is output device
380
Eric Laurente552edb2014-03-10 17:42:56 -0700381 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700382 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700384 switch (state)
385 {
386 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700390 return INVALID_OPERATION;
391 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700392
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530393 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (mAvailableInputDevices.add(device) < 0) {
396 return NO_MEMORY;
397 }
398
François Gaffie44481e72016-04-20 07:49:57 +0200399 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
400 // parameters on newly connected devices (instead of opening the inputs...)
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000401 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700402 // Propagate device availability to Engine
403 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200404
Eric Laurent0dd51852019-04-19 18:18:58 -0700405 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700406 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
407
Eric Laurent0dd51852019-04-19 18:18:58 -0700408 mAvailableInputDevices.remove(device);
409
jiabinc0048632023-04-27 22:04:31 +0000410 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100411
412 mHwModules.cleanUpForDevice(device);
413
Eric Laurentd4692962014-05-05 18:13:44 -0700414 return INVALID_OPERATION;
415 }
416
Eric Laurentd4692962014-05-05 18:13:44 -0700417 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700418
419 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700420 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700421 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return INVALID_OPERATION;
424 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700425
François Gaffie11d30102018-11-02 16:09:09 +0100426 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700427
jiabinc0048632023-04-27 22:04:31 +0000428 // Notify the HAL to prepare to disconnect device
429 broadcastDeviceConnectionState(
430 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700431
François Gaffie11d30102018-11-02 16:09:09 +0100432 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700433
434 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100435
jiabinc0048632023-04-27 22:04:31 +0000436 // Set Disconnect to HALs
437 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
438
Kriti Dangef6be8f2020-11-05 11:58:19 +0100439 // remove device from mReportedFormatsMap cache
440 mReportedFormatsMap.erase(device);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700441
442 // Propagate device availability to Engine
443 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700444 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700445
446 default:
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449 }
450
Eric Laurent0dd51852019-04-19 18:18:58 -0700451 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700452 // As the input device list can impact the output device selection, update
453 // getDeviceForStrategy() cache
454 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700455
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100456 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200457 // Reconnect Audio Source
458 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
459 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
460 checkAudioSourceForAttributes(attributes);
461 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700462 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100463 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700464 }
465
Eric Laurentb52c1522014-05-20 11:27:36 -0700466 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530467 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700468 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700469 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700470
François Gaffie11d30102018-11-02 16:09:09 +0100471 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700472 return BAD_VALUE;
473}
474
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100475status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
476 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800477 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000478 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
479 devDescr->setName(device_name);
480 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100481}
482
Eric Laurent736a1022019-03-27 18:28:46 -0700483void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
484 audio_policy_dev_state_t state) {
485
486 // the Engine does not have to know about remote submix devices used by dynamic audio policies
487 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
488 return;
489 }
490 mEngine->setDeviceConnectionState(device, state);
491}
492
493
Eric Laurente0720872014-03-11 09:30:41 -0700494audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100495 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700496{
Eric Laurent634b7142016-04-20 13:48:02 -0700497 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800498 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
499 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700500 (strlen(device_address) != 0)/*matchAddress*/);
501
502 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100503 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700504 device, device_address);
505 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
506 }
François Gaffie53615e22015-03-19 09:24:12 +0100507
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 DeviceVector *deviceVector;
509
Eric Laurente552edb2014-03-10 17:42:56 -0700510 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700511 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700512 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700513 deviceVector = &mAvailableInputDevices;
514 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100515 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700516 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700517 }
Eric Laurent634b7142016-04-20 13:48:02 -0700518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 return (deviceVector->getDevice(
520 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800522}
523
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
525 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 const char *device_name,
527 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
530 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800532 // connect/disconnect only 1 device at a time
533 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
534
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800535 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700536 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538 // Nothing to do: device is not connected
539 return NO_ERROR;
540 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800542
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700543 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 // configure codecs.
545 // Handle two specific cases by sending a set parameter to
546 // configure A2DP codecs. No need to toggle device state.
547 // Case 1: A2DP active device switches from primary to primary
548 // module
549 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100550 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700551 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800552 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
553 if (availablePrimaryOutputDevices().contains(devDesc) &&
554 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100555 bool isA2dp = audio_is_a2dp_out_device(device);
556 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
557 : String8(AudioParameter::keyReconfigLeSupported);
558 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800559 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100560 int isReconfigSupported;
561 repliedParameters.getInt(supportKey, isReconfigSupported);
562 if (isReconfigSupported) {
563 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
564 : String8(AudioParameter::keyReconfigLe);
565 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 param.add(key, String8("true"));
567 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
568 devDesc->setEncodedFormat(encodedFormat);
569 return NO_ERROR;
570 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700571 }
572 }
cnx421bd2dcc42020-07-11 14:58:44 +0800573 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000574 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800575 for (size_t i = 0; i < mOutputs.size(); i++) {
576 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000577 // mute media strategies to avoid sending the music tail into
578 // the earpiece or headset.
579 if (desc->isStrategyActive(musicStrategy)) {
580 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
581 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
582 tempRecommendedMuteDuration : desc->latency() * 4;
583 if (muteWaitMs < tempMuteDurationMs) {
584 muteWaitMs = tempMuteDurationMs;
585 }
586 }
cnx421bd2dcc42020-07-11 14:58:44 +0800587 setStrategyMute(musicStrategy, true, desc);
588 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
589 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
590 nullptr, true /*fromCache*/).types());
591 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000592 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
593 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
594 // happens after the actual device switch.
595 if (muteWaitMs > 0) {
596 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
597 usleep(muteWaitMs * 1000);
598 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800599 // Toggle the device state: UNAVAILABLE -> AVAILABLE
600 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100601 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800602 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800603 device_address, device_name,
604 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800605 if (status != NO_ERROR) {
606 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
607 status);
608 return status;
609 }
610
611 status = setDeviceConnectionState(device,
612 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800613 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800614 if (status != NO_ERROR) {
615 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
616 status);
617 return status;
618 }
619
620 return NO_ERROR;
621}
622
Pattydd807582021-11-04 21:01:03 +0800623status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
624 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800625{
Pattydd807582021-11-04 21:01:03 +0800626 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800627 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800628 std::unordered_set<audio_format_t> formatSet;
629 sp<HwModule> primaryModule =
630 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700631 if (primaryModule == nullptr) {
632 ALOGE("%s() unable to get primary module", __func__);
633 return NO_INIT;
634 }
Pattydd807582021-11-04 21:01:03 +0800635
636 DeviceTypeSet audioDeviceSet;
637
638 switch(device) {
639 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
640 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
641 break;
642 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800643 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
644 break;
645 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
646 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800647 break;
648 default:
649 ALOGE("%s() device type 0x%08x not supported", __func__, device);
650 return BAD_VALUE;
651 }
652
jiabin9a3361e2019-10-01 09:38:30 -0700653 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800654 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800655 for (const auto& device : declaredDevices) {
656 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800657 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800658 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800659 return status;
660}
661
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
663{
664 DeviceVector rxSinkdevices{};
665 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
666 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
667 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
668 auto rxSinkDevice = rxSinkdevices.itemAt(0);
669 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
670 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
671 // retrieve Rx Source device descriptor
672 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
673 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
674
675 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
676 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
677 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
678 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
679 return DeviceVector(rxSinkDevice);
680 }
681 }
682 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
683 // the device returned is not necessarily reachable via this output
684 // (filter later by setOutputDevices())
685 return getNewOutputDevices(mPrimaryOutput, fromCache);
686}
687
688status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
689{
François Gaffiedb1755b2023-09-01 11:50:35 +0200690 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100691 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
692 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
693 }
694 return INVALID_OPERATION;
695}
696
697status_t AudioPolicyManager::updateCallRoutingInternal(
698 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700699{
700 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100701 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700702 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200703 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700704 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100705 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700706 }
François Gaffie11d30102018-11-02 16:09:09 +0100707
Francois Gaffie716e1432019-01-14 16:58:59 +0100708 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100709 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200710
711 disconnectTelephonyAudioSource(mCallRxSourceClient);
712 disconnectTelephonyAudioSource(mCallTxSourceClient);
713
714 if (rxDevices.isEmpty()) {
715 ALOGW("%s() no selected output device", __func__);
716 return INVALID_OPERATION;
717 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000718 if (txSourceDevice == nullptr) {
719 ALOGE("%s() selected input device not available", __func__);
720 return INVALID_OPERATION;
721 }
François Gaffiec005e562018-11-06 15:04:49 +0100722
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100723 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100724 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700725
François Gaffie9eb18552018-11-05 10:33:26 +0100726 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700727 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100728 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700729 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100730 // retrieve Rx Source and Tx Sink device descriptors
731 sp<DeviceDescriptor> rxSourceDevice =
732 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
733 String8(),
734 AUDIO_FORMAT_DEFAULT);
735 sp<DeviceDescriptor> txSinkDevice =
736 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
737 String8(),
738 AUDIO_FORMAT_DEFAULT);
739
740 // RX and TX Telephony device are declared by Primary Audio HAL
741 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
742 (telephonyRxModule->getHalVersionMajor() >= 3)) {
743 if (rxSourceDevice == 0 || txSinkDevice == 0) {
744 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100745 ALOGE("%s() no telephony Tx and/or RX device", __func__);
746 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100747 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100748 // createAudioPatchInternal now supports both HW / SW bridging
749 createRxPatch = true;
750 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100751 } else {
752 // If the RX device is on the primary HW module, then use legacy routing method for
753 // voice calls via setOutputDevice() on primary output.
754 // Otherwise, create two audio patches for TX and RX path.
755 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
756 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700757 // If the TX device is also on the primary HW module, setOutputDevice() will take care
758 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100759 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
760 (txSinkDevice != 0);
761 }
762 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
763 // Otherwise, create two audio patches for TX and RX path.
764 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200765 if (!hasPrimaryOutput()) {
766 ALOGW("%s() no primary output available", __func__);
767 return INVALID_OPERATION;
768 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530769 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700770 } else { // create RX path audio patch
David Li48b6a832024-07-01 13:14:10 +0000771 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800772 // If the TX device is on the primary HW module but RX device is
773 // on other HW module, SinkMetaData of telephony input should handle it
774 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700775 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700776 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100777 // terminate active capture if on the same HW module as the call TX source device
778 // FIXME: would be better to refine to only inputs whose profile connects to the
779 // call TX device but this information is not in the audio patch and logic here must be
780 // symmetric to the one in startInput()
781 for (const auto& activeDesc : mInputs.getActiveInputs()) {
782 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
783 closeActiveClients(activeDesc);
784 }
785 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200786 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800787 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100788 if (waitMs != nullptr) {
789 *waitMs = muteWaitMs;
790 }
791 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800792}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700793
Mikhail Naganov100f0122018-11-29 11:22:16 -0800794bool AudioPolicyManager::isDeviceOfModule(
795 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
796 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
797 if (module != 0) {
798 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
799 .indexOf(devDesc) != NAME_NOT_FOUND
800 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
801 .indexOf(devDesc) != NAME_NOT_FOUND;
802 }
803 return false;
804}
805
David Li48b6a832024-07-01 13:14:10 +0000806void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200807{
Francois Gaffie601801d2021-06-22 13:27:39 +0200808 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200809 const struct audio_port_config source = {
810 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
811 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
812 };
813 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100814
815 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent963dbcc2024-06-20 12:34:15 +0000816 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Li48b6a832024-07-01 13:14:10 +0000817 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100818 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
819 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200820 ALOGE_IF(mCallRxSourceClient == nullptr,
821 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200822}
823
Francois Gaffie601801d2021-06-22 13:27:39 +0200824void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200825{
Francois Gaffie601801d2021-06-22 13:27:39 +0200826 if (clientDesc == nullptr) {
827 return;
828 }
829 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
830 "%s error stopping audio source", __func__);
831 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200832}
833
834void AudioPolicyManager::connectTelephonyTxAudioSource(
835 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
836 uint32_t delayMs)
837{
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200839 if (srcDevice == nullptr || sinkDevice == nullptr) {
840 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
841 return;
842 }
843 PatchBuilder patchBuilder;
844 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
845 ALOGV("%s between source %s and sink %s", __func__,
846 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200847 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200848 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
849
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200850 struct audio_port_config source = {};
851 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100852 mCallTxSourceClient = new SourceClientDescriptor(
853 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurent963dbcc2024-06-20 12:34:15 +0000854 mCommunnicationStrategy, toVolumeSource(aa), true,
855 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100856 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
857
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200858 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
859 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200860 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
861 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200862 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
863 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200864 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200865 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200866}
867
Eric Laurente0720872014-03-11 09:30:41 -0700868void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700869{
870 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100871 // store previous phone state for management of sonification strategy below
872 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100873 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100874
875 if (mEngine->setPhoneState(state) != NO_ERROR) {
876 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700877 return;
878 }
François Gaffie2110e042015-03-24 08:41:51 +0100879 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700880 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700881 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700882 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800883 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700884 }
885
François Gaffie2110e042015-03-24 08:41:51 +0100886 /**
887 * Switching to or from incall state or switching between telephony and VoIP lead to force
888 * routing command.
889 */
Eric Laurent74b71512019-11-06 17:21:57 -0800890 bool force = ((isStateInCall(oldState) != isStateInCall(state))
891 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700892
893 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700894 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700895
Eric Laurente552edb2014-03-10 17:42:56 -0700896 int delayMs = 0;
897 if (isStateInCall(state)) {
898 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100899 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
900 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700901 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700902 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700903 // mute media and sonification strategies and delay device switch by the largest
904 // latency of any output where either strategy is active.
905 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100906 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
907 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
908 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700909 (delayMs < (int)desc->latency()*2)) {
910 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700911 }
François Gaffiec005e562018-11-06 15:04:49 +0100912 setStrategyMute(musicStrategy, true, desc);
913 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
914 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
915 nullptr, true /*fromCache*/).types());
916 setStrategyMute(sonificationStrategy, true, desc);
917 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
918 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
919 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700920 }
921 }
922
François Gaffiedb1755b2023-09-01 11:50:35 +0200923 if (state == AUDIO_MODE_IN_CALL) {
924 (void)updateCallRouting(false /*fromCache*/, delayMs);
925 } else {
926 if (oldState == AUDIO_MODE_IN_CALL) {
927 disconnectTelephonyAudioSource(mCallRxSourceClient);
928 disconnectTelephonyAudioSource(mCallTxSourceClient);
929 }
930 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100931 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
932 // force routing command to audio hardware when ending call
933 // even if no device change is needed
934 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
935 rxDevices = mPrimaryOutput->devices();
936 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530937 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700938 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700939 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700940
jiabin3ff8d7d2022-12-13 06:27:44 +0000941 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700942 // reevaluate routing on all outputs in case tracks have been started during the call
943 for (size_t i = 0; i < mOutputs.size(); i++) {
944 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100945 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000946 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
947 && desc->mPreferredAttrInfo != nullptr) {
948 // If the output is using preferred mixer attributes and the audio mode is not normal,
949 // the output need to reopen with default configuration.
950 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
951 continue;
952 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200953 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
954 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530955 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200956 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700957 }
958 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000959 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700960
Eric Laurent96d1dda2022-03-14 17:14:19 +0100961 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
962
Eric Laurente552edb2014-03-10 17:42:56 -0700963 if (isStateInCall(state)) {
964 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700965 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800966 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
968
969 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100970 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
971 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700972}
973
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700974audio_mode_t AudioPolicyManager::getPhoneState() {
975 return mEngine->getPhoneState();
976}
977
Eric Laurente0720872014-03-11 09:30:41 -0700978void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100979 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700980{
François Gaffie2110e042015-03-24 08:41:51 +0100981 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700982 if (config == mEngine->getForceUse(usage)) {
983 return;
984 }
Eric Laurente552edb2014-03-10 17:42:56 -0700985
François Gaffie2110e042015-03-24 08:41:51 +0100986 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
987 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
988 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700989 }
François Gaffie2110e042015-03-24 08:41:51 +0100990 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
991 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
992 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700993
994 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700995 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800996
Eric Laurent22fcda22019-05-17 16:28:47 -0700997 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
998 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800999 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001000 }
1001
Eric Laurentdc462862016-07-19 12:29:53 -07001002 //FIXME: workaround for truncated touch sounds
1003 // to be removed when the problem is handled by system UI
1004 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001005 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1006 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1007 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001008
1009 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001010 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001011}
1012
Eric Laurente0720872014-03-11 09:30:41 -07001013void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001014{
1015 ALOGV("setSystemProperty() property %s, value %s", property, value);
1016}
1017
Dorin Drimusecc9f422022-03-09 17:57:40 +01001018// Find an MSD output profile compatible with the parameters passed.
1019// When "directOnly" is set, restrict search to profiles for direct outputs.
1020sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1021 const DeviceVector& devices,
1022 uint32_t samplingRate,
1023 audio_format_t format,
1024 audio_channel_mask_t channelMask,
1025 audio_output_flags_t flags,
1026 bool directOnly)
1027{
1028 flags = getRelevantFlags(flags, directOnly);
1029
1030 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1031 if (msdModule != nullptr) {
1032 // for the msd module check if there are patches to the output devices
1033 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1034 HwModuleCollection modules;
1035 modules.add(msdModule);
1036 return searchCompatibleProfileHwModules(
1037 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1038 flags, directOnly);
1039 }
1040 }
1041 return nullptr;
1042}
1043
Michael Chana94fbb22018-04-24 14:31:19 +10001044// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1045// search to profiles for direct outputs.
1046sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001047 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001048 uint32_t samplingRate,
1049 audio_format_t format,
1050 audio_channel_mask_t channelMask,
1051 audio_output_flags_t flags,
1052 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001053{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001054 flags = getRelevantFlags(flags, directOnly);
1055
1056 return searchCompatibleProfileHwModules(
1057 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1058}
1059
1060audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1061 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001062 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 // only retain flags that will drive the direct output profile selection
1064 // if explicitly requested
1065 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001066 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1068 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001069 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001070 return flags;
1071}
Eric Laurent861a6282015-05-18 15:40:16 -07001072
Dorin Drimusecc9f422022-03-09 17:57:40 +01001073sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1074 const HwModuleCollection& hwModules,
1075 const DeviceVector& devices,
1076 uint32_t samplingRate,
1077 audio_format_t format,
1078 audio_channel_mask_t channelMask,
1079 audio_output_flags_t flags,
1080 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001081 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001082 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001083 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001084 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001085 samplingRate, NULL /*updatedSamplingRate*/,
1086 format, NULL /*updatedFormat*/,
1087 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001088 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001089 continue;
1090 }
1091 // reject profiles not corresponding to a device currently available
1092 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1093 continue;
1094 }
1095 // reject profiles if connected device does not support codec
1096 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1097 continue;
1098 }
1099 if (!directOnly) {
1100 return curProfile;
1101 }
1102
1103 // when searching for direct outputs, if several profiles are compatible, give priority
1104 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001105 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001106 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001107 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001108 }
1109 profile = curProfile;
1110 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1111 break;
1112 }
Eric Laurente552edb2014-03-10 17:42:56 -07001113 }
1114 }
Eric Laurent861a6282015-05-18 15:40:16 -07001115 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001116}
1117
Eric Laurentfa0f6742021-08-17 18:39:44 +02001118sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001119 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001120{
1121 for (const auto& hwModule : mHwModules) {
1122 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001123 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001124 continue;
1125 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001126 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001127 // reject profiles not corresponding to a device currently available
1128 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1129 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1130 continue;
1131 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001132 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1133 != devices.size()) {
1134 continue;
1135 }
1136 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001137 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1138 return curProfile;
1139 }
1140 }
1141 return nullptr;
1142}
1143
Eric Laurentf4e63452017-11-06 19:31:46 +00001144audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001145{
François Gaffiec005e562018-11-06 15:04:49 +01001146 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001147
1148 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1149 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1150 // format, flags, etc. This may result in some discrepancy for functions that utilize
1151 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1152 // and AudioSystem::getOutputSamplingRate().
1153
François Gaffie11d30102018-11-02 16:09:09 +01001154 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001155 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1156 if (stream == AUDIO_STREAM_MUSIC &&
1157 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1158 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1159 }
1160 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001161
François Gaffie11d30102018-11-02 16:09:09 +01001162 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1163 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001164 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001165}
1166
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001167status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1168 const audio_attributes_t *srcAttr,
1169 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001170{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001171 if (srcAttr != NULL) {
1172 if (!isValidAttributes(srcAttr)) {
1173 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1174 __func__,
1175 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1176 srcAttr->tags);
1177 return BAD_VALUE;
1178 }
1179 *dstAttr = *srcAttr;
1180 } else {
1181 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1182 ALOGE("%s: invalid stream type", __func__);
1183 return BAD_VALUE;
1184 }
François Gaffiec005e562018-11-06 15:04:49 +01001185 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001186 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001187
1188 // Only honor audibility enforced when required. The client will be
1189 // forced to reconnect if the forced usage changes.
1190 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001191 dstAttr->flags = static_cast<audio_flags_mask_t>(
1192 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001193 }
1194
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001195 return NO_ERROR;
1196}
1197
Kevin Rocard153f92d2018-12-18 18:33:28 -08001198status_t AudioPolicyManager::getOutputForAttrInt(
1199 audio_attributes_t *resultAttr,
1200 audio_io_handle_t *output,
1201 audio_session_t session,
1202 const audio_attributes_t *attr,
1203 audio_stream_type_t *stream,
1204 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001205 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001206 audio_output_flags_t *flags,
1207 audio_port_handle_t *selectedDeviceId,
1208 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001209 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001210 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001211 bool *isSpatialized,
1212 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001213{
François Gaffiec005e562018-11-06 15:04:49 +01001214 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001215 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001216 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001217 const sp<DeviceDescriptor> requestedDevice =
1218 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1219
Eric Laurent8a1095a2019-11-08 14:44:16 -08001220 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001221 *isSpatialized = false;
1222
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001223 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1224 if (status != NO_ERROR) {
1225 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001226 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001227 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001228 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001229 }
François Gaffiec005e562018-11-06 15:04:49 +01001230 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001231
François Gaffiec005e562018-11-06 15:04:49 +01001232 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1233 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001234
Oscar Azucena873d10f2023-01-12 18:34:42 -08001235 bool usePrimaryOutputFromPolicyMixes = false;
1236
Kevin Rocard153f92d2018-12-18 18:33:28 -08001237 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1238 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1239 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001240 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001241 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1242 .channel_mask = config->channel_mask,
1243 .format = config->format,
1244 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001245 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001246 mAvailableOutputDevices, requestedDevice, primaryMix,
1247 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001248 if (status != OK) {
1249 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001250 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001251
Kevin Rocard153f92d2018-12-18 18:33:28 -08001252 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001253 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1254 && !audio_is_linear_pcm(config->format)) {
1255 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001256 return BAD_VALUE;
1257 }
1258 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001259 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001260 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1261 primaryMix->mDeviceAddress,
1262 AUDIO_FORMAT_DEFAULT);
1263 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001264 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001265 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1266 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001267 // if a direct output can be opened to deliver the track's multi-channel content to the
1268 // output rather than being downmixed by the primary output, then use this direct
1269 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1270 // mix.
1271 bool tryDirectForChannelMask = policyDesc != nullptr
1272 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1273 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001274 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001275 audio_io_handle_t newOutput;
1276 status = openDirectOutput(
1277 *stream, session, config,
1278 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001279 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001280 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001281 policyDesc = mOutputs.valueFor(newOutput);
1282 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001283 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001284 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001285 policyDesc = nullptr;
1286 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001287 }
1288 if (policyDesc != nullptr) {
1289 policyDesc->mPolicyMix = primaryMix;
1290 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001291 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1292 : AUDIO_PORT_HANDLE_NONE;
1293 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1294 // Remove direct flag as it is not on a direct output.
1295 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1296 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001297
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001298 ALOGV("getOutputForAttr() returns output %d", *output);
1299 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1300 *outputType = API_OUT_MIX_PLAYBACK;
1301 } else {
1302 *outputType = API_OUTPUT_LEGACY;
1303 }
1304 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001305 } else {
1306 if (policyMixDevice != nullptr) {
1307 ALOGE("%s, try to use primary mix but no output found", __func__);
1308 return INVALID_OPERATION;
1309 }
1310 // Fallback to default engine selection as the selected primary mix device is not
1311 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001312 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001313 }
François Gaffiec005e562018-11-06 15:04:49 +01001314 // Virtual sources must always be dynamicaly or explicitly routed
1315 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1316 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1317 return BAD_VALUE;
1318 }
1319 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1320 // in order to let the choice of the order to future vendor engine
1321 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001322
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001323 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001324 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001325 }
1326
Nadav Barb2f18162018-07-18 13:01:53 +03001327 // Set incall music only if device was explicitly set, and fallback to the device which is
1328 // chosen by the engine if not.
1329 // FIXME: provide a more generic approach which is not device specific and move this back
1330 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001331 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001332 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001333 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001334 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001335 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001336 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001337 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001338 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001339 }
1340 }
1341
François Gaffiec005e562018-11-06 15:04:49 +01001342 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1343 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1344 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001345
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001347 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001348 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001349 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001350 ALOGV("%s() Using MSD devices %s instead of devices %s",
1351 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001352 } else {
1353 *output = AUDIO_IO_HANDLE_NONE;
1354 }
1355 }
1356 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001357 sp<PreferredMixerAttributesInfo> info = nullptr;
1358 if (outputDevices.size() == 1) {
1359 info = getPreferredMixerAttributesInfo(
1360 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001361 mEngine->getProductStrategyForAttributes(*resultAttr),
1362 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001363 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1364 // and it is currently active.
1365 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001366 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001367 info = nullptr;
1368 }
jiabin220eea12024-05-17 17:55:20 +00001369 if (com::android::media::audioserver::
1370 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1371 if (info != nullptr && info->getUid() == uid &&
1372 info->configMatches(*config) &&
1373 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1374 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1375 [this, &outputDevices](audio_usage_t usage) {
1376 return mOutputs.isUsageActiveOnDevice(
1377 usage, outputDevices[0]); }))) {
1378 // Bit-perfect request is not allowed when the phone mode is not normal or
1379 // there is any higher priority user case active.
1380 return INVALID_OPERATION;
1381 }
1382 }
jiabina84c3d32022-12-02 18:59:55 +00001383 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001384 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001385 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001386 // The client will be active if the client is currently preferred mixer owner and the
1387 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001388 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001389 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001390 && info->getUid() == uid
1391 && *output != AUDIO_IO_HANDLE_NONE
1392 // When bit-perfect output is selected for the preferred mixer attributes owner,
1393 // only need to consider the config matches.
1394 && mOutputs.valueFor(*output)->isConfigurationMatched(
1395 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001396
1397 if (*isBitPerfect) {
1398 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1399 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001400 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001401 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001402 AudioProfileVector profiles;
1403 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1404 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001405 const auto channels = profiles[0]->getChannels();
1406 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1407 config->channel_mask = *channels.begin();
1408 }
1409 const auto sampleRates = profiles[0]->getSampleRates();
1410 if (!sampleRates.empty() &&
1411 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1412 config->sample_rate = *sampleRates.begin();
1413 }
jiabinf1c73972022-04-14 16:28:52 -07001414 config->format = profiles[0]->getFormat();
1415 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001416 return INVALID_OPERATION;
1417 }
Paul McLeanaa981192015-03-21 09:55:15 -07001418
François Gaffiec005e562018-11-06 15:04:49 +01001419 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001420 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001421 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001422 *selectedDeviceId = outputDevice->getId();
1423 break;
1424 }
1425 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001426
Eric Laurent8a1095a2019-11-08 14:44:16 -08001427 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1428 *outputType = API_OUTPUT_TELEPHONY_TX;
1429 } else {
1430 *outputType = API_OUTPUT_LEGACY;
1431 }
1432
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001433 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1434
1435 return NO_ERROR;
1436}
1437
1438status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1439 audio_io_handle_t *output,
1440 audio_session_t session,
1441 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001442 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001443 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001444 audio_output_flags_t *flags,
1445 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001446 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001447 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001448 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001449 bool *isSpatialized,
1450 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001451{
1452 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1453 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1454 return INVALID_OPERATION;
1455 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001456 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001457 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001458 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001459 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001460 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001461 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001462 const sp<DeviceDescriptor> requestedDevice =
1463 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1464
1465 // Prevent from storing invalid requested device id in clients
1466 const audio_port_handle_t sanitizedRequestedPortId =
1467 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1468 *selectedDeviceId = sanitizedRequestedPortId;
1469
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001470 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001471 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001472 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1473 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001474 if (status != NO_ERROR) {
1475 return status;
1476 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001477 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001478 if (secondaryOutputs != nullptr) {
1479 for (auto &secondaryMix : secondaryMixes) {
1480 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1481 if (outputDesc != nullptr &&
1482 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1483 secondaryOutputs->push_back(outputDesc->mIoHandle);
1484 weakSecondaryOutputDescs.push_back(outputDesc);
1485 }
1486 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001487 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001488
Eric Laurent8fc147b2018-07-22 19:13:55 -07001489 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001490 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001491 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001492 };
jiabin4ef93452019-09-10 14:29:54 -07001493 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001494
Eric Laurentc209fe42020-06-05 18:11:23 -07001495 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001496 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001497 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001498 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001499 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001500 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001501 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001502 std::move(weakSecondaryOutputDescs),
1503 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001504 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001505
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001506 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1507 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001508
Eric Laurente83b55d2014-11-14 10:06:21 -08001509 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001510}
1511
Eric Laurentc529cf62020-04-17 18:19:10 -07001512status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1513 audio_session_t session,
1514 const audio_config_t *config,
1515 audio_output_flags_t flags,
1516 const DeviceVector &devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001517 audio_io_handle_t *output,
1518 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001519
1520 *output = AUDIO_IO_HANDLE_NONE;
1521
1522 // skip direct output selection if the request can obviously be attached to a mixed output
1523 // and not explicitly requested
1524 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1525 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1526 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1527 return NAME_NOT_FOUND;
1528 }
1529
1530 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1531 // This prevents creating an offloaded track and tearing it down immediately after start
1532 // when audioflinger detects there is an active non offloadable effect.
1533 // FIXME: We should check the audio session here but we do not have it in this context.
1534 // This may prevent offloading in rare situations where effects are left active by apps
1535 // in the background.
1536 sp<IOProfile> profile;
1537 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1538 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1539 profile = getProfileForOutput(
1540 devices, config->sample_rate, config->format, config->channel_mask,
1541 flags, true /* directOnly */);
1542 }
1543
1544 if (profile == nullptr) {
1545 return NAME_NOT_FOUND;
1546 }
1547
1548 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1549 for (size_t i = 0; i < mOutputs.size(); i++) {
1550 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1551 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1552 // reuse direct output if currently open by the same client
1553 // and configured with same parameters
1554 if ((config->sample_rate == desc->getSamplingRate()) &&
1555 (config->format == desc->getFormat()) &&
1556 (config->channel_mask == desc->getChannelMask()) &&
1557 (session == desc->mDirectClientSession)) {
1558 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301559 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001560 mOutputs.keyAt(i), session);
1561 *output = mOutputs.keyAt(i);
1562 return NO_ERROR;
1563 }
1564 }
1565 }
1566
1567 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001568 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301569 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1570 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001571 return NAME_NOT_FOUND;
1572 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1573 // MMAP gracefully handles lack of an exclusive track resource by mixing
1574 // above the audio framework. For AAudio to know that the limit is reached,
1575 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301576 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1577 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001578 return NAME_NOT_FOUND;
1579 } else {
1580 // Close outputs on this profile, if available, to free resources for this request
1581 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1582 const auto desc = mOutputs.valueAt(i);
1583 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301584 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1585 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001586 closeOutput(desc->mIoHandle);
1587 }
1588 }
1589 }
1590 }
1591
1592 // Unable to close streams to find free resources for this request
1593 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301594 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1595 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001596 return NAME_NOT_FOUND;
1597 }
1598
Atneya Nairb16666a2023-12-11 20:18:33 -08001599 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001600
Michael Chan6fb34492020-12-08 15:44:49 +11001601 // An MSD patch may be using the only output stream that can service this request. Release
1602 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001603 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001604
Eric Laurentf1f22e72021-07-13 14:04:14 +02001605 status_t status =
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001606 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1607 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001608
1609 // only accept an output with the requested parameters
1610 if (status != NO_ERROR ||
1611 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1612 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1613 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1614 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1615 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1616 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1617 config->channel_mask, outputDesc->getChannelMask());
1618 if (*output != AUDIO_IO_HANDLE_NONE) {
1619 outputDesc->close();
1620 }
1621 // fall back to mixer output if possible when the direct output could not be open
1622 if (audio_is_linear_pcm(config->format) &&
1623 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1624 return NAME_NOT_FOUND;
1625 }
1626 *output = AUDIO_IO_HANDLE_NONE;
1627 return BAD_VALUE;
1628 }
1629 outputDesc->mDirectOpenCount = 1;
1630 outputDesc->mDirectClientSession = session;
1631
1632 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001633 setOutputDevices(__func__, outputDesc,
1634 devices,
1635 true,
1636 0,
1637 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001638 mPreviousOutputs = mOutputs;
1639 ALOGV("%s returns new direct output %d", __func__, *output);
1640 mpClientInterface->onAudioPortListUpdate();
1641 return NO_ERROR;
1642}
1643
François Gaffie11d30102018-11-02 16:09:09 +01001644audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1645 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001646 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001647 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001648 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001649 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001650 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001651 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001652 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001653{
Andy Hungc88b0642018-04-27 15:42:35 -07001654 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001655
jiabine375d412019-02-26 12:54:53 -08001656 // Discard haptic channel mask when forcing muting haptic channels.
1657 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001658 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1659 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001660
Eric Laurente552edb2014-03-10 17:42:56 -07001661 // open a direct output if required by specified parameters
1662 //force direct flag if offload flag is set: offloading implies a direct output stream
1663 // and all common behaviors are driven by checking only the direct flag
1664 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001665 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1666 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001667 }
Nadav Bar766fb022018-01-07 12:18:03 +02001668 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1669 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001670 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001671
1672 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1673
Eric Laurente83b55d2014-11-14 10:06:21 -08001674 // only allow deep buffering for music stream type
1675 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001676 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001677 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001678 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001679 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1680 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001681 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001682 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001683 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001684 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001685 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001686 audio_is_linear_pcm(config->format) &&
1687 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001688 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001689 AUDIO_OUTPUT_FLAG_DIRECT);
1690 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001691 }
Eric Laurente552edb2014-03-10 17:42:56 -07001692
Carter Hsua3abb402021-10-26 11:11:20 +08001693 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1694 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1695 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1696 }
1697
Eric Laurentf9230d52024-01-26 18:49:09 +01001698 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001699 // was specified and offload or direct playback is not explicitly requested, and there is no
1700 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001701 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001702 if (mSpatializerOutput != nullptr &&
1703 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1704 prefMixerConfigInfo == nullptr &&
1705 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1706 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001707 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001708 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001709 }
1710
Eric Laurentc529cf62020-04-17 18:19:10 -07001711 audio_config_t directConfig = *config;
1712 directConfig.channel_mask = channelMask;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001713
1714 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1715 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001716 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001717 return output;
1718 }
1719
Eric Laurent14cbfca2016-03-17 09:42:16 -07001720 // A request for HW A/V sync cannot fallback to a mixed output because time
1721 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001722 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001723 return AUDIO_IO_HANDLE_NONE;
1724 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001725 // A request for Tuner cannot fallback to a mixed output
1726 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1727 return AUDIO_IO_HANDLE_NONE;
1728 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001729
Eric Laurente552edb2014-03-10 17:42:56 -07001730 // ignoring channel mask due to downmix capability in mixer
1731
1732 // open a non direct output
1733
1734 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001735 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001736 // get which output is suitable for the specified stream. The actual
1737 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001738 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001739 if (prefMixerConfigInfo != nullptr) {
1740 for (audio_io_handle_t outputHandle : outputs) {
1741 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1742 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1743 output = outputHandle;
1744 break;
1745 }
1746 }
1747 if (output == AUDIO_IO_HANDLE_NONE) {
1748 // No output open with the preferred profile. Open a new one.
1749 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1750 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1751 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1752 config.format = prefMixerConfigInfo->getConfigBase().format;
1753 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1754 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1755 &config, prefMixerConfigInfo->getFlags());
1756 if (preferredOutput == nullptr) {
1757 ALOGE("%s failed to open output with preferred mixer config", __func__);
1758 } else {
1759 output = preferredOutput->mIoHandle;
1760 }
1761 }
1762 } else {
1763 // at this stage we should ignore the DIRECT flag as no direct output could be
1764 // found earlier
1765 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001766 if (com::android::media::audioserver::
1767 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1768 // If the preferred mixer attributes is null, do not select the bit-perfect output
1769 // unless the bit-perfect output is the only output.
1770 // The bit-perfect output can exist while the passed in preferred mixer attributes
1771 // info is null when it is a high priority client. The high priority clients are
1772 // ringtone or alarm, which is not a bit-perfect use case.
1773 size_t i = 0;
1774 while (i < outputs.size() && outputs.size() > 1) {
1775 auto desc = mOutputs.valueFor(outputs[i]);
1776 // The output descriptor must not be null here.
1777 if (desc->isBitPerfect()) {
1778 outputs.removeItemsAt(i);
1779 } else {
1780 i += 1;
1781 }
1782 }
1783 }
jiabina84c3d32022-12-02 18:59:55 +00001784 output = selectOutput(
1785 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1786 }
Eric Laurente552edb2014-03-10 17:42:56 -07001787 }
François Gaffie11d30102018-11-02 16:09:09 +01001788 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001789 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001790 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001791
Eric Laurente552edb2014-03-10 17:42:56 -07001792 return output;
1793}
1794
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001795sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001796 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1797 mAvailableInputDevices);
1798 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1799}
1800
1801DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1802 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1803 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001804}
1805
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001806const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001807 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001808 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1809 if (msdModule != 0) {
1810 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1811 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1812 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1813 const struct audio_port_config *source = &patch->mPatch.sources[j];
1814 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1815 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001816 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001817 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001818 }
1819 }
1820 }
1821 return msdPatches;
1822}
1823
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001824bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1825 ssize_t index = mAudioPatches.indexOfKey(handle);
1826 if (index < 0) {
1827 return false;
1828 }
1829 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1830 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1831 if (msdModule == nullptr) {
1832 return false;
1833 }
1834 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1835 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1836 return true;
1837 }
1838 index = getMsdOutputPatches().indexOfKey(handle);
1839 if (index < 0) {
1840 return false;
1841 }
1842 return true;
1843}
1844
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001845status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1846 const InputProfileCollection &inputProfiles,
1847 const OutputProfileCollection &outputProfiles,
1848 const sp<DeviceDescriptor> &sourceDevice,
1849 const sp<DeviceDescriptor> &sinkDevice,
1850 AudioProfileVector& sourceProfiles,
1851 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001852 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854 return NO_INIT;
1855 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001856 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001857 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001858 return NO_INIT;
1859 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001860 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001861 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1862 inProfile->supportsDevice(sourceDevice)) {
1863 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001864 }
1865 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001866 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001867 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001868 outProfile->supportsDevice(sinkDevice)) {
1869 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001870 }
1871 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001872 return NO_ERROR;
1873}
1874
1875status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1876 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1877 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1878{
Dean Wheatley16809da2022-12-09 14:55:46 +11001879 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1880 static const std::vector<audio_format_t> formatsOrder = {{
1881 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001882 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1883 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001884 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1885 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1886 // preferred).
1887 std::vector<audio_channel_mask_t> masks = {{
1888 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1889 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1890 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1891 // insert index masks (higher counts most preferred) as preferred over position masks
1892 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1893 masks.insert(
1894 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1895 }
1896 return masks;
1897 }();
1898
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001900 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1901 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001902 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001903 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1904 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001905 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001906 }
1907 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1908 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1909 sinkConfig->format = bestSinkConfig.format;
1910 // For encoded streams force direct flag to prevent downstream mixing.
1911 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1912 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001913 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1914 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001915 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001916 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1917 // raw and IEC61937 framed streams.
1918 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1919 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1920 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001921 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1922 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001923 sourceConfig->channel_mask =
1924 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1925 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1926 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001927 sourceConfig->format = bestSinkConfig.format;
1928 // Copy input stream directly without any processing (e.g. resampling).
1929 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1930 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1931 if (hwAvSync) {
1932 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1933 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1934 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1935 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1936 }
1937 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1938 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1939 sinkConfig->config_mask |= config_mask;
1940 sourceConfig->config_mask |= config_mask;
1941 return NO_ERROR;
1942}
1943
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001944PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1945 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001946{
1947 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001948 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1949 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1950 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1951 if (deviceModule == nullptr) {
1952 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1953 return patchBuilder;
1954 }
1955 const InputProfileCollection inputProfiles = msdIsSource ?
1956 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1957 const OutputProfileCollection outputProfiles = msdIsSource ?
1958 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1959
1960 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1961 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1962 device : getMsdAudioOutDevices().itemAt(0);
1963 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1964
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001965 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1966 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001967 AudioProfileVector sourceProfiles;
1968 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001969 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1970 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001971 for (auto hwAvSync : { true, false }) {
1972 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1973 sourceProfiles, sinkProfiles) != NO_ERROR) {
1974 continue;
1975 }
1976 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1977 &sinkConfig) == NO_ERROR) {
1978 // Found a matching config. Re-create PatchBuilder with this config.
1979 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1980 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001981 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001982 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001983 " supporting PCM format conversion.", __func__);
1984 return patchBuilder;
1985}
1986
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001987status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001988 DeviceVector devices;
1989 if (outputDevices != nullptr && outputDevices->size() > 0) {
1990 devices.add(*outputDevices);
1991 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001992 // Use media strategy for unspecified output device. This should only
1993 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1994 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001995 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001996 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001997 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001998 }
Michael Chan6fb34492020-12-08 15:44:49 +11001999 std::vector<PatchBuilder> patchesToCreate;
2000 for (auto i = 0u; i < devices.size(); ++i) {
2001 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002002 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002003 }
2004 // Retain only the MSD patches associated with outputDevices request.
2005 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002006 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002007 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2008 auto retainedPatch = false;
2009 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2010 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2011 patchesToRemove.removeItemsAt(i);
2012 retainedPatch = true;
2013 break;
2014 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002015 }
Michael Chan6fb34492020-12-08 15:44:49 +11002016 if (retainedPatch) {
2017 it = patchesToCreate.erase(it);
2018 continue;
2019 }
2020 ++it;
2021 }
2022 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2023 return NO_ERROR;
2024 }
2025 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2026 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002027 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002028 }
Michael Chan6fb34492020-12-08 15:44:49 +11002029 status_t status = NO_ERROR;
2030 for (const auto &p : patchesToCreate) {
2031 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2032 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2033 char message[256];
2034 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2035 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2036 currStatus == NO_ERROR ? "Success" : "Error",
2037 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2038 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2039 if (currStatus == NO_ERROR) {
2040 ALOGD("%s", message);
2041 } else {
2042 ALOGE("%s", message);
2043 if (status == NO_ERROR) {
2044 status = currStatus;
2045 }
2046 }
2047 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002048 return status;
2049}
2050
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002051void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2052 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002053 for (size_t i = 0; i < msdPatches.size(); i++) {
2054 const auto& patch = msdPatches[i];
2055 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2056 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2057 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2058 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2059 releaseAudioPatch(patch->getHandle(), mUidCached);
2060 break;
2061 }
2062 }
2063 }
2064}
2065
Dorin Drimus94d94412022-02-02 09:05:02 +01002066bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002067 DeviceVector devicesToCheck =
2068 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002069 AudioPatchCollection msdPatches = getMsdOutputPatches();
2070 for (size_t i = 0; i < msdPatches.size(); i++) {
2071 const auto& patch = msdPatches[i];
2072 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2073 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2074 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2075 const auto& foundDevice = devicesToCheck.getDevice(
2076 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2077 if (foundDevice != nullptr) {
2078 devicesToCheck.remove(foundDevice);
2079 if (devicesToCheck.isEmpty()) {
2080 return true;
2081 }
2082 }
2083 }
2084 }
2085 }
2086 return false;
2087}
2088
Eric Laurente0720872014-03-11 09:30:41 -07002089audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002090 audio_output_flags_t flags,
2091 audio_format_t format,
2092 audio_channel_mask_t channelMask,
2093 uint32_t samplingRate,
2094 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002095{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002096 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2097 "%s called with format %#x", __func__, format);
2098
jiabinebb6af42020-06-09 17:31:17 -07002099 // Return the output that haptic-generating attached to when 1) session id is specified,
2100 // 2) haptic-generating effect exists for given session id and 3) the output that
2101 // haptic-generating effect attached to is in given outputs.
2102 if (sessionId != AUDIO_SESSION_NONE) {
2103 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2104 sessionId, FX_IID_HAPTICGENERATOR);
2105 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2106 return hapticGeneratingOutput;
2107 }
2108 }
2109
Eric Laurent16c66dd2019-05-01 17:54:10 -07002110 // Flags disqualifying an output: the match must happen before calling selectOutput()
2111 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2112 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2113
2114 // Flags expressing a functional request: must be honored in priority over
2115 // other criteria
2116 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2117 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002118 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2119 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002120 // Flags expressing a performance request: have lower priority than serving
2121 // requested sampling rate or channel mask
2122 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2123 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2124 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2125
2126 const audio_output_flags_t functionalFlags =
2127 (audio_output_flags_t)(flags & kFunctionalFlags);
2128 const audio_output_flags_t performanceFlags =
2129 (audio_output_flags_t)(flags & kPerformanceFlags);
2130
2131 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2132
Eric Laurente552edb2014-03-10 17:42:56 -07002133 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002134 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002135 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002136 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002137 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002138 // with tiebreak preferring the minimum number of extra functional flags
2139 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002140 // 3: the output supporting the exact channel mask
2141 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002142 // 5: the output with the highest sampling rate if the requested sample rate is
2143 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002144 // 6: the output with the highest number of requested performance flags
2145 // 7: the output with the bit depth the closest to the requested one
2146 // 8: the primary output
2147 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002148
Eric Laurent16c66dd2019-05-01 17:54:10 -07002149 // matching criteria values in priority order for best matching output so far
2150 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002151
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002152 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002153 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2154 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2155 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002156
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002157 for (audio_io_handle_t output : outputs) {
2158 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002159 // matching criteria values in priority order for current output
2160 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002161
Eric Laurent16c66dd2019-05-01 17:54:10 -07002162 if (outputDesc->isDuplicated()) {
2163 continue;
2164 }
2165 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2166 continue;
2167 }
Eric Laurent8838a382014-09-08 16:44:28 -07002168
Eric Laurent16c66dd2019-05-01 17:54:10 -07002169 // If haptic channel is specified, use the haptic output if present.
2170 // When using haptic output, same audio format and sample rate are required.
2171 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002172 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002173 // skip if haptic channel specified but output does not support it, or output support haptic
2174 // but there is no haptic channel requested AND no orphan haptic effect exist
2175 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2176 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002177 continue;
2178 }
Shunkai Yao808da212024-04-05 22:50:56 +00002179 // In the case of audio-coupled-haptic playback, there is no format conversion and
2180 // resampling in the framework, same format/channel/sampleRate for client and the output
2181 // thread is required. In the case of HapticGenerator effect, do not require format
2182 // matching.
2183 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2184 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002185 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002186 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002187 }
2188
2189 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002190 const int matchingFunctionalFlags =
2191 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2192 const int totalFunctionalFlags =
2193 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2194 // Prefer matching functional flags, but subtract unnecessary functional flags.
2195 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002196
2197 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002198 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2199 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002200 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2201 channelCount <= outputChannelCount) {
2202 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002203 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2204 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002205 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002206 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002207 currentMatchCriteria[3] = outputChannelCount;
2208 }
2209
2210 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002211 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002212 int diff; // avoid unsigned integer overflow.
2213 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2214
2215 // prefer the closest output sampling rate greater than or equal to target
2216 // if none exists, prefer the closest output sampling rate less than target.
2217 //
2218 // criteria is offset to make non-negative.
2219 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002220 }
2221
2222 // performance flags match
2223 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2224
2225 // format match
2226 if (format != AUDIO_FORMAT_INVALID) {
2227 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002228 PolicyAudioPort::kFormatDistanceMax -
2229 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002230 }
2231
2232 // primary output match
2233 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2234
2235 // compare match criteria by priority then value
2236 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2237 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2238 bestMatchCriteria = currentMatchCriteria;
2239 bestOutput = output;
2240
2241 std::stringstream result;
2242 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2243 std::ostream_iterator<int>(result, " "));
2244 ALOGV("%s new bestOutput %d criteria %s",
2245 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002246 }
2247 }
2248
Eric Laurent16c66dd2019-05-01 17:54:10 -07002249 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002250}
2251
Eric Laurent8fc147b2018-07-22 19:13:55 -07002252status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002253{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002254 ALOGV("%s portId %d", __FUNCTION__, portId);
2255
2256 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2257 if (outputDesc == 0) {
2258 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002259 return BAD_VALUE;
2260 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002261 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002262
Eric Laurent8fc147b2018-07-22 19:13:55 -07002263 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002265
jiabin220eea12024-05-17 17:55:20 +00002266 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2267 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2268 && outputDesc->isBitPerfect()) {
2269 // Usually, APM selects bit-perfect output for high priority use cases only when
2270 // bit-perfect output is the only output that can be routed to the selected device.
2271 // However, here is no need to play high priority use cases such as ringtone and alarm
2272 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2273 // can attach to new output.
2274 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2275 __func__, client->stream());
2276 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2277 return DEAD_OBJECT;
2278 }
2279
Eric Laurent733ce942017-12-07 12:18:25 -08002280 status_t status = outputDesc->start();
2281 if (status != NO_ERROR) {
2282 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002283 }
2284
Eric Laurent97ac8712018-07-27 18:59:02 -07002285 uint32_t delayMs;
2286 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002287
2288 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002289 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002290 if (status == DEAD_OBJECT) {
2291 sp<SwAudioOutputDescriptor> desc =
2292 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2293 if (desc == nullptr) {
2294 // This is not common, it may indicate something wrong with the HAL.
2295 ALOGE("%s unable to open output with default config", __func__);
2296 return status;
2297 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002298 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002299 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002300 }
jiabina84c3d32022-12-02 18:59:55 +00002301
2302 // If the client is the first one active on preferred mixer parameters, reopen the output
2303 // if the current mixer parameters doesn't match the preferred one.
2304 if (outputDesc->devices().size() == 1) {
2305 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2306 outputDesc->devices()[0]->getId(), client->strategy());
2307 if (info != nullptr && info->getUid() == client->uid()) {
2308 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2309 info->getConfigBase(), info->getFlags())) {
2310 stopSource(outputDesc, client);
2311 outputDesc->stop();
2312 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2313 config.channel_mask = info->getConfigBase().channel_mask;
2314 config.sample_rate = info->getConfigBase().sample_rate;
2315 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002316 sp<SwAudioOutputDescriptor> desc =
2317 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2318 if (desc == nullptr) {
2319 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002320 }
jiabin220eea12024-05-17 17:55:20 +00002321 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002322 // Intentionally return error to let the client side resending request for
2323 // creating and starting.
2324 return DEAD_OBJECT;
2325 }
2326 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002327 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002328 // If it is first bit-perfect client, reroute all clients that will be routed to
2329 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2330 PortHandleVector clientsToInvalidate;
2331 for (size_t i = 0; i < mOutputs.size(); i++) {
2332 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002333 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002334 continue;
2335 }
2336 for (const auto& c : mOutputs[i]->getClientIterable()) {
2337 clientsToInvalidate.push_back(c->portId());
2338 }
2339 }
2340 if (!clientsToInvalidate.empty()) {
2341 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2342 __func__);
2343 mpClientInterface->invalidateTracks(clientsToInvalidate);
2344 }
2345 }
jiabina84c3d32022-12-02 18:59:55 +00002346 }
2347 }
2348
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002349 if (client->hasPreferredDevice()) {
2350 // playback activity with preferred device impacts routing occurred, inform upper layers
2351 mpClientInterface->onRoutingUpdated();
2352 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002353 if (delayMs != 0) {
2354 usleep(delayMs * 1000);
2355 }
2356
jiabin220eea12024-05-17 17:55:20 +00002357 if (status == NO_ERROR &&
2358 outputDesc->mPreferredAttrInfo != nullptr &&
2359 outputDesc->isBitPerfect() &&
2360 com::android::media::audioserver::
2361 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2362 // A new client is started on bit-perfect output, update all clients internal mute.
2363 updateClientsInternalMute(outputDesc);
2364 }
2365
Eric Laurentc75307b2015-03-17 15:29:32 -07002366 return status;
2367}
2368
Eric Laurent96d1dda2022-03-14 17:14:19 +01002369bool AudioPolicyManager::isLeUnicastActive() const {
2370 if (isInCall()) {
2371 return true;
2372 }
2373 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2374}
2375
2376bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2377 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2378 return false;
2379 }
2380 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2381 ALOGV("%s active %d", __func__, active);
2382 return active;
2383}
2384
Eric Laurent97ac8712018-07-27 18:59:02 -07002385status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2386 const sp<TrackClientDescriptor>& client,
2387 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002388{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002389 // cannot start playback of STREAM_TTS if any other output is being used
2390 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002391
2392 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002393 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002394 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002395 auto clientStrategy = client->strategy();
2396 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002397 if (stream == AUDIO_STREAM_TTS) {
2398 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002399 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002400 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002401 return INVALID_OPERATION;
2402 } else {
2403 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2404 }
2405 } else {
2406 // some playback other than beacon starts
2407 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2408 }
2409
Eric Laurent77305a62016-07-25 16:39:22 -07002410 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002411 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002412 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002413
François Gaffie11d30102018-11-02 16:09:09 +01002414 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002415 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002416 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002417 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002418 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002419 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002420 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002421 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002422 } else {
2423 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002424 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002425 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2426 AUDIO_FORMAT_DEFAULT);
2427 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2428 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002429 }
2430
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002431 // requiresMuteCheck is false when we can bypass mute strategy.
2432 // It covers a common case when there is no materially active audio
2433 // and muting would result in unnecessary delay and dropped audio.
2434 const uint32_t outputLatencyMs = outputDesc->latency();
2435 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002436 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002437
Eric Laurente552edb2014-03-10 17:42:56 -07002438 // increment usage count for this stream on the requested output:
2439 // NOTE that the usage count is the same for duplicated output and hardware output which is
2440 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002441 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002442
2443 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002444 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002445 // Preferred device may be exclusive, use only if no other active clients on this output
2446 devices = DeviceVector(
2447 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2448 } else {
2449 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2450 }
François Gaffie11d30102018-11-02 16:09:09 +01002451 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002452 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002453 }
2454 }
Eric Laurente552edb2014-03-10 17:42:56 -07002455
François Gaffiec005e562018-11-06 15:04:49 +01002456 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002457 selectOutputForMusicEffects();
2458 }
2459
François Gaffie1c878552018-11-22 16:53:21 +01002460 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002461 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002462 if (devices.isEmpty()) {
2463 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002464 }
François Gaffiec005e562018-11-06 15:04:49 +01002465 bool shouldWait =
2466 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2467 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2468 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002469 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002470 const bool needToCloseBitPerfectOutput =
2471 (com::android::media::audioserver::
2472 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2473 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2474 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002475 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002476 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002477 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002478 // An output has a shared device if
2479 // - managed by the same hw module
2480 // - supports the currently selected device
2481 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002482 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002483
Eric Laurent77305a62016-07-25 16:39:22 -07002484 // force a device change if any other output is:
2485 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002486 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002487 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002488 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002489 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002490 // change the device currently selected by the other output.
2491 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002492 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002493 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002494 force = true;
2495 }
2496 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002497 // a notification so that audio focus effect can propagate, or that a mute/unmute
2498 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002499 const uint32_t latencyMs = desc->latency();
2500 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2501
2502 if (shouldWait && isActive && (waitMs < latencyMs)) {
2503 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002504 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002505
2506 // Require mute check if another output is on a shared device
2507 // and currently active to have proper drain and avoid pops.
2508 // Note restoring AudioTracks onto this output needs to invoke
2509 // a volume ramp if there is no mute.
2510 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002511
2512 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2513 outputsToReopen.push_back(desc);
2514 }
Eric Laurente552edb2014-03-10 17:42:56 -07002515 }
2516 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002517
jiabin220eea12024-05-17 17:55:20 +00002518 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002519 // If the output is open with preferred mixer attributes, but the routed device is
2520 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2521 // changed.
2522 return DEAD_OBJECT;
2523 }
jiabin220eea12024-05-17 17:55:20 +00002524 for (auto& outputToReopen : outputsToReopen) {
2525 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2526 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002527 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302528 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2529 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002530
Eric Laurente552edb2014-03-10 17:42:56 -07002531 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002532 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002533 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002534 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002535 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002536 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002537 outputDesc->useHwGain() /*force*/)) {
2538 // request AudioService to reinitialize the volume curves asynchronously
2539 ALOGE("checkAndSetVolume failed, requesting volume range init");
2540 mpClientInterface->onVolumeRangeInitRequest();
2541 };
Eric Laurente552edb2014-03-10 17:42:56 -07002542
2543 // update the outputs if starting an output with a stream that can affect notification
2544 // routing
2545 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002546
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002547 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002548 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002549 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002550 }
Eric Laurentdc462862016-07-19 12:29:53 -07002551
2552 if (waitMs > muteWaitMs) {
2553 *delayMs = waitMs - muteWaitMs;
2554 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002555
2556 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2557 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2558 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2559 // change occurs after the MixerThread starts and causes a stream volume
2560 // glitch.
2561 //
2562 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002563 }
Eric Laurentdc462862016-07-19 12:29:53 -07002564
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002565 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002566 mEngine->getForceUse(
2567 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002568 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002569 }
2570
Eric Laurent97ac8712018-07-27 18:59:02 -07002571 // Automatically enable the remote submix input when output is started on a re routing mix
2572 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002573 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2574 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002575 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2576 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2577 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002578 "remote-submix",
2579 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002580 }
2581
Eric Laurent96d1dda2022-03-14 17:14:19 +01002582 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2583
Eric Laurente552edb2014-03-10 17:42:56 -07002584 return NO_ERROR;
2585}
2586
Eric Laurent96d1dda2022-03-14 17:14:19 +01002587void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2588 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2589 bool isUnicastActive = isLeUnicastActive();
2590
2591 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002592 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002593 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2594 for (size_t i = 0; i < mOutputs.size(); i++) {
2595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2596 if (desc != ignoredOutput && desc->isActive()
2597 && ((isUnicastActive &&
2598 !desc->devices().
2599 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2600 || (wasUnicastActive &&
2601 !desc->devices().getDevicesFromTypes(
2602 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2603 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2604 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002605 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002606 // If the device is using preferred mixer attributes, the output need to reopen
2607 // with default configuration when the new selected devices are different from
2608 // current routing devices.
2609 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2610 continue;
2611 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302612 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002613 // re-apply device specific volume if not done by setOutputDevice()
2614 if (!force) {
2615 applyStreamVolumes(desc, newDevices.types(), delayMs);
2616 }
2617 }
2618 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002619 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002620 }
2621}
2622
Eric Laurent8fc147b2018-07-22 19:13:55 -07002623status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002624{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002625 ALOGV("%s portId %d", __FUNCTION__, portId);
2626
2627 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2628 if (outputDesc == 0) {
2629 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002630 return BAD_VALUE;
2631 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002632 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002633
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002634 if (client->hasPreferredDevice(true)) {
2635 // playback activity with preferred device impacts routing occurred, inform upper layers
2636 mpClientInterface->onRoutingUpdated();
2637 }
2638
Eric Laurent97ac8712018-07-27 18:59:02 -07002639 ALOGV("stopOutput() output %d, stream %d, session %d",
2640 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002641
Eric Laurent97ac8712018-07-27 18:59:02 -07002642 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002643
Eric Laurent733ce942017-12-07 12:18:25 -08002644 if (status == NO_ERROR ) {
2645 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002646 } else {
2647 return status;
2648 }
2649
2650 if (outputDesc->devices().size() == 1) {
2651 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2652 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002653 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002654 if (info != nullptr && info->getUid() == client->uid()) {
2655 info->decreaseActiveClient();
2656 if (info->getActiveClientCount() == 0) {
2657 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002658 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002659 }
2660 }
jiabin220eea12024-05-17 17:55:20 +00002661 if (com::android::media::audioserver::
2662 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2663 !outputReopened && outputDesc->isBitPerfect()) {
2664 // Only need to update the clients' internal mute when the output is bit-perfect and it
2665 // is not reopened.
2666 updateClientsInternalMute(outputDesc);
2667 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002668 }
2669 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002670}
2671
Eric Laurent97ac8712018-07-27 18:59:02 -07002672status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2673 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002674{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002675 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002676 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002677 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002678 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002679
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002680 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2681
François Gaffie1c878552018-11-22 16:53:21 +01002682 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2683 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002684 // Automatically disable the remote submix input when output is stopped on a
2685 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002686 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002687 if (isSingleDeviceType(
2688 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002689 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002690 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002691 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2692 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002693 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002694 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002695 }
2696 }
2697 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002698 if (client->hasPreferredDevice(true) &&
2699 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002700 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002701 forceDeviceUpdate = true;
2702 }
2703
Eric Laurente552edb2014-03-10 17:42:56 -07002704 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002705 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002706
Eric Laurente552edb2014-03-10 17:42:56 -07002707 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002708 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002709 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002710 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002711
2712 // If the routing does not change, if an output is routed on a device using HwGain
2713 // (aka setAudioPortConfig) and there are still active clients following different
2714 // volume group(s), force reapply volume
2715 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2716 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2717
Eric Laurente552edb2014-03-10 17:42:56 -07002718 // delay the device switch by twice the latency because stopOutput() is executed when
2719 // the track stop() command is received and at that time the audio track buffer can
2720 // still contain data that needs to be drained. The latency only covers the audio HAL
2721 // and kernel buffers. Also the latency does not always include additional delay in the
2722 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302723 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002724 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002725
2726 // force restoring the device selection on other active outputs if it differs from the
2727 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002728 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002729 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002730 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002731 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002732 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002733 desc->isActive() &&
2734 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002735 (newDevices != desc->devices())) {
2736 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2737 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002738
jiabin220eea12024-05-17 17:55:20 +00002739 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002740 // If the device is using preferred mixer attributes, the output need to
2741 // reopen with default configuration when the new selected devices are
2742 // different from current routing devices.
2743 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2744 continue;
2745 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302746 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002747
Eric Laurent57de36c2016-09-28 16:59:11 -07002748 // re-apply device specific volume if not done by setOutputDevice()
2749 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002750 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002751 }
Eric Laurente552edb2014-03-10 17:42:56 -07002752 }
2753 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002754 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002755 // update the outputs if stopping one with a stream that can affect notification routing
2756 handleNotificationRoutingForStream(stream);
2757 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002758
2759 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2760 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002761 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002762 }
2763
François Gaffiec005e562018-11-06 15:04:49 +01002764 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002765 selectOutputForMusicEffects();
2766 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002767
2768 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2769
Eric Laurente552edb2014-03-10 17:42:56 -07002770 return NO_ERROR;
2771 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002772 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002773 return INVALID_OPERATION;
2774 }
2775}
2776
jiabinbce0c1d2020-10-05 11:20:18 -07002777bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002778{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002779 ALOGV("%s portId %d", __FUNCTION__, portId);
2780
2781 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2782 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002783 // If an output descriptor is closed due to a device routing change,
2784 // then there are race conditions with releaseOutput from tracks
2785 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2786 // destroyed shortly thereafter.
2787 //
2788 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002789 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002790 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002791 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002792
2793 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002794
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302795 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2796 if (outputDesc->isClientActive(client)) {
2797 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2798 stopOutput(portId);
2799 }
2800
Eric Laurent8fc147b2018-07-22 19:13:55 -07002801 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2802 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002803 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002804 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002805 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002806 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002807 if (--outputDesc->mDirectOpenCount == 0) {
2808 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002809 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002810 }
2811 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302812
Andy Hung39efb7a2018-09-26 15:39:28 -07002813 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002814 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2815 // The output is pending reopened to query dynamic profiles and
2816 // there is no active clients
2817 closeOutput(outputDesc->mIoHandle);
2818 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2819 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2820 if (newOutputDesc == nullptr) {
2821 ALOGE("%s failed to open output", __func__);
2822 }
2823 return true;
2824 }
2825 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002826}
2827
Eric Laurentcaf7f482014-11-25 17:50:47 -08002828status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2829 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002830 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002831 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002832 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002833 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002834 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002835 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002836 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002837 audio_port_handle_t *portId,
2838 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002839{
François Gaffiec005e562018-11-06 15:04:49 +01002840 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002841 "flags %#x attributes=%s requested device ID %d",
2842 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2843 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002844
Eric Laurentad2e7b92017-09-14 20:06:42 -07002845 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002846 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002847 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002848 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002849 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002850 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002851 sp<RecordClientDescriptor> clientDesc;
2852 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002853 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002854 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855
2856 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2857 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2858 return INVALID_OPERATION;
2859 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002860
Francois Gaffie716e1432019-01-14 16:58:59 +01002861 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2862 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002863 }
2864
Paul McLean466dc8e2015-04-17 13:15:36 -06002865 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002866 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002867 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002868
Eric Laurentad2e7b92017-09-14 20:06:42 -07002869 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2870 // possible
2871 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2872 *input != AUDIO_IO_HANDLE_NONE) {
2873 ssize_t index = mInputs.indexOfKey(*input);
2874 if (index < 0) {
2875 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2876 status = BAD_VALUE;
2877 goto error;
2878 }
2879 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002880 RecordClientVector clients = inputDesc->getClientsForSession(session);
2881 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002882 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2883 status = BAD_VALUE;
2884 goto error;
2885 }
2886 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2887 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002888 // corresponds to a new client and is only permitted from the same UID.
2889 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002890 if (clients.size() > 1) {
2891 for (const auto& client : clients) {
2892 // The client map is ordered by key values (portId) and portIds are allocated
2893 // incrementaly. So the first client in this list is the one opened by audio flinger
2894 // when the mmap stream is created and should be ignored as it does not correspond
2895 // to an actual client
2896 if (client == *clients.cbegin()) {
2897 continue;
2898 }
2899 if (uid != client->uid() && !client->isSilenced()) {
2900 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2901 uid, client->portId(), client->uid());
2902 status = INVALID_OPERATION;
2903 goto error;
2904 }
Eric Laurent331679c2018-04-16 17:03:16 -07002905 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002906 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002907 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002908 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002909
Eric Laurentfecbceb2021-02-09 14:46:43 +01002910 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002911 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002912 }
2913
2914 *input = AUDIO_IO_HANDLE_NONE;
2915 *inputType = API_INPUT_INVALID;
2916
Francois Gaffie716e1432019-01-14 16:58:59 +01002917 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002918 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002919 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002920 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002921 ALOGW("%s could not find input mix for attr %s",
2922 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002923 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002924 }
jiabinc1de2df2019-05-07 14:26:40 -07002925 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2926 String8(attr->tags + strlen("addr=")),
2927 AUDIO_FORMAT_DEFAULT);
2928 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002929 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002930 __func__, attributes.source, attributes.tags);
2931 status = BAD_VALUE;
2932 goto error;
2933 }
2934
Kevin Rocard25f9b052019-02-27 15:08:54 -08002935 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2936 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2937 } else {
2938 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2939 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002940 if (virtualDeviceId) {
2941 *virtualDeviceId = policyMix->mVirtualDeviceId;
2942 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002943 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002944 if (explicitRoutingDevice != nullptr) {
2945 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002946 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002947 // Prevent from storing invalid requested device id in clients
2948 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002949 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002950 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2951 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002952 }
François Gaffie11d30102018-11-02 16:09:09 +01002953 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002954 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002955 status = BAD_VALUE;
2956 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002957 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002958 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2959 *inputType = API_INPUT_MIX_CAPTURE;
2960 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002961 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2962 // there is an external policy, but this input is attached to a mix of recorders,
2963 // meaning it receives audio injected into the framework, so the recorder doesn't
2964 // know about it and is therefore considered "legacy"
2965 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002966
2967 if (virtualDeviceId) {
2968 *virtualDeviceId = policyMix->mVirtualDeviceId;
2969 }
François Gaffie11d30102018-11-02 16:09:09 +01002970 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002971 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002972 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002973 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002974 } else {
2975 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002976 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002977
Eric Laurent599c7582015-12-07 18:05:55 -08002978 }
2979
François Gaffiec005e562018-11-06 15:04:49 +01002980 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002981 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002982 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002983 AudioProfileVector profiles;
2984 status_t ret = getProfilesForDevices(
2985 DeviceVector(device), profiles, flags, true /*isInput*/);
2986 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002987 const auto channels = profiles[0]->getChannels();
2988 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2989 config->channel_mask = *channels.begin();
2990 }
2991 const auto sampleRates = profiles[0]->getSampleRates();
2992 if (!sampleRates.empty() &&
2993 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2994 config->sample_rate = *sampleRates.begin();
2995 }
jiabinf1c73972022-04-14 16:28:52 -07002996 config->format = profiles[0]->getFormat();
2997 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002998 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002999 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003000
Marvin Ramine5a122d2023-12-07 13:57:59 +01003001
3002 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3003 *virtualDeviceId = policyMix->mVirtualDeviceId;
3004 }
3005
Eric Laurent8f42ea12018-08-08 09:08:25 -07003006exit:
3007
François Gaffiec005e562018-11-06 15:04:49 +01003008 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3009 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003010
Francois Gaffie716e1432019-01-14 16:58:59 +01003011 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003012 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003013 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014
Mikhail Naganov2996f672019-04-18 12:29:59 -07003015 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003016 requestedDeviceId, attributes.source, flags,
3017 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003018 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003019 // Move (if found) effect for the client session to its input
3020 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003021 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003022
3023 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3024 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003025
Eric Laurent599c7582015-12-07 18:05:55 -08003026 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003027
3028error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003029 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003030}
3031
3032
François Gaffie11d30102018-11-02 16:09:09 +01003033audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003034 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003035 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003036 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003037 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003038 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003039{
3040 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003041 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003042 bool isSoundTrigger = false;
3043
François Gaffiec005e562018-11-06 15:04:49 +01003044 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003045 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3046 if (index >= 0) {
3047 input = mSoundTriggerSessions.valueFor(session);
3048 isSoundTrigger = true;
3049 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3050 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3051 } else {
3052 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003053 }
François Gaffiec005e562018-11-06 15:04:49 +01003054 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003055 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003056 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003057 }
3058
Carter Hsua3abb402021-10-26 11:11:20 +08003059 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3060 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3061 }
3062
Eric Laurentfe231122017-11-17 17:48:06 -08003063 // sampling rate and flags may be updated by getInputProfile
3064 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3065 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003066 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003067 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003068 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003069 // find a compatible input profile (not necessarily identical in parameters)
3070 sp<IOProfile> profile = getInputProfile(
3071 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3072 if (profile == nullptr) {
3073 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003074 }
jiabin2fd710d2022-05-02 23:20:22 +00003075
Glenn Kasten05ddca52016-02-11 08:17:12 -08003076 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003077 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003078 if (samplingRate == 0) {
3079 samplingRate = profileSamplingRate;
3080 }
Eric Laurente552edb2014-03-10 17:42:56 -07003081
Eric Laurent322b4d22015-04-03 15:57:54 -07003082 if (profile->getModuleHandle() == 0) {
3083 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003084 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003085 }
3086
Eric Laurentec376dc2021-04-08 20:41:22 +02003087 // Reuse an already opened input if a client with the same session ID already exists
3088 // on that input
3089 for (size_t i = 0; i < mInputs.size(); i++) {
3090 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3091 if (desc->mProfile != profile) {
3092 continue;
3093 }
3094 RecordClientVector clients = desc->clientsList();
3095 for (const auto &client : clients) {
3096 if (session == client->session()) {
3097 return desc->mIoHandle;
3098 }
3099 }
3100 }
3101
Eric Laurent3974e3b2017-12-07 17:58:43 -08003102 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003103 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003104 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003105 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003106 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003107 continue;
3108 }
3109 // if sound trigger, reuse input if used by other sound trigger on same session
3110 // else
3111 // reuse input if active client app is not in IDLE state
3112 //
3113 RecordClientVector clients = desc->clientsList();
3114 bool doClose = false;
3115 for (const auto& client : clients) {
3116 if (isSoundTrigger != client->isSoundTrigger()) {
3117 continue;
3118 }
3119 if (client->isSoundTrigger()) {
3120 if (session == client->session()) {
3121 return desc->mIoHandle;
3122 }
3123 continue;
3124 }
3125 if (client->active() && client->appState() != APP_STATE_IDLE) {
3126 return desc->mIoHandle;
3127 }
3128 doClose = true;
3129 }
3130 if (doClose) {
3131 closeInput(desc->mIoHandle);
3132 } else {
3133 i++;
3134 }
3135 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003136 }
3137
Eric Laurentfe231122017-11-17 17:48:06 -08003138 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003139
Eric Laurentfe231122017-11-17 17:48:06 -08003140 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3141 lConfig.sample_rate = profileSamplingRate;
3142 lConfig.channel_mask = profileChannelMask;
3143 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003144
François Gaffie11d30102018-11-02 16:09:09 +01003145 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003146
3147 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003148 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003149 (profileSamplingRate != lConfig.sample_rate) ||
3150 !audio_formats_match(profileFormat, lConfig.format) ||
3151 (profileChannelMask != lConfig.channel_mask)) {
3152 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003153 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003154 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003155 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003156 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003157 }
Eric Laurent599c7582015-12-07 18:05:55 -08003158 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003159 }
3160
Eric Laurentc722f302014-12-10 11:21:49 -08003161 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003162
Eric Laurent599c7582015-12-07 18:05:55 -08003163 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003164 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003165
Eric Laurent599c7582015-12-07 18:05:55 -08003166 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003167}
3168
Eric Laurent4eb58f12018-12-07 16:41:02 -08003169status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003170{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003171 ALOGV("%s portId %d", __FUNCTION__, portId);
3172
3173 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3174 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003175 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003176 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003177 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003178 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003179 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003180 if (client->active()) {
3181 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3182 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003183 }
3184
Eric Laurent8f42ea12018-08-08 09:08:25 -07003185 audio_session_t session = client->session();
3186
Eric Laurent4eb58f12018-12-07 16:41:02 -08003187 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003188
Eric Laurent4eb58f12018-12-07 16:41:02 -08003189 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003190
Eric Laurent4eb58f12018-12-07 16:41:02 -08003191 status_t status = inputDesc->start();
3192 if (status != NO_ERROR) {
3193 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003194 }
Eric Laurente552edb2014-03-10 17:42:56 -07003195
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003196 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003197 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003198 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003199
Eric Laurent8f42ea12018-08-08 09:08:25 -07003200 // indicate active capture to sound trigger service if starting capture from a mic on
3201 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003202 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003203 if (device != nullptr) {
3204 status = setInputDevice(input, device, true /* force */);
3205 } else {
3206 ALOGW("%s no new input device can be found for descriptor %d",
3207 __FUNCTION__, inputDesc->getId());
3208 status = BAD_VALUE;
3209 }
Eric Laurente552edb2014-03-10 17:42:56 -07003210
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003211 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003212 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003213 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003214 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003215 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3216 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003217 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003218 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003219
François Gaffie11d30102018-11-02 16:09:09 +01003220 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3221 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003222 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003223 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003224 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003225
Eric Laurent8f42ea12018-08-08 09:08:25 -07003226 // automatically enable the remote submix output when input is started if not
3227 // used by a policy mix of type MIX_TYPE_RECORDERS
3228 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003229 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003230 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003231 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003232 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003233 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3234 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003235 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003236 if (address != "") {
3237 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3238 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003239 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003240 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003241 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003242 } else if (status != NO_ERROR) {
3243 // Restore client activity state.
3244 inputDesc->setClientActive(client, false);
3245 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003246 }
3247
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003248 ALOGV("%s input %d source = %d status = %d exit",
3249 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003250
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003251 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003252}
3253
Eric Laurent8fc147b2018-07-22 19:13:55 -07003254status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003255{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003256 ALOGV("%s portId %d", __FUNCTION__, portId);
3257
3258 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3259 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003260 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003261 return BAD_VALUE;
3262 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003263 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003264 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003265 if (!client->active()) {
3266 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003267 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003268 }
Carter Hsue6139d52021-07-08 10:30:20 +08003269 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003270 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003271
Eric Laurent8f42ea12018-08-08 09:08:25 -07003272 inputDesc->stop();
3273 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003274 auto current_source = inputDesc->source();
3275 setInputDevice(input, getNewInputDevice(inputDesc),
3276 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003277 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003278 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003279 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003280 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003281 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3282 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003283 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003284 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003285
3286 // automatically disable the remote submix output when input is stopped if not
3287 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003288 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003289 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003290 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003291 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003292 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3293 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003294 }
3295 if (address != "") {
3296 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3297 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003298 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003299 }
3300 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003301 resetInputDevice(input);
3302
3303 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3304 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003305 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3306 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003307 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003308 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003309 }
3310 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003311 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003312 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003313}
3314
Eric Laurent8fc147b2018-07-22 19:13:55 -07003315void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003316{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003317 ALOGV("%s portId %d", __FUNCTION__, portId);
3318
3319 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3320 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003321 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003322 return;
3323 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003324 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003325 audio_io_handle_t input = inputDesc->mIoHandle;
3326
Eric Laurent8f42ea12018-08-08 09:08:25 -07003327 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003328
Andy Hung39efb7a2018-09-26 15:39:28 -07003329 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003330
3331 // If no more clients are present in this session, park effects to an orphan chain
3332 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3333 if (clientsOnSession.size() == 0) {
3334 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3335 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003336 if (inputDesc->getClientCount() > 0) {
3337 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003338 return;
3339 }
3340
Eric Laurent05b90f82014-08-27 15:32:29 -07003341 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003342 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003343 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003344}
3345
Eric Laurent8f42ea12018-08-08 09:08:25 -07003346void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003347{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003348 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003349
3350 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003351 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003352 }
3353}
3354
Eric Laurent8f42ea12018-08-08 09:08:25 -07003355void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3356{
3357 stopInput(portId);
3358 releaseInput(portId);
3359}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003360
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003361bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3362 if (input->clientsList().size() == 0
3363 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3364 return true;
3365 }
3366 for (const auto& client : input->clientsList()) {
3367 sp<DeviceDescriptor> device =
3368 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3369 client->session());
3370 if (!input->supportedDevices().contains(device)) {
3371 return true;
3372 }
3373 }
3374 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3375 return false;
3376}
3377
Eric Laurent0dd51852019-04-19 18:18:58 -07003378void AudioPolicyManager::checkCloseInputs() {
3379 // After connecting or disconnecting an input device, close input if:
3380 // - it has no client (was just opened to check profile) OR
3381 // - none of its supported devices are connected anymore OR
3382 // - one of its clients cannot be routed to one of its supported
3383 // devices anymore. Otherwise update device selection
3384 std::vector<audio_io_handle_t> inputsToClose;
3385 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003386 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003387 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003388 }
3389 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003390 for (const audio_io_handle_t handle : inputsToClose) {
3391 ALOGV("%s closing input %d", __func__, handle);
3392 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003393 }
Eric Laurentd4692962014-05-05 18:13:44 -07003394}
3395
Vlad Popa87e0e582024-05-20 18:49:20 -07003396status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3397 const char *address __unused,
3398 bool enabled,
3399 audio_stream_type_t streamToDriveAbs)
3400{
3401 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3402 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3403 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3404 toString(streamToDriveAbs).c_str());
3405 return BAD_VALUE;
3406 }
3407
3408 if (enabled) {
3409 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3410 } else {
3411 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3412 }
3413
3414 return NO_ERROR;
3415}
3416
François Gaffie251c7f02018-11-07 10:41:08 +01003417void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003418{
3419 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003420 if (indexMin < 0 || indexMax < 0) {
3421 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3422 return;
3423 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003424 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003425
3426 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003427 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3428 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003429 continue;
3430 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003431 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003432 }
Eric Laurente552edb2014-03-10 17:42:56 -07003433}
3434
Eric Laurente0720872014-03-11 09:30:41 -07003435status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003436 int index,
3437 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003438{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003439 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003440 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3441 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3442 return NO_ERROR;
3443 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303444 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3445 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003446 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003447}
3448
Eric Laurente0720872014-03-11 09:30:41 -07003449status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003450 int *index,
3451 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003452{
François Gaffiec005e562018-11-06 15:04:49 +01003453 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3454 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003455 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003456 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003457 deviceTypes = mEngine->getOutputDevicesForStream(
3458 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003459 }
jiabin9a3361e2019-10-01 09:38:30 -07003460 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003461}
3462
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003463status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003464 int index,
3465 audio_devices_t device)
3466{
3467 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003468 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3469 if (group == VOLUME_GROUP_NONE) {
3470 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003471 return BAD_VALUE;
3472 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003473 ALOGV("%s: group %d matching with %s index %d",
3474 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003475 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003476 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003477 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003478 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3479 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3480 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3481 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003482 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3483
3484 status = setVolumeCurveIndex(index, device, curves);
3485 if (status != NO_ERROR) {
3486 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3487 return status;
3488 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003489
jiabin9a3361e2019-10-01 09:38:30 -07003490 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003491 auto curCurvAttrs = curves.getAttributes();
3492 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3493 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003494 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003495 } else if (!curves.getStreamTypes().empty()) {
3496 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003497 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003498 } else {
3499 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3500 return BAD_VALUE;
3501 }
jiabin9a3361e2019-10-01 09:38:30 -07003502 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3503 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003504
François Gaffiecfe17322018-11-07 13:41:29 +01003505 // update volume on all outputs and streams matching the following:
3506 // - The requested stream (or a stream matching for volume control) is active on the output
3507 // - The device (or devices) selected by the engine for this stream includes
3508 // the requested device
3509 // - For non default requested device, currently selected device on the output is either the
3510 // requested device or one of the devices selected by the engine for this stream
3511 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3512 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003513 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003514 for (size_t i = 0; i < mOutputs.size(); i++) {
3515 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003516 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003517
jiabin9a3361e2019-10-01 09:38:30 -07003518 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3519 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003520 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003521
3522 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003523 continue;
3524 }
3525 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3526 curDevices.find(device) == curDevices.end()) {
3527 continue;
3528 }
3529 bool applyVolume = false;
3530 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3531 curSrcDevices.insert(device);
3532 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003533 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3534 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003535 } else {
3536 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3537 }
3538 if (!applyVolume) {
3539 continue; // next output
3540 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003541 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3542 // If a higher priority strategy is active, and the output is routed to a device with a
3543 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003544 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003545 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003546 // If the volume source is active with higher priority source, ensure at least Sw Muted
3547 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003548 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3549 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3550 false /*preferredDevice*/);
3551 if (activeClients.empty()) {
3552 continue;
3553 }
3554 bool isPreempted = false;
3555 bool isHigherPriority = productStrategy < strategy;
3556 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003557 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003558 ALOGV("%s: Strategy=%d (\nrequester:\n"
3559 " group %d, volumeGroup=%d attributes=%s)\n"
3560 " higher priority source active:\n"
3561 " volumeGroup=%d attributes=%s) \n"
3562 " on output %zu, bailing out", __func__, productStrategy,
3563 group, group, toString(attributes).c_str(),
3564 client->volumeSource(), toString(client->attributes()).c_str(), i);
3565 applyVolume = false;
3566 isPreempted = true;
3567 break;
3568 }
3569 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003570 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003571 applyVolume = true;
3572 }
3573 }
3574 if (isPreempted || applyVolume) {
3575 break;
3576 }
3577 }
3578 if (!applyVolume) {
3579 continue; // next output
3580 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003581 }
François Gaffieed91f582020-01-31 10:35:37 +01003582 //FIXME: workaround for truncated touch sounds
3583 // delayed volume change for system stream to be removed when the problem is
3584 // handled by system UI
3585 status_t volStatus = checkAndSetVolume(
3586 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003587 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003588 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3589 if (volStatus != NO_ERROR) {
3590 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003591 }
3592 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003593
3594 // update voice volume if the an active call route exists
3595 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3596 && (curSrcDevices.find(
3597 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3598 != curSrcDevices.end())) {
3599 bool isVoiceVolSrc;
3600 bool isBtScoVolSrc;
3601 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3602 isVoiceVolSrc, isBtScoVolSrc, __func__)
3603 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003604 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3605 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3606 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003607 }
3608 }
3609
François Gaffiecfe17322018-11-07 13:41:29 +01003610 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3611 return status;
3612}
3613
François Gaffieaaac0fd2018-11-22 17:56:39 +01003614status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003615 audio_devices_t device,
3616 IVolumeCurves &volumeCurves)
3617{
3618 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3619 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003620 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3621 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003622 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303623 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3624 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003625 return BAD_VALUE;
3626 }
3627 if (!audio_is_output_device(device)) {
3628 return BAD_VALUE;
3629 }
3630
3631 // Force max volume if stream cannot be muted
3632 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3633
François Gaffieaaac0fd2018-11-22 17:56:39 +01003634 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003635 volumeCurves.addCurrentVolumeIndex(device, index);
3636 return NO_ERROR;
3637}
3638
3639status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3640 int &index,
3641 audio_devices_t device)
3642{
3643 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3644 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003645 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003646 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003647 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003648 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003649 }
jiabin9a3361e2019-10-01 09:38:30 -07003650 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003651}
3652
3653status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3654 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003655 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003656{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003657 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003658 return BAD_VALUE;
3659 }
jiabin9a3361e2019-10-01 09:38:30 -07003660 index = curves.getVolumeIndex(deviceTypes);
3661 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003662 return NO_ERROR;
3663}
3664
3665status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3666 int &index)
3667{
3668 index = getVolumeCurves(attr).getVolumeIndexMin();
3669 return NO_ERROR;
3670}
3671
3672status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3673 int &index)
3674{
3675 index = getVolumeCurves(attr).getVolumeIndexMax();
3676 return NO_ERROR;
3677}
3678
Eric Laurent36829f92017-04-07 19:04:42 -07003679audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003680{
3681 // select one output among several suitable for global effects.
3682 // The priority is as follows:
3683 // 1: An offloaded output. If the effect ends up not being offloadable,
3684 // AudioFlinger will invalidate the track and the offloaded output
3685 // will be closed causing the effect to be moved to a PCM output.
3686 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003687 // 3: The primary output
3688 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003689
François Gaffiec005e562018-11-06 15:04:49 +01003690 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3691 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003692 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003693
Eric Laurent36829f92017-04-07 19:04:42 -07003694 if (outputs.size() == 0) {
3695 return AUDIO_IO_HANDLE_NONE;
3696 }
Eric Laurente552edb2014-03-10 17:42:56 -07003697
Eric Laurent36829f92017-04-07 19:04:42 -07003698 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3699 bool activeOnly = true;
3700
3701 while (output == AUDIO_IO_HANDLE_NONE) {
3702 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3703 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3704 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3705
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003706 for (audio_io_handle_t output : outputs) {
3707 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003708 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003709 continue;
3710 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003711 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3712 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003713 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003714 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003715 }
3716 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003717 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003718 }
3719 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003720 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003721 }
3722 }
3723 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3724 output = outputOffloaded;
3725 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3726 output = outputDeepBuffer;
3727 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3728 output = outputPrimary;
3729 } else {
3730 output = outputs[0];
3731 }
3732 activeOnly = false;
3733 }
3734
3735 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003736 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3737 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003738 mMusicEffectOutput = output;
3739 }
3740
3741 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003742 return output;
3743}
3744
Eric Laurent36829f92017-04-07 19:04:42 -07003745audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3746{
3747 return selectOutputForMusicEffects();
3748}
3749
Eric Laurente0720872014-03-11 09:30:41 -07003750status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003751 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003752 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003753 int session,
3754 int id)
3755{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003756 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003757 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003758 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003759 index = mInputs.indexOfKey(io);
3760 if (index < 0) {
3761 ALOGW("registerEffect() unknown io %d", io);
3762 return INVALID_OPERATION;
3763 }
Eric Laurente552edb2014-03-10 17:42:56 -07003764 }
3765 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003766 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3767 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3768 || strategy == PRODUCT_STRATEGY_NONE));
3769 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003770}
3771
Eric Laurentc241b0d2018-11-28 09:08:49 -08003772status_t AudioPolicyManager::unregisterEffect(int id)
3773{
3774 if (mEffects.getEffect(id) == nullptr) {
3775 return INVALID_OPERATION;
3776 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003777 if (mEffects.isEffectEnabled(id)) {
3778 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3779 setEffectEnabled(id, false);
3780 }
3781 return mEffects.unregisterEffect(id);
3782}
3783
3784status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3785{
3786 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3787 if (effect == nullptr) {
3788 return INVALID_OPERATION;
3789 }
3790
3791 status_t status = mEffects.setEffectEnabled(id, enabled);
3792 if (status == NO_ERROR) {
3793 mInputs.trackEffectEnabled(effect, enabled);
3794 }
3795 return status;
3796}
3797
Eric Laurent6c796322019-04-09 14:13:17 -07003798
3799status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3800{
3801 mEffects.moveEffects(ids, io);
3802 return NO_ERROR;
3803}
3804
Eric Laurentc75307b2015-03-17 15:29:32 -07003805bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3806{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003807 auto vs = toVolumeSource(stream, false);
3808 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003809}
3810
3811bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3812{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003813 auto vs = toVolumeSource(stream, false);
3814 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003815}
3816
Eric Laurente0720872014-03-11 09:30:41 -07003817bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003818{
3819 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003820 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003821 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003822 return true;
3823 }
3824 }
3825 return false;
3826}
3827
Eric Laurent275e8e92014-11-30 15:14:47 -08003828// Register a list of custom mixes with their attributes and format.
3829// When a mix is registered, corresponding input and output profiles are
3830// added to the remote submix hw module. The profile contains only the
3831// parameters (sampling rate, format...) specified by the mix.
3832// The corresponding input remote submix device is also connected.
3833//
3834// When a remote submix device is connected, the address is checked to select the
3835// appropriate profile and the corresponding input or output stream is opened.
3836//
3837// When capture starts, getInputForAttr() will:
3838// - 1 look for a mix matching the address passed in attribtutes tags if any
3839// - 2 if none found, getDeviceForInputSource() will:
3840// - 2.1 look for a mix matching the attributes source
3841// - 2.2 if none found, default to device selection by policy rules
3842// At this time, the corresponding output remote submix device is also connected
3843// and active playback use cases can be transferred to this mix if needed when reconnecting
3844// after AudioTracks are invalidated
3845//
3846// When playback starts, getOutputForAttr() will:
3847// - 1 look for a mix matching the address passed in attribtutes tags if any
3848// - 2 if none found, look for a mix matching the attributes usage
3849// - 3 if none found, default to device and output selection by policy rules.
3850
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003851status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003852{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003853 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3854 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003855 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003856 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003857 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003858 // examine each mix's route type
3859 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003860 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003861 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3862 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3863 ALOGE("Unsupported Policy Mix %zu of %zu: "
3864 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3865 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003866 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003867 break;
3868 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003869 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3870 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003871 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003872 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3873 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003874 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003875 rSubmixModule = mHwModules.getModuleFromName(
3876 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3877 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003878 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003879 i);
3880 res = INVALID_OPERATION;
3881 break;
3882 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003883 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003884
Eric Laurent97ac8712018-07-27 18:59:02 -07003885 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003886 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003887 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003888 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003889 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3890 } else {
3891 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3892 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003893 }
François Gaffie036e1e92015-03-19 10:16:24 +01003894
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003895 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003896 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003897 res = INVALID_OPERATION;
3898 break;
3899 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003900 audio_config_t outputConfig = mix.mFormat;
3901 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003902 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3903 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003904 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3905 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003906 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003907 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3908 audio_is_linear_pcm(outputConfig.format)
3909 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003910 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003911 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3912 audio_is_linear_pcm(inputConfig.format)
3913 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003914
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003915 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003916 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003917 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003918 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003919 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003920 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003921 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003922 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3923 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003924 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003925 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003926 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003927
3928 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3929 mix.mDeviceType, mix.mDeviceAddress,
3930 String8(), AUDIO_FORMAT_DEFAULT);
3931 if (device == nullptr) {
3932 res = INVALID_OPERATION;
3933 break;
3934 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003935
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003936 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003937 // First try to find an already opened output supporting the device
3938 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003939 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003940
Eric Laurentc529cf62020-04-17 18:19:10 -07003941 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003942 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003943 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003944 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003945 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003946 } else {
3947 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003948 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003949 }
3950 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003951 // If no output found, try to find a direct output profile supporting the device
3952 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3953 sp<HwModule> module = mHwModules[i];
3954 for (size_t j = 0;
3955 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3956 j++) {
3957 sp<IOProfile> profile = module->getOutputProfiles()[j];
3958 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3959 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3960 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003961 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003962 res = INVALID_OPERATION;
3963 } else {
3964 foundOutput = true;
3965 }
3966 }
3967 }
3968 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003969 if (res != NO_ERROR) {
3970 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003971 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003972 res = INVALID_OPERATION;
3973 break;
3974 } else if (!foundOutput) {
3975 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003976 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003977 res = INVALID_OPERATION;
3978 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003979 } else {
3980 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003981 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003982 }
Eric Laurentc722f302014-12-10 11:21:49 -08003983 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003984 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003985 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003986 if (audio_flags::audio_mix_ownership()) {
3987 // Only unregister mixes that were actually registered to not accidentally unregister
3988 // mixes that already existed previously.
3989 unregisterPolicyMixes(registeredMixes);
3990 registeredMixes.clear();
3991 } else {
3992 unregisterPolicyMixes(mixes);
3993 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003994 } else if (checkOutputs) {
3995 checkForDeviceAndOutputChanges();
3996 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003997 }
3998 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003999}
4000
4001status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4002{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004003 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004004 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004005 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004006 sp<HwModule> rSubmixModule;
4007 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004008 for (const auto& mix : mixes) {
4009 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004010
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004011 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004012 rSubmixModule = mHwModules.getModuleFromName(
4013 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4014 if (rSubmixModule == 0) {
4015 res = INVALID_OPERATION;
4016 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004017 }
4018 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004019
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004020 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004021
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004022 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004023 res = INVALID_OPERATION;
4024 continue;
4025 }
4026
Marvin Ramin0783e202024-03-05 12:45:50 +01004027 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004028 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004029 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4030 status_t currentRes =
4031 setDeviceConnectionStateInt(device,
4032 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4033 address.c_str(),
4034 "remote-submix",
4035 AUDIO_FORMAT_DEFAULT);
4036 if (!audio_flags::audio_mix_ownership()) {
4037 res = currentRes;
4038 }
4039 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004040 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004041 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004042 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004043 }
4044 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004045 }
jiabin5740f082019-08-19 15:08:30 -07004046 rSubmixModule->removeOutputProfile(address.c_str());
4047 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004048
Kevin Rocard153f92d2018-12-18 18:33:28 -08004049 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004050 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004051 res = INVALID_OPERATION;
4052 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004053 } else {
4054 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004055 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004056 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004057 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004058
4059 if (res == NO_ERROR && checkOutputs) {
4060 checkForDeviceAndOutputChanges();
4061 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004062 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004063 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004064}
4065
Marvin Raminbdefaf02023-11-01 09:10:32 +01004066status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4067 if (!audio_flags::audio_mix_test_api()) {
4068 return INVALID_OPERATION;
4069 }
4070
4071 _aidl_return.clear();
4072 _aidl_return.reserve(mPolicyMixes.size());
4073 for (const auto &policyMix: mPolicyMixes) {
4074 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4075 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4076 policyMix->mCbFlags);
4077 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004078 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004079 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004080 }
4081
Vlad Popaa5d73f32024-03-08 16:05:38 -08004082 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004083 return OK;
4084}
4085
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004086status_t AudioPolicyManager::updatePolicyMix(
4087 const AudioMix& mix,
4088 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4089 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4090 if (res == NO_ERROR) {
4091 checkForDeviceAndOutputChanges();
4092 updateCallAndOutputRouting();
4093 }
4094 return res;
4095}
4096
Mikhail Naganov100f0122018-11-29 11:22:16 -08004097void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4098{
4099 size_t i = 0;
4100 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4101 for (const auto& fmt : mManualSurroundFormats) {
4102 if (i++ != 0) dst->append(", ");
4103 std::string sfmt;
4104 FormatConverter::toString(fmt, sfmt);
4105 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4106 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4107 }
4108}
4109
Eric Laurentc529cf62020-04-17 18:19:10 -07004110// Returns true if all devices types match the predicate and are supported by one HW module
4111bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004112 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004113 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004114 const char *context,
4115 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004116 for (size_t i = 0; i < devices.size(); i++) {
4117 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004118 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004119 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004120 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004121 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004122 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004123 return false;
4124 }
4125 }
4126 return true;
4127}
4128
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004129void AudioPolicyManager::changeOutputDevicesMuteState(
4130 const AudioDeviceTypeAddrVector& devices) {
4131 ALOGVV("%s() num devices %zu", __func__, devices.size());
4132
4133 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4134 getSoftwareOutputsForDevices(devices);
4135
4136 for (size_t i = 0; i < outputs.size(); i++) {
4137 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4138 DeviceVector prevDevices = outputDesc->devices();
4139 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4140 }
4141}
4142
4143std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4144 const AudioDeviceTypeAddrVector& devices) const
4145{
4146 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4147 DeviceVector deviceDescriptors;
4148 for (size_t j = 0; j < devices.size(); j++) {
4149 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4150 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4151 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4152 ALOGE("%s: device type %#x address %s not supported or not an output device",
4153 __func__, devices[j].mType, devices[j].getAddress());
4154 continue;
4155 }
4156 deviceDescriptors.add(desc);
4157 }
4158 for (size_t i = 0; i < mOutputs.size(); i++) {
4159 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4160 continue;
4161 }
4162 outputs.push_back(mOutputs.valueAt(i));
4163 }
4164 return outputs;
4165}
4166
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004167status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004168 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004169 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004170 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4171 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004172 }
4173 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004174 if (res != NO_ERROR) {
4175 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4176 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004177 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004178
4179 checkForDeviceAndOutputChanges();
4180 updateCallAndOutputRouting();
4181
4182 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004183}
4184
4185status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4186 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004187 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4188 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004189 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004190 __FUNCTION__, uid);
4191 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004192 }
4193
Eric Laurentc529cf62020-04-17 18:19:10 -07004194 checkForDeviceAndOutputChanges();
4195 updateCallAndOutputRouting();
4196
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004197 return res;
4198}
4199
Eric Laurent2517af32020-11-25 15:31:27 +01004200
jiabin0a488932020-08-07 17:32:40 -07004201status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4202 device_role_t role,
4203 const AudioDeviceTypeAddrVector &devices) {
4204 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4205 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004206
Eric Laurentc529cf62020-04-17 18:19:10 -07004207 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004208 return BAD_VALUE;
4209 }
jiabin0a488932020-08-07 17:32:40 -07004210 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004211 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004212 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4213 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004214 return status;
4215 }
4216
4217 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004218
4219 bool forceVolumeReeval = false;
4220 // FIXME: workaround for truncated touch sounds
4221 // to be removed when the problem is handled by system UI
4222 uint32_t delayMs = 0;
4223 if (strategy == mCommunnicationStrategy) {
4224 forceVolumeReeval = true;
4225 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4226 updateInputRouting();
4227 }
4228 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004229
4230 return NO_ERROR;
4231}
4232
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004233void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4234 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004235{
4236 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004237 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004238 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004239 // Only apply special touch sound delay once
4240 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004241 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004242 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004243 for (size_t i = 0; i < mOutputs.size(); i++) {
4244 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4245 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004246 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4247 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004248 // As done in setDeviceConnectionState, we could also fix default device issue by
4249 // preventing the force re-routing in case of default dev that distinguishes on address.
4250 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004251 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004252 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004253 // If the device is using preferred mixer attributes, the output need to reopen
4254 // with default configuration when the new selected devices are different from
4255 // current routing devices.
4256 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4257 continue;
4258 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304259
4260 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4261 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004262 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004263 // Only apply special touch sound delay once
4264 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004265 }
4266 if (forceVolumeReeval && !newDevices.isEmpty()) {
4267 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4268 }
4269 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004270 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004271 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004272}
4273
Eric Laurent2517af32020-11-25 15:31:27 +01004274void AudioPolicyManager::updateInputRouting() {
4275 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304276 // Skip for hotword recording as the input device switch
4277 // is handled within sound trigger HAL
4278 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4279 continue;
4280 }
Eric Laurent2517af32020-11-25 15:31:27 +01004281 auto newDevice = getNewInputDevice(activeDesc);
4282 // Force new input selection if the new device can not be reached via current input
4283 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4284 setInputDevice(activeDesc->mIoHandle, newDevice);
4285 } else {
4286 closeInput(activeDesc->mIoHandle);
4287 }
4288 }
4289}
4290
Paul Wang5d7cdb52022-11-22 09:45:06 +00004291status_t
4292AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4293 device_role_t role,
4294 const AudioDeviceTypeAddrVector &devices) {
4295 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4296 dumpAudioDeviceTypeAddrVector(devices).c_str());
4297
Eric Laurent78fedbf2023-03-09 14:40:44 +01004298 if (!areAllDevicesSupported(
4299 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004300 return BAD_VALUE;
4301 }
4302 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4303 if (status != NO_ERROR) {
4304 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4305 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4306 return status;
4307 }
4308
4309 checkForDeviceAndOutputChanges();
4310
4311 bool forceVolumeReeval = false;
4312 // TODO(b/263479999): workaround for truncated touch sounds
4313 // to be removed when the problem is handled by system UI
4314 uint32_t delayMs = 0;
4315 if (strategy == mCommunnicationStrategy) {
4316 forceVolumeReeval = true;
4317 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4318 updateInputRouting();
4319 }
4320 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4321
4322 return NO_ERROR;
4323}
4324
4325status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4326 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004327{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004328 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004329
Paul Wang5d7cdb52022-11-22 09:45:06 +00004330 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004331 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004332 ALOGW_IF(status != NAME_NOT_FOUND,
4333 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004334 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004335 return status;
4336 }
4337
4338 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004339
4340 bool forceVolumeReeval = false;
4341 // FIXME: workaround for truncated touch sounds
4342 // to be removed when the problem is handled by system UI
4343 uint32_t delayMs = 0;
4344 if (strategy == mCommunnicationStrategy) {
4345 forceVolumeReeval = true;
4346 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4347 updateInputRouting();
4348 }
4349 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004350
4351 return NO_ERROR;
4352}
4353
jiabin0a488932020-08-07 17:32:40 -07004354status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4355 device_role_t role,
4356 AudioDeviceTypeAddrVector &devices) {
4357 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004358}
4359
Jiabin Huang3b98d322020-09-03 17:54:16 +00004360status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4361 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4362 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4363 dumpAudioDeviceTypeAddrVector(devices).c_str());
4364
Mikhail Naganov55773032020-10-01 15:08:13 -07004365 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004366 return BAD_VALUE;
4367 }
4368 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4369 ALOGW_IF(status != NO_ERROR,
4370 "Engine could not set preferred devices %s for audio source %d role %d",
4371 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4372
4373 return status;
4374}
4375
4376status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4377 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4378 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4379 dumpAudioDeviceTypeAddrVector(devices).c_str());
4380
Mikhail Naganov55773032020-10-01 15:08:13 -07004381 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004382 return BAD_VALUE;
4383 }
4384 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4385 ALOGW_IF(status != NO_ERROR,
4386 "Engine could not add preferred devices %s for audio source %d role %d",
4387 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4388
Eric Laurent2517af32020-11-25 15:31:27 +01004389 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004390 return status;
4391}
4392
4393status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4394 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4395{
4396 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4397 dumpAudioDeviceTypeAddrVector(devices).c_str());
4398
Eric Laurent78fedbf2023-03-09 14:40:44 +01004399 if (!areAllDevicesSupported(
4400 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004401 return BAD_VALUE;
4402 }
4403
4404 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4405 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004406 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004407 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004408 if (status == NO_ERROR) {
4409 updateInputRouting();
4410 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004411 return status;
4412}
4413
4414status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4415 device_role_t role) {
4416 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4417
4418 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004419 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004420 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004421 if (status == NO_ERROR) {
4422 updateInputRouting();
4423 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004424 return status;
4425}
4426
4427status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4428 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4429 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4430}
4431
Oscar Azucena90e77632019-11-27 17:12:28 -08004432status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004433 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004434 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004435 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4436 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004437 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004438 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4439 if (status != NO_ERROR) {
4440 ALOGE("%s() could not set device affinity for userId %d",
4441 __FUNCTION__, userId);
4442 return status;
4443 }
4444
4445 // reevaluate outputs for all devices
4446 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004447 changeOutputDevicesMuteState(devices);
4448 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4449 true /* skipDelays */);
4450 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004451
4452 return NO_ERROR;
4453}
4454
4455status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004456 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004457 AudioDeviceTypeAddrVector devices;
4458 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004459 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4460 if (status != NO_ERROR) {
4461 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4462 __FUNCTION__, userId);
4463 return status;
4464 }
4465
4466 // reevaluate outputs for all devices
4467 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004468 changeOutputDevicesMuteState(devices);
4469 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4470 true /* skipDelays */);
4471 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004472
4473 return NO_ERROR;
4474}
4475
Andy Hungc29d82b2018-10-05 12:23:17 -07004476void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004477{
Andy Hungc29d82b2018-10-05 12:23:17 -07004478 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004479 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004480 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004481 std::string stateLiteral;
4482 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004483 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004484 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4485 "communications", "media", "record", "dock", "system",
4486 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4487 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4488 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004489 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4490 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4491 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4492 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4493 dst->append(" (MANUAL: ");
4494 dumpManualSurroundFormats(dst);
4495 dst->append(")");
4496 }
4497 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004498 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004499 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4500 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004501 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004502 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004503
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004504 dst->append("\n");
4505 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4506 dst->append("\n");
4507 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004508 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004509 mOutputs.dump(dst);
4510 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004511 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004512 mAudioPatches.dump(dst);
4513 mPolicyMixes.dump(dst);
4514 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004515
Kevin Rocardb99cc752019-03-21 20:52:24 -07004516 dst->appendFormat(" AllowedCapturePolicies:\n");
4517 for (auto& policy : mAllowedCapturePolicies) {
4518 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4519 }
4520
jiabina84c3d32022-12-02 18:59:55 +00004521 dst->appendFormat(" Preferred mixer audio configuration:\n");
4522 for (const auto it : mPreferredMixerAttrInfos) {
4523 dst->appendFormat(" - device port id: %d\n", it.first);
4524 for (const auto preferredMixerInfoIt : it.second) {
4525 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4526 preferredMixerInfoIt.second->dump(dst);
4527 }
4528 }
4529
François Gaffiec005e562018-11-06 15:04:49 +01004530 dst->appendFormat("\nPolicy Engine dump:\n");
4531 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004532
4533 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4534 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4535 dst->appendFormat(" - device type: %s, driving stream %d\n",
4536 dumpDeviceTypes({it.first}).c_str(),
4537 mEngine->getVolumeGroupForAttributes(it.second));
4538 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004539}
4540
4541status_t AudioPolicyManager::dump(int fd)
4542{
4543 String8 result;
4544 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004545 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004546 return NO_ERROR;
4547}
4548
Kevin Rocardb99cc752019-03-21 20:52:24 -07004549status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4550{
4551 mAllowedCapturePolicies[uid] = capturePolicy;
4552 return NO_ERROR;
4553}
4554
Eric Laurente552edb2014-03-10 17:42:56 -07004555// This function checks for the parameters which can be offloaded.
4556// This can be enhanced depending on the capability of the DSP and policy
4557// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004558audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004559{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004560 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004561 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004562 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004563 offloadInfo.format,
4564 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4565 offloadInfo.has_video);
4566
jiabin2b9d5a12021-12-10 01:06:29 +00004567 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004568 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004569 }
4570
4571 // See if there is a profile to support this.
4572 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004573 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004574 offloadInfo.sample_rate,
4575 offloadInfo.format,
4576 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004577 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4578 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004579 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4580 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4581 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004582 if (profile == nullptr) {
4583 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4584 }
4585 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4586 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4587 }
4588 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004589}
4590
Michael Chana94fbb22018-04-24 14:31:19 +10004591bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4592 const audio_attributes_t& attributes) {
4593 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004594 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004595 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4596 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004597 config.sample_rate,
4598 config.format,
4599 config.channel_mask,
4600 output_flags,
4601 true /* directOnly */);
4602 ALOGV("%s() profile %sfound with name: %s, "
4603 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4604 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004605 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004606 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004607
4608 // also try the MSD module if compatible profile not found
4609 if (profile == nullptr) {
4610 profile = getMsdProfileForOutput(outputDevices,
4611 config.sample_rate,
4612 config.format,
4613 config.channel_mask,
4614 output_flags,
4615 true /* directOnly */);
4616 ALOGV("%s() MSD profile %sfound with name: %s, "
4617 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4618 __FUNCTION__, profile != 0 ? "" : "NOT ",
4619 (profile != 0 ? profile->getTagName().c_str() : "null"),
4620 config.sample_rate, config.format, config.channel_mask, output_flags);
4621 }
4622 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004623}
4624
jiabin2b9d5a12021-12-10 01:06:29 +00004625bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4626 bool durationIgnored) {
4627 if (mMasterMono) {
4628 return false; // no offloading if mono is set.
4629 }
4630
4631 // Check if offload has been disabled
4632 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4633 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4634 return false;
4635 }
4636
4637 // Check if stream type is music, then only allow offload as of now.
4638 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4639 {
4640 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4641 return false;
4642 }
4643
4644 //TODO: enable audio offloading with video when ready
4645 const bool allowOffloadWithVideo =
4646 property_get_bool("audio.offload.video", false /* default_value */);
4647 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4648 ALOGV("%s: has_video == true, returning false", __func__);
4649 return false;
4650 }
4651
4652 //If duration is less than minimum value defined in property, return false
4653 const int min_duration_secs = property_get_int32(
4654 "audio.offload.min.duration.secs", -1 /* default_value */);
4655 if (!durationIgnored) {
4656 if (min_duration_secs >= 0) {
4657 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4658 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4659 __func__, min_duration_secs);
4660 return false;
4661 }
4662 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4663 ALOGV("%s: Offload denied by duration < default min(=%u)",
4664 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4665 return false;
4666 }
4667 }
4668
4669 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4670 // creating an offloaded track and tearing it down immediately after start when audioflinger
4671 // detects there is an active non offloadable effect.
4672 // FIXME: We should check the audio session here but we do not have it in this context.
4673 // This may prevent offloading in rare situations where effects are left active by apps
4674 // in the background.
4675 if (mEffects.isNonOffloadableEffectEnabled()) {
4676 return false;
4677 }
4678
4679 return true;
4680}
4681
4682audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4683 const audio_config_t *config) {
4684 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4685 offloadInfo.format = config->format;
4686 offloadInfo.sample_rate = config->sample_rate;
4687 offloadInfo.channel_mask = config->channel_mask;
4688 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4689 offloadInfo.has_video = false;
4690 offloadInfo.is_streaming = false;
4691 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4692
4693 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4694 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4695 audio_flags_to_audio_output_flags(attr->flags, &flags);
4696 // only retain flags that will drive compressed offload or passthrough
4697 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4698 if (offloadPossible) {
4699 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4700 }
4701 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4702
Dorin Drimusfae3c642022-03-17 18:36:30 +01004703 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004704 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004705 DeviceVector outputDevices = engineOutputDevices;
4706 // the MSD module checks for different conditions and output devices
4707 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4708 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4709 continue;
4710 }
4711 outputDevices = getMsdAudioOutDevices();
4712 }
jiabin2b9d5a12021-12-10 01:06:29 +00004713 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004714 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004715 config->sample_rate, nullptr /*updatedSamplingRate*/,
4716 config->format, nullptr /*updatedFormat*/,
4717 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004718 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004719 continue;
4720 }
4721 // reject profiles not corresponding to a device currently available
4722 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4723 continue;
4724 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004725 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4726 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004727 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004728 != AUDIO_DIRECT_NOT_SUPPORTED) {
4729 // Already reports offload gapless supported. No need to report offload support.
4730 continue;
4731 }
4732 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4733 != AUDIO_OUTPUT_FLAG_NONE) {
4734 // If offload gapless is reported, no need to report offload support.
4735 directMode = (audio_direct_mode_t) ((directMode &
4736 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4737 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4738 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004739 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004740 }
4741 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004742 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004743 }
4744 }
4745 }
4746 return directMode;
4747}
4748
Dorin Drimusf2196d82022-01-03 12:11:18 +01004749status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4750 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004751 if (mEffects.isNonOffloadableEffectEnabled()) {
4752 return OK;
4753 }
jiabinf1c73972022-04-14 16:28:52 -07004754 DeviceVector devices;
4755 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004756 if (status != OK) {
4757 return status;
4758 }
4759 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4760 if (devices.empty()) {
4761 return OK; // no output devices for the attributes
4762 }
jiabinf1c73972022-04-14 16:28:52 -07004763 return getProfilesForDevices(devices, audioProfilesVector,
4764 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004765}
4766
jiabina84c3d32022-12-02 18:59:55 +00004767status_t AudioPolicyManager::getSupportedMixerAttributes(
4768 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4769 ALOGV("%s, portId=%d", __func__, portId);
4770 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4771 if (deviceDescriptor == nullptr) {
4772 ALOGE("%s the requested device is currently unavailable", __func__);
4773 return BAD_VALUE;
4774 }
jiabin96daffc2023-05-11 17:51:55 +00004775 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4776 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4777 deviceDescriptor->type());
4778 return BAD_VALUE;
4779 }
jiabina84c3d32022-12-02 18:59:55 +00004780 for (const auto& hwModule : mHwModules) {
4781 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4782 if (curProfile->supportsDevice(deviceDescriptor)) {
4783 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4784 }
4785 }
4786 }
4787 return NO_ERROR;
4788}
4789
4790status_t AudioPolicyManager::setPreferredMixerAttributes(
4791 const audio_attributes_t *attr,
4792 audio_port_handle_t portId,
4793 uid_t uid,
4794 const audio_mixer_attributes_t *mixerAttributes) {
4795 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4796 "mixerBehavior=%d}, uid=%d, portId=%u",
4797 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4798 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4799 mixerAttributes->mixer_behavior, uid, portId);
4800 if (attr->usage != AUDIO_USAGE_MEDIA) {
4801 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4802 return BAD_VALUE;
4803 }
4804 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4805 if (deviceDescriptor == nullptr) {
4806 ALOGE("%s the requested device is currently unavailable", __func__);
4807 return BAD_VALUE;
4808 }
4809 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4810 ALOGE("%s(%d), type=%d, is not a usb output device",
4811 __func__, portId, deviceDescriptor->type());
4812 return BAD_VALUE;
4813 }
4814
4815 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4816 audio_flags_to_audio_output_flags(attr->flags, &flags);
4817 flags = (audio_output_flags_t) (flags |
4818 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4819 sp<IOProfile> profile = nullptr;
4820 DeviceVector devices(deviceDescriptor);
4821 for (const auto& hwModule : mHwModules) {
4822 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4823 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004824 && curProfile->getCompatibilityScore(
4825 devices,
4826 mixerAttributes->config.sample_rate,
4827 nullptr /*updatedSamplingRate*/,
4828 mixerAttributes->config.format,
4829 nullptr /*updatedFormat*/,
4830 mixerAttributes->config.channel_mask,
4831 nullptr /*updatedChannelMask*/,
4832 flags,
4833 false /*exactMatchRequiredForInputFlags*/)
4834 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004835 profile = curProfile;
4836 break;
4837 }
4838 }
4839 }
4840 if (profile == nullptr) {
4841 ALOGE("%s, there is no compatible profile found", __func__);
4842 return BAD_VALUE;
4843 }
4844
4845 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4846 sp<PreferredMixerAttributesInfo>::make(
4847 uid, portId, profile, flags, *mixerAttributes);
4848 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4849 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4850
4851 // If 1) there is any client from the preferred mixer configuration owner that is currently
4852 // active and matches the strategy and 2) current output is on the preferred device and the
4853 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4854 // configuration.
4855 std::vector<audio_io_handle_t> outputsToReopen;
4856 for (size_t i = 0; i < mOutputs.size(); i++) {
4857 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004858 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4859 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004860 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004861 } else {
4862 for (const auto &client: output->getActiveClients()) {
4863 if (client->uid() == uid && client->strategy() == strategy) {
4864 client->setIsInvalid();
4865 outputsToReopen.push_back(output->mIoHandle);
4866 }
jiabina84c3d32022-12-02 18:59:55 +00004867 }
4868 }
4869 }
4870 }
4871 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4872 config.sample_rate = mixerAttributes->config.sample_rate;
4873 config.channel_mask = mixerAttributes->config.channel_mask;
4874 config.format = mixerAttributes->config.format;
4875 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004876 sp<SwAudioOutputDescriptor> desc =
4877 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4878 if (desc == nullptr) {
4879 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4880 continue;
4881 }
jiabin220eea12024-05-17 17:55:20 +00004882 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004883 }
4884
4885 return NO_ERROR;
4886}
4887
4888sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004889 audio_port_handle_t devicePortId,
4890 product_strategy_t strategy,
4891 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004892 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4893 if (it == mPreferredMixerAttrInfos.end()) {
4894 return nullptr;
4895 }
jiabind9a58d32023-06-01 17:57:30 +00004896 if (activeBitPerfectPreferred) {
4897 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004898 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004899 return info;
4900 }
4901 }
jiabina84c3d32022-12-02 18:59:55 +00004902 }
jiabind9a58d32023-06-01 17:57:30 +00004903 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4904 return strategyMatchedMixerAttrInfoIt == it->second.end()
4905 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004906}
4907
4908status_t AudioPolicyManager::getPreferredMixerAttributes(
4909 const audio_attributes_t *attr,
4910 audio_port_handle_t portId,
4911 audio_mixer_attributes_t* mixerAttributes) {
4912 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4913 portId, mEngine->getProductStrategyForAttributes(*attr));
4914 if (info == nullptr) {
4915 return NAME_NOT_FOUND;
4916 }
4917 *mixerAttributes = info->getMixerAttributes();
4918 return NO_ERROR;
4919}
4920
4921status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4922 audio_port_handle_t portId,
4923 uid_t uid) {
4924 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4925 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4926 if (preferredMixerAttrInfo == nullptr) {
4927 return NAME_NOT_FOUND;
4928 }
4929 if (preferredMixerAttrInfo->getUid() != uid) {
4930 ALOGE("%s, requested uid=%d, owned uid=%d",
4931 __func__, uid, preferredMixerAttrInfo->getUid());
4932 return PERMISSION_DENIED;
4933 }
4934 mPreferredMixerAttrInfos[portId].erase(strategy);
4935 if (mPreferredMixerAttrInfos[portId].empty()) {
4936 mPreferredMixerAttrInfos.erase(portId);
4937 }
4938
4939 // Reconfig existing output
4940 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4941 for (size_t i = 0; i < mOutputs.size(); i++) {
4942 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4943 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4944 }
4945 }
4946 for (const auto output : potentialOutputsToReopen) {
4947 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4948 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4949 preferredMixerAttrInfo->getFlags())) {
4950 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4951 }
4952 }
4953 return NO_ERROR;
4954}
4955
Eric Laurent6a94d692014-05-20 11:18:06 -07004956status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4957 audio_port_type_t type,
4958 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004959 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004960 unsigned int *generation)
4961{
jiabin19cdba52020-11-24 11:28:58 -08004962 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4963 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004964 return BAD_VALUE;
4965 }
4966 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004967 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004968 *num_ports = 0;
4969 }
4970
4971 size_t portsWritten = 0;
4972 size_t portsMax = *num_ports;
4973 *num_ports = 0;
4974 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004975 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4976 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004978 for (const auto& dev : mAvailableOutputDevices) {
4979 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004980 continue;
4981 }
4982 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004983 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004984 }
4985 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004987 }
4988 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004989 for (const auto& dev : mAvailableInputDevices) {
4990 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004991 continue;
4992 }
4993 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004994 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004995 }
4996 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 }
4999 }
5000 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5001 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5002 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5003 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5004 }
5005 *num_ports += mInputs.size();
5006 }
5007 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005008 size_t numOutputs = 0;
5009 for (size_t i = 0; i < mOutputs.size(); i++) {
5010 if (!mOutputs[i]->isDuplicated()) {
5011 numOutputs++;
5012 if (portsWritten < portsMax) {
5013 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5014 }
5015 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 }
Eric Laurent84c70242014-06-23 08:46:27 -07005017 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005018 }
5019 }
jiabina84c3d32022-12-02 18:59:55 +00005020
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005022 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005023 return NO_ERROR;
5024}
5025
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005026status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5027 std::vector<media::AudioPortFw>* _aidl_return) {
5028 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5029 audio_port_v7 port;
5030 dev->toAudioPort(&port);
5031 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5032 _aidl_return->push_back(std::move(aidlPort));
5033 return OK;
5034 };
5035
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005036 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005037 for (const auto& dev : module->getDeclaredDevices()) {
5038 if (role == media::AudioPortRole::NONE ||
5039 ((role == media::AudioPortRole::SOURCE)
5040 == audio_is_input_device(dev->type()))) {
5041 RETURN_STATUS_IF_ERROR(pushPort(dev));
5042 }
5043 }
5044 }
5045 return OK;
5046}
5047
jiabin19cdba52020-11-24 11:28:58 -08005048status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005049{
Eric Laurent99fcae42018-05-17 16:59:18 -07005050 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5051 return BAD_VALUE;
5052 }
5053 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5054 if (dev != 0) {
5055 dev->toAudioPort(port);
5056 return NO_ERROR;
5057 }
5058 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5059 if (dev != 0) {
5060 dev->toAudioPort(port);
5061 return NO_ERROR;
5062 }
5063 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5064 if (out != 0) {
5065 out->toAudioPort(port);
5066 return NO_ERROR;
5067 }
5068 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5069 if (in != 0) {
5070 in->toAudioPort(port);
5071 return NO_ERROR;
5072 }
5073 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005074}
5075
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005076status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5077 audio_patch_handle_t *handle,
5078 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005079{
François Gaffieafd4cea2019-11-18 15:50:22 +01005080 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005081 if (handle == NULL || patch == NULL) {
5082 return BAD_VALUE;
5083 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005084 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005085 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005086 return BAD_VALUE;
5087 }
5088 // only one source per audio patch supported for now
5089 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005090 return INVALID_OPERATION;
5091 }
Eric Laurent874c42872014-08-08 15:13:39 -07005092 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005093 return INVALID_OPERATION;
5094 }
Eric Laurent874c42872014-08-08 15:13:39 -07005095 for (size_t i = 0; i < patch->num_sinks; i++) {
5096 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5097 return INVALID_OPERATION;
5098 }
5099 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005100
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005101 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5102 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5103 if (srcDevice == nullptr || sinkDevice == nullptr) {
5104 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5105 return BAD_VALUE;
5106 }
5107 ALOGV("%s between source %s and sink %s", __func__,
5108 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5109 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5110 // Default attributes, default volume priority, not to infer with non raw audio patches.
5111 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5112 const struct audio_port_config *source = &patch->sources[0];
5113 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005114 new SourceClientDescriptor(
5115 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5116 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005117 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005118 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005119
5120 status_t status =
5121 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5122
5123 if (status != NO_ERROR) {
5124 return INVALID_OPERATION;
5125 }
5126 mAudioSources.add(portId, sourceDesc);
5127 return NO_ERROR;
5128}
5129
5130status_t AudioPolicyManager::connectAudioSourceToSink(
5131 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5132 const struct audio_patch *patch,
5133 audio_patch_handle_t &handle,
5134 uid_t uid, uint32_t delayMs)
5135{
5136 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5137 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5138 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5139 return INVALID_OPERATION;
5140 }
5141 sourceDesc->connect(handle, sinkDevice);
5142 if (isMsdPatch(handle)) {
5143 return NO_ERROR;
5144 }
5145 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5146 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5147 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5148 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5149 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5150 goto FailurePatchAdded;
5151 }
5152 status = swOutput->start();
5153 if (status != NO_ERROR) {
5154 goto FailureSourceAdded;
5155 }
5156 swOutput->addClient(sourceDesc);
5157 status = startSource(swOutput, sourceDesc, &delayMs);
5158 if (status != NO_ERROR) {
5159 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5160 goto FailureSourceActive;
5161 }
5162 if (delayMs != 0) {
5163 usleep(delayMs * 1000);
5164 }
5165 return NO_ERROR;
5166
5167FailureSourceActive:
5168 swOutput->stop();
5169 releaseOutput(sourceDesc->portId());
5170FailureSourceAdded:
5171 sourceDesc->setSwOutput(nullptr);
5172FailurePatchAdded:
5173 releaseAudioPatchInternal(handle);
5174 return INVALID_OPERATION;
5175}
5176
5177status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5178 audio_patch_handle_t *handle,
5179 uid_t uid, uint32_t delayMs,
5180 const sp<SourceClientDescriptor>& sourceDesc)
5181{
5182 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005183 sp<AudioPatch> patchDesc;
5184 ssize_t index = mAudioPatches.indexOfKey(*handle);
5185
François Gaffieafd4cea2019-11-18 15:50:22 +01005186 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5187 patch->sources[0].role,
5188 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005189#if LOG_NDEBUG == 0
5190 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005191 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5192 patch->sinks[i].role,
5193 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005194 }
5195#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005196
5197 if (index >= 0) {
5198 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005199 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5200 __func__, mUidCached, patchDesc->getUid(), uid);
5201 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005202 return INVALID_OPERATION;
5203 }
5204 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005205 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005206 }
5207
5208 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005209 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005211 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005212 return BAD_VALUE;
5213 }
Eric Laurent84c70242014-06-23 08:46:27 -07005214 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5215 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005216 if (patchDesc != 0) {
5217 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005218 ALOGV("%s source id differs for patch current id %d new id %d",
5219 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005220 return BAD_VALUE;
5221 }
5222 }
Eric Laurent874c42872014-08-08 15:13:39 -07005223 DeviceVector devices;
5224 for (size_t i = 0; i < patch->num_sinks; i++) {
5225 // Only support mix to devices connection
5226 // TODO add support for mix to mix connection
5227 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005228 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005229 return INVALID_OPERATION;
5230 }
5231 sp<DeviceDescriptor> devDesc =
5232 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5233 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005234 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005235 return BAD_VALUE;
5236 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005237
jiabin66acc432024-02-06 00:57:36 +00005238 if (outputDesc->mProfile->getCompatibilityScore(
5239 DeviceVector(devDesc),
5240 patch->sources[0].sample_rate,
5241 nullptr, // updatedSamplingRate
5242 patch->sources[0].format,
5243 nullptr, // updatedFormat
5244 patch->sources[0].channel_mask,
5245 nullptr, // updatedChannelMask
5246 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005247 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005248 return INVALID_OPERATION;
5249 }
5250 devices.add(devDesc);
5251 }
5252 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 return INVALID_OPERATION;
5254 }
Eric Laurent874c42872014-08-08 15:13:39 -07005255
Eric Laurent6a94d692014-05-20 11:18:06 -07005256 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005257 ALOGV("%s setting device %s on output %d",
5258 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305259 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005260 index = mAudioPatches.indexOfKey(*handle);
5261 if (index >= 0) {
5262 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005263 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005264 }
5265 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005266 patchDesc->setUid(uid);
5267 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005268 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005269 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 return INVALID_OPERATION;
5271 }
5272 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5273 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5274 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005275 // only one sink supported when connecting an input device to a mix
5276 if (patch->num_sinks > 1) {
5277 return INVALID_OPERATION;
5278 }
François Gaffie53615e22015-03-19 09:24:12 +01005279 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 if (inputDesc == NULL) {
5281 return BAD_VALUE;
5282 }
5283 if (patchDesc != 0) {
5284 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5285 return BAD_VALUE;
5286 }
5287 }
François Gaffie11d30102018-11-02 16:09:09 +01005288 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005290 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005291 return BAD_VALUE;
5292 }
5293
jiabin66acc432024-02-06 00:57:36 +00005294 if (inputDesc->mProfile->getCompatibilityScore(
5295 DeviceVector(device),
5296 patch->sinks[0].sample_rate,
5297 nullptr, /*updatedSampleRate*/
5298 patch->sinks[0].format,
5299 nullptr, /*updatedFormat*/
5300 patch->sinks[0].channel_mask,
5301 nullptr, /*updatedChannelMask*/
5302 // FIXME for the parameter type,
5303 // and the NONE
5304 (audio_output_flags_t)
5305 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005306 return INVALID_OPERATION;
5307 }
5308 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005309 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005310 device->toString().c_str(), inputDesc->mIoHandle);
5311 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005312 index = mAudioPatches.indexOfKey(*handle);
5313 if (index >= 0) {
5314 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005315 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005316 }
5317 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005318 patchDesc->setUid(uid);
5319 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005320 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005321 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 return INVALID_OPERATION;
5323 }
5324 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5325 // device to device connection
5326 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005327 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005328 return BAD_VALUE;
5329 }
5330 }
François Gaffie11d30102018-11-02 16:09:09 +01005331 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005332 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005333 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005334 return BAD_VALUE;
5335 }
Eric Laurent874c42872014-08-08 15:13:39 -07005336
Eric Laurent6a94d692014-05-20 11:18:06 -07005337 //update source and sink with our own data as the data passed in the patch may
5338 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005339 PatchBuilder patchBuilder;
5340 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005341
5342 // if first sink is to MSD, establish single MSD patch
5343 if (getMsdAudioOutDevices().contains(
5344 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5345 ALOGV("%s patching to MSD", __FUNCTION__);
5346 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5347 goto installPatch;
5348 }
5349
François Gaffieafd4cea2019-11-18 15:50:22 +01005350 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5351 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005352
Eric Laurent874c42872014-08-08 15:13:39 -07005353 for (size_t i = 0; i < patch->num_sinks; i++) {
5354 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005355 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005356 return INVALID_OPERATION;
5357 }
François Gaffie11d30102018-11-02 16:09:09 +01005358 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005359 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005360 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005361 return BAD_VALUE;
5362 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005363 audio_port_config sinkPortConfig = {};
5364 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5365 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005366
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005367 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5368 // volume management purpose (tracking activity)
5369 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5370 // in config XML to reach the sink so that is can be declared as available.
5371 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005372 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005373 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005374 // take care of dynamic routing for SwOutput selection,
5375 audio_attributes_t attributes = sourceDesc->attributes();
5376 audio_stream_type_t stream = sourceDesc->stream();
5377 audio_attributes_t resultAttr;
5378 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5379 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005380 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5381 config.channel_mask =
5382 (audio_channel_mask_get_representation(sourceMask)
5383 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5384 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005385 config.format = sourceDesc->config().format;
5386 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5387 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5388 bool isRequestedDeviceForExclusiveUse = false;
5389 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005390 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005391 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005392 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5393 &stream, sourceDesc->uid(), &config, &flags,
5394 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005395 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005396 if (output == AUDIO_IO_HANDLE_NONE) {
5397 ALOGV("%s no output for device %s",
5398 __FUNCTION__, sinkDevice->toString().c_str());
5399 return INVALID_OPERATION;
5400 }
5401 outputDesc = mOutputs.valueFor(output);
5402 if (outputDesc->isDuplicated()) {
5403 ALOGE("%s output is duplicated", __func__);
5404 return INVALID_OPERATION;
5405 }
François Gaffie7e39df22022-04-26 12:48:49 +02005406 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5407 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005408 } else {
5409 // Same for "raw patches" aka created from createAudioPatch API
5410 SortedVector<audio_io_handle_t> outputs =
5411 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5412 // if the sink device is reachable via an opened output stream, request to
5413 // go via this output stream by adding a second source to the patch
5414 // description
5415 output = selectOutput(outputs);
5416 if (output == AUDIO_IO_HANDLE_NONE) {
5417 ALOGE("%s no output available for internal patch sink", __func__);
5418 return INVALID_OPERATION;
5419 }
5420 outputDesc = mOutputs.valueFor(output);
5421 if (outputDesc->isDuplicated()) {
5422 ALOGV("%s output for device %s is duplicated",
5423 __func__, sinkDevice->toString().c_str());
5424 return INVALID_OPERATION;
5425 }
François Gaffie7e39df22022-04-26 12:48:49 +02005426 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005427 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005428 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005429 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005430 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005431 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005432 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5433 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005434 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5435 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005436 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005437 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005438 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005439 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005440 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005441 return INVALID_OPERATION;
5442 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005443 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005444 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005445 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005446 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005447 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005448 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005449 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005450 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5451 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005452 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005453 }
Eric Laurent83b88082014-06-20 18:31:16 -07005454 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005455 }
5456 // TODO: check from routing capabilities in config file and other conflicting patches
5457
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005458installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005459 status_t status = installPatch(
5460 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005461 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005462 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 return INVALID_OPERATION;
5464 }
5465 } else {
5466 return BAD_VALUE;
5467 }
5468 } else {
5469 return BAD_VALUE;
5470 }
5471 return NO_ERROR;
5472}
5473
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005474status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005475{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005476 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005477 ssize_t index = mAudioPatches.indexOfKey(handle);
5478
5479 if (index < 0) {
5480 return BAD_VALUE;
5481 }
5482 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005483 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5484 __func__, mUidCached, patchDesc->getUid(), uid);
5485 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005486 return INVALID_OPERATION;
5487 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005488 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5489 for (size_t i = 0; i < mAudioSources.size(); i++) {
5490 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5491 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5492 portId = sourceDesc->portId();
5493 break;
5494 }
5495 }
5496 return portId != AUDIO_PORT_HANDLE_NONE ?
5497 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005498}
Eric Laurent6a94d692014-05-20 11:18:06 -07005499
François Gaffieafd4cea2019-11-18 15:50:22 +01005500status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005501 uint32_t delayMs,
5502 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005503{
5504 ALOGV("%s patch %d", __func__, handle);
5505 if (mAudioPatches.indexOfKey(handle) < 0) {
5506 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5507 return BAD_VALUE;
5508 }
5509 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005511 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005512 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005513 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005514 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005515 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005516 return BAD_VALUE;
5517 }
5518
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305519 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005520 getNewOutputDevices(outputDesc, true /*fromCache*/),
5521 true,
5522 0,
5523 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005524 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5525 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005526 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005527 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005528 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005529 return BAD_VALUE;
5530 }
5531 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005532 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005533 true,
5534 NULL);
5535 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005536 status_t status =
5537 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5538 ALOGV("%s patch panel returned %d patchHandle %d",
5539 __func__, status, patchDesc->getAfHandle());
5540 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005541 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005542 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005543 // SW or HW Bridge
5544 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5545 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005546 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005547 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5548 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5549 outputDesc = sourceDesc->swOutput().promote();
5550 }
5551 if (outputDesc == nullptr) {
5552 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5553 // releaseOutput has already called closeOutput in case of direct output
5554 return NO_ERROR;
5555 }
François Gaffie7e39df22022-04-26 12:48:49 +02005556 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005557 // While using a HwBridge, force reconsidering device only if not reusing an existing
5558 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005559 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005560 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5561 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5562 // Reconsider device only for cases:
5563 // 1 / Active Output
5564 // 2 / Inactive Output previously hosting HwBridge
5565 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5566 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5567 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305568 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005569 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5570 outputDesc->devices(),
5571 force,
5572 0,
5573 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005574 } else {
5575 return BAD_VALUE;
5576 }
5577 } else {
5578 return BAD_VALUE;
5579 }
5580 return NO_ERROR;
5581}
5582
5583status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5584 struct audio_patch *patches,
5585 unsigned int *generation)
5586{
François Gaffie53615e22015-03-19 09:24:12 +01005587 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005588 return BAD_VALUE;
5589 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005590 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005591 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005592}
5593
Eric Laurente1715a42014-05-20 11:30:42 -07005594status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005595{
Eric Laurente1715a42014-05-20 11:30:42 -07005596 ALOGV("setAudioPortConfig()");
5597
5598 if (config == NULL) {
5599 return BAD_VALUE;
5600 }
5601 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5602 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005603 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5604 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005605 }
5606
Eric Laurenta121f902014-06-03 13:32:54 -07005607 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005608 if (config->type == AUDIO_PORT_TYPE_MIX) {
5609 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005610 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005611 if (outputDesc == NULL) {
5612 return BAD_VALUE;
5613 }
Eric Laurent84c70242014-06-23 08:46:27 -07005614 ALOG_ASSERT(!outputDesc->isDuplicated(),
5615 "setAudioPortConfig() called on duplicated output %d",
5616 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005617 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005618 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005619 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005620 if (inputDesc == NULL) {
5621 return BAD_VALUE;
5622 }
Eric Laurenta121f902014-06-03 13:32:54 -07005623 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005624 } else {
5625 return BAD_VALUE;
5626 }
5627 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5628 sp<DeviceDescriptor> deviceDesc;
5629 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5630 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5631 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5632 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5633 } else {
5634 return BAD_VALUE;
5635 }
5636 if (deviceDesc == NULL) {
5637 return BAD_VALUE;
5638 }
Eric Laurenta121f902014-06-03 13:32:54 -07005639 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005640 } else {
5641 return BAD_VALUE;
5642 }
5643
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005644 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005645 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5646 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005647 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005648 audioPortConfig->toAudioPortConfig(&newConfig, config);
5649 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005650 }
Eric Laurenta121f902014-06-03 13:32:54 -07005651 if (status != NO_ERROR) {
5652 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005653 }
Eric Laurente1715a42014-05-20 11:30:42 -07005654
5655 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005656}
5657
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005658void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5659{
Eric Laurentd60560a2015-04-10 11:31:20 -07005660 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005661 clearAudioPatches(uid);
5662 clearSessionRoutes(uid);
5663}
5664
Eric Laurent6a94d692014-05-20 11:18:06 -07005665void AudioPolicyManager::clearAudioPatches(uid_t uid)
5666{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005667 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005668 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005669 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005670 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005671 }
5672 }
5673}
5674
François Gaffiec005e562018-11-06 15:04:49 +01005675void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005676{
François Gaffiec005e562018-11-06 15:04:49 +01005677 // Take the first attributes following the product strategy as it is used to retrieve the routed
5678 // device. All attributes wihin a strategy follows the same "routing strategy"
5679 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5680 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005681 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005682 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005683 for (size_t j = 0; j < mOutputs.size(); j++) {
5684 if (mOutputs.keyAt(j) == ouptutToSkip) {
5685 continue;
5686 }
5687 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005688 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005689 continue;
5690 }
5691 // If the default device for this strategy is on another output mix,
5692 // invalidate all tracks in this strategy to force re connection.
5693 // Otherwise select new device on the output mix.
5694 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005695 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005696 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005697 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005698 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005699 // If the device is using preferred mixer attributes, the output need to reopen
5700 // with default configuration when the new selected devices are different from
5701 // current routing devices.
5702 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5703 continue;
5704 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305705 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005706 }
5707 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005708 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005709}
5710
5711void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5712{
5713 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005714 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005715 for (size_t i = 0; i < mOutputs.size(); i++) {
5716 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005717 for (const auto& client : outputDesc->getClientIterable()) {
5718 if (client->hasPreferredDevice() && client->uid() == uid) {
5719 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005720 auto clientStrategy = client->strategy();
5721 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5722 end(affectedStrategies)) {
5723 continue;
5724 }
5725 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005726 }
5727 }
5728 }
5729 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005730 for (const auto& strategy : affectedStrategies) {
5731 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005732 }
5733
5734 // remove input routes associated with this uid
5735 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005736 for (size_t i = 0; i < mInputs.size(); i++) {
5737 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005738 for (const auto& client : inputDesc->getClientIterable()) {
5739 if (client->hasPreferredDevice() && client->uid() == uid) {
5740 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5741 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005742 }
5743 }
5744 }
5745 // reroute inputs if necessary
5746 SortedVector<audio_io_handle_t> inputsToClose;
5747 for (size_t i = 0; i < mInputs.size(); i++) {
5748 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005749 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005750 inputsToClose.add(inputDesc->mIoHandle);
5751 }
5752 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005753 for (const auto& input : inputsToClose) {
5754 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005755 }
5756}
5757
Eric Laurentd60560a2015-04-10 11:31:20 -07005758void AudioPolicyManager::clearAudioSources(uid_t uid)
5759{
5760 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005761 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5762 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005763 stopAudioSource(mAudioSources.keyAt(i));
5764 }
5765 }
5766}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005767
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005768status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5769 audio_io_handle_t *ioHandle,
5770 audio_devices_t *device)
5771{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005772 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5773 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005774 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005775 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5776 if (deviceDesc == nullptr) {
5777 return INVALID_OPERATION;
5778 }
5779 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005780
François Gaffiedf372692015-03-19 10:43:27 +01005781 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005782}
5783
Eric Laurentd60560a2015-04-10 11:31:20 -07005784status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005785 const audio_attributes_t *attributes,
5786 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005787 uid_t uid) {
5788 return startAudioSourceInternal(source, attributes, portId, uid,
David Li48b6a832024-07-01 13:14:10 +00005789 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurent963dbcc2024-06-20 12:34:15 +00005790}
5791
5792status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5793 const audio_attributes_t *attributes,
5794 audio_port_handle_t *portId,
David Li48b6a832024-07-01 13:14:10 +00005795 uid_t uid, bool internal, bool isCallRx,
5796 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005797{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005798 ALOGV("%s", __FUNCTION__);
5799 *portId = AUDIO_PORT_HANDLE_NONE;
5800
5801 if (source == NULL || attributes == NULL || portId == NULL) {
5802 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5803 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005804 return BAD_VALUE;
5805 }
5806
Eric Laurentd60560a2015-04-10 11:31:20 -07005807 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5808 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005809 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5810 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005811 return INVALID_OPERATION;
5812 }
5813
François Gaffie11d30102018-11-02 16:09:09 +01005814 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005815 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005816 String8(source->ext.device.address),
5817 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005818 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005819 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005820 return BAD_VALUE;
5821 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005822
jiabin4ef93452019-09-10 14:29:54 -07005823 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005824
François Gaffieaaac0fd2018-11-22 17:56:39 +01005825 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005826 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005827 mEngine->getStreamTypeForAttributes(*attributes),
5828 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005829 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005830
David Li48b6a832024-07-01 13:14:10 +00005831 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005832 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005833 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005834 }
5835 return status;
5836}
5837
David Li48b6a832024-07-01 13:14:10 +00005838status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5839 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005840{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005841 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005842
5843 // make sure we only have one patch per source.
5844 disconnectAudioSource(sourceDesc);
5845
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005846 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005847 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5848 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5849 sourceDesc->srcDevice()->type(),
5850 String8(sourceDesc->srcDevice()->address().c_str()),
5851 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005852 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005853 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005854 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005855 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005856 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5857 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5858 return INVALID_OPERATION;
5859 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005860 PatchBuilder patchBuilder;
5861 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5862 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005863
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005864 return connectAudioSourceToSink(
David Li48b6a832024-07-01 13:14:10 +00005865 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005866}
5867
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005868status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005869{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005870 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5871 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005872 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005873 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005874 return BAD_VALUE;
5875 }
5876 status_t status = disconnectAudioSource(sourceDesc);
5877
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005878 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005879 return status;
5880}
5881
Andy Hung2ddee192015-12-18 17:34:44 -08005882status_t AudioPolicyManager::setMasterMono(bool mono)
5883{
5884 if (mMasterMono == mono) {
5885 return NO_ERROR;
5886 }
5887 mMasterMono = mono;
5888 // if enabling mono we close all offloaded devices, which will invalidate the
5889 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5890 // for recreating the new AudioTrack as non-offloaded PCM.
5891 //
5892 // If disabling mono, we leave all tracks as is: we don't know which clients
5893 // and tracks are able to be recreated as offloaded. The next "song" should
5894 // play back offloaded.
5895 if (mMasterMono) {
5896 Vector<audio_io_handle_t> offloaded;
5897 for (size_t i = 0; i < mOutputs.size(); ++i) {
5898 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5899 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5900 offloaded.push(desc->mIoHandle);
5901 }
5902 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005903 for (const auto& handle : offloaded) {
5904 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005905 }
5906 }
5907 // update master mono for all remaining outputs
5908 for (size_t i = 0; i < mOutputs.size(); ++i) {
5909 updateMono(mOutputs.keyAt(i));
5910 }
5911 return NO_ERROR;
5912}
5913
5914status_t AudioPolicyManager::getMasterMono(bool *mono)
5915{
5916 *mono = mMasterMono;
5917 return NO_ERROR;
5918}
5919
Eric Laurentac9cef52017-06-09 15:46:26 -07005920float AudioPolicyManager::getStreamVolumeDB(
5921 audio_stream_type_t stream, int index, audio_devices_t device)
5922{
jiabin9a3361e2019-10-01 09:38:30 -07005923 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005924}
5925
jiabin81772902018-04-02 17:52:27 -07005926status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5927 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005928 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005929{
Kriti Dang6537def2021-03-02 13:46:59 +01005930 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5931 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005932 return BAD_VALUE;
5933 }
Kriti Dang6537def2021-03-02 13:46:59 +01005934 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5935 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005936
5937 size_t formatsWritten = 0;
5938 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005939
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005940 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005941 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5942 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005943 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005944 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005945 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005946 bool formatEnabled = true;
5947 switch (forceUse) {
5948 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005949 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005950 break;
5951 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5952 formatEnabled = false;
5953 break;
5954 default: // AUTO or ALWAYS => true
5955 break;
jiabin81772902018-04-02 17:52:27 -07005956 }
5957 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5958 }
jiabin81772902018-04-02 17:52:27 -07005959 }
5960 return NO_ERROR;
5961}
5962
Kriti Dang6537def2021-03-02 13:46:59 +01005963status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5964 audio_format_t *surroundFormats) {
5965 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5966 return BAD_VALUE;
5967 }
5968 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5969 __func__, *numSurroundFormats, surroundFormats);
5970
5971 size_t formatsWritten = 0;
5972 size_t formatsMax = *numSurroundFormats;
5973 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5974
5975 // Return formats from all device profiles that have already been resolved by
5976 // checkOutputsForDevice().
5977 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5978 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5979 audio_devices_t deviceType = device->type();
5980 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5981 // returns formats reported by HDMI devices.
5982 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5983 continue;
5984 }
5985 // Formats reported by sink devices
5986 std::unordered_set<audio_format_t> formatset;
5987 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5988 formatset.insert(it->second.begin(), it->second.end());
5989 }
5990
5991 // Formats hard-coded in the in policy configuration file (if any).
5992 FormatVector encodedFormats = device->encodedFormats();
5993 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5994 // Filter the formats which are supported by the vendor hardware.
5995 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005996 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005997 formats.insert(*it);
5998 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005999 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006000 if (pair.second.count(*it) != 0) {
6001 formats.insert(pair.first);
6002 break;
6003 }
6004 }
6005 }
6006 }
6007 }
6008 *numSurroundFormats = formats.size();
6009 for (const auto& format: formats) {
6010 if (formatsWritten < formatsMax) {
6011 surroundFormats[formatsWritten++] = format;
6012 }
6013 }
6014 return NO_ERROR;
6015}
6016
jiabin81772902018-04-02 17:52:27 -07006017status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6018{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006019 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006020 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6021 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006022 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006023 return BAD_VALUE;
6024 }
6025
Mikhail Naganov100f0122018-11-29 11:22:16 -08006026 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6027 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006028 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006029 return INVALID_OPERATION;
6030 }
6031
Mikhail Naganov100f0122018-11-29 11:22:16 -08006032 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006033 return NO_ERROR;
6034 }
6035
Mikhail Naganov100f0122018-11-29 11:22:16 -08006036 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006037 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006038 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006039 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006040 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006041 }
6042 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006043 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006044 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006045 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006046 }
6047 }
6048
6049 sp<SwAudioOutputDescriptor> outputDesc;
6050 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006051 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6052 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006053 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6054 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006055 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006056 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006057 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6058 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6059 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006060 name.c_str(),
6061 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006062 if (status != NO_ERROR) {
6063 continue;
6064 }
6065 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6066 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6067 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006068 name.c_str(),
6069 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006070 profileUpdated |= (status == NO_ERROR);
6071 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006072 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006073 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006074 AUDIO_DEVICE_IN_HDMI);
6075 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6076 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006077 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006078 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006079 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6080 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6081 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006082 name.c_str(),
6083 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006084 if (status != NO_ERROR) {
6085 continue;
6086 }
6087 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6088 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6089 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006090 name.c_str(),
6091 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006092 profileUpdated |= (status == NO_ERROR);
6093 }
6094
jiabin81772902018-04-02 17:52:27 -07006095 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006096 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006097 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006098 }
6099
6100 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6101}
6102
Eric Laurent5ada82e2019-08-29 17:53:54 -07006103void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006104{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006105 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006106 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006107 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006108 }
6109}
6110
jiabin6012f912018-11-02 17:06:30 -07006111bool AudioPolicyManager::isHapticPlaybackSupported()
6112{
6113 for (const auto& hwModule : mHwModules) {
6114 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6115 for (const auto &outProfile : outputProfiles) {
6116 struct audio_port audioPort;
6117 outProfile->toAudioPort(&audioPort);
6118 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6119 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6120 return true;
6121 }
6122 }
6123 }
6124 }
6125 return false;
6126}
6127
Carter Hsu325a8eb2022-01-19 19:56:51 +08006128bool AudioPolicyManager::isUltrasoundSupported()
6129{
6130 bool hasUltrasoundOutput = false;
6131 bool hasUltrasoundInput = false;
6132 for (const auto& hwModule : mHwModules) {
6133 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6134 if (!hasUltrasoundOutput) {
6135 for (const auto &outProfile : outputProfiles) {
6136 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6137 hasUltrasoundOutput = true;
6138 break;
6139 }
6140 }
6141 }
6142
6143 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6144 if (!hasUltrasoundInput) {
6145 for (const auto &inputProfile : inputProfiles) {
6146 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6147 hasUltrasoundInput = true;
6148 break;
6149 }
6150 }
6151 }
6152
6153 if (hasUltrasoundOutput && hasUltrasoundInput)
6154 return true;
6155 }
6156 return false;
6157}
6158
Atneya Nair698f5ef2022-12-15 16:15:09 -08006159bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6160{
6161 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6162 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6163 for (const auto& hwModule : mHwModules) {
6164 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6165 for (const auto &inputProfile : inputProfiles) {
6166 if ((inputProfile->getFlags() & mask) == mask) {
6167 return true;
6168 }
6169 }
6170 }
6171 return false;
6172}
6173
Eric Laurent8340e672019-11-06 11:01:08 -08006174bool AudioPolicyManager::isCallScreenModeSupported()
6175{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006176 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006177}
6178
6179
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006180status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006181{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006182 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006183 if (!sourceDesc->isConnected()) {
6184 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6185 return NO_ERROR;
6186 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006187 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6188 if (swOutput != 0) {
6189 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006190 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006191 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006192 }
jiabinbce0c1d2020-10-05 11:20:18 -07006193 if (releaseOutput(sourceDesc->portId())) {
6194 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6195 // no need to release audio patch here but just return NO_ERROR.
6196 return NO_ERROR;
6197 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006198 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006199 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006200 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006201 // close Hwoutput and remove from mHwOutputs
6202 } else {
6203 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6204 }
6205 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006206 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006207 sourceDesc->disconnect();
6208 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006209}
6210
François Gaffiec005e562018-11-06 15:04:49 +01006211sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6212 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006213{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006214 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006215 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006216 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006217 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006218 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6219 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006220 source = sourceDesc;
6221 break;
6222 }
6223 }
6224 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006225}
6226
Eric Laurentb4f42a92022-01-17 17:37:31 +01006227bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006228 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006229 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006230{
6231 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6232 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006233 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006234 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006235 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6236 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6237 return false;
6238 }
6239 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6240 return false;
6241 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006242 }
6243
Eric Laurentd332bc82023-08-04 11:45:23 +02006244 // The caller can have the audio config criteria ignored by either passing a null ptr or
6245 // the AUDIO_CONFIG_INITIALIZER value.
6246 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006247 // some positional channel masks and PCM format and for stereo if low latency performance
6248 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006249
6250 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006251 static const bool stereo_spatialization_enabled =
6252 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006253 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006254 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006255 ? audio_channel_mask_contains_stereo(config->channel_mask)
6256 : audio_is_channel_mask_spatialized(config->channel_mask);
6257 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006258 return false;
6259 }
6260 if (!audio_is_linear_pcm(config->format)) {
6261 return false;
6262 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006263 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6264 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6265 return false;
6266 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006267 }
6268
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006269 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006270 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006271 if (profile == nullptr) {
6272 return false;
6273 }
6274
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006275 return true;
6276}
6277
Shunkai Yao57b93392024-04-26 04:12:21 +00006278// The Spatializer output is compatible with Haptic use cases if:
6279// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6280// with client if client haptic channel bits were set, or
6281// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6282// including the haptic bits or creating the HapticGenerator effect for same session.
6283bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6284 const audio_config_t* config, audio_session_t sessionId) const {
6285 const auto clientHapticChannel =
6286 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6287 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6288 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6289
6290 if (threadOutputHapticChannel) {
6291 // check format and sampleRate match if client haptic channel mask exist
6292 if (clientHapticChannel) {
6293 return mSpatializerOutput->getFormat() == config->format &&
6294 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6295 }
6296 return true;
6297 } else {
6298 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6299 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6300 // HapticGenerator effect for this session) are not supported.
6301 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006302 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006303 }
6304}
6305
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006306void AudioPolicyManager::checkVirtualizerClientRoutes() {
6307 std::set<audio_stream_type_t> streamsToInvalidate;
6308 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006309 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6310 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006311 audio_attributes_t attr = client->attributes();
6312 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6313 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6314 audio_config_base_t clientConfig = client->config();
6315 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006316 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006317 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006318 streamsToInvalidate.insert(client->stream());
6319 }
6320 }
6321 }
6322
jiabinc44b3462022-12-08 12:52:31 -08006323 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006324}
6325
Eric Laurente191d1b2022-04-15 11:59:25 +02006326
6327bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6328 const sp<SwAudioOutputDescriptor>& outputDesc) {
6329 if (outputDesc->isDuplicated()) {
6330 return false;
6331 }
6332 DeviceVector devices = outputDesc->supportedDevices();
6333 for (size_t i = 0; i < mOutputs.size(); i++) {
6334 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6335 if (desc == outputDesc || desc->isDuplicated()) {
6336 continue;
6337 }
6338 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6339 if (!sharedDevices.isEmpty()
6340 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6341 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6342 return false;
6343 }
6344 }
6345 return true;
6346}
6347
6348
Eric Laurentfa0f6742021-08-17 18:39:44 +02006349status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006350 const audio_attributes_t *attr,
6351 audio_io_handle_t *output) {
6352 *output = AUDIO_IO_HANDLE_NONE;
6353
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006354 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6355 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6356 audio_config_t *configPtr = nullptr;
6357 audio_config_t config;
6358 if (mixerConfig != nullptr) {
6359 config = audio_config_initializer(mixerConfig);
6360 configPtr = &config;
6361 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006362 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006363 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006364 return BAD_VALUE;
6365 }
6366
6367 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006368 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006369 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006370 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006371 return BAD_VALUE;
6372 }
6373
Eric Laurente191d1b2022-04-15 11:59:25 +02006374 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006375 for (size_t i = 0; i < mOutputs.size(); i++) {
6376 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006377 if (!desc->isDuplicated()
6378 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6379 spatializerOutputs.push_back(desc);
6380 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006381 }
6382 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006383 mSpatializerOutput.clear();
6384 bool outputsChanged = false;
6385 for (const auto& desc : spatializerOutputs) {
6386 if (desc->mProfile == profile
6387 && (configPtr == nullptr
6388 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6389 mSpatializerOutput = desc;
6390 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6391 } else {
6392 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6393 " and devices %s", __func__, desc->mIoHandle,
6394 configPtr != nullptr ? configPtr->channel_mask : 0,
6395 devices.toString().c_str());
6396 closeOutput(desc->mIoHandle);
6397 outputsChanged = true;
6398 }
Eric Laurent39095982021-08-24 18:29:27 +02006399 }
6400
Eric Laurente191d1b2022-04-15 11:59:25 +02006401 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006402 sp<SwAudioOutputDescriptor> desc =
6403 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006404 if (desc != nullptr) {
6405 mSpatializerOutput = desc;
6406 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006407 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006408 }
6409
6410 checkVirtualizerClientRoutes();
6411
Eric Laurente191d1b2022-04-15 11:59:25 +02006412 if (outputsChanged) {
6413 mPreviousOutputs = mOutputs;
6414 mpClientInterface->onAudioPortListUpdate();
6415 }
6416
6417 if (mSpatializerOutput == nullptr) {
6418 ALOGV("%s could not open spatializer output with requested config", __func__);
6419 return BAD_VALUE;
6420 }
Eric Laurent39095982021-08-24 18:29:27 +02006421 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006422 ALOGV("%s returning new spatializer output %d", __func__, *output);
6423 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006424}
6425
Eric Laurentfa0f6742021-08-17 18:39:44 +02006426status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6427 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006428 return INVALID_OPERATION;
6429 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006430 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006431 return BAD_VALUE;
6432 }
Eric Laurent39095982021-08-24 18:29:27 +02006433
Eric Laurente191d1b2022-04-15 11:59:25 +02006434 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6435 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6436 closeOutput(mSpatializerOutput->mIoHandle);
6437 //from now on mSpatializerOutput is null
6438 checkVirtualizerClientRoutes();
6439 }
Eric Laurent39095982021-08-24 18:29:27 +02006440
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006441 return NO_ERROR;
6442}
6443
Eric Laurente552edb2014-03-10 17:42:56 -07006444// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006445// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006446// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006447uint32_t AudioPolicyManager::nextAudioPortGeneration()
6448{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006449 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006450}
6451
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006452AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006453 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006454 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006455 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006456 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006457 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006458 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006459 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006460 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006461 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006462 mAudioPortGeneration(1),
6463 mBeaconMuteRefCount(0),
6464 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006465 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006466 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006467 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006468 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006469{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006470}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006471
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006472status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006473 if (mEngine == nullptr) {
6474 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006475 }
6476 mEngine->setObserver(this);
6477 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006478 if (status != NO_ERROR) {
6479 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6480 return status;
6481 }
François Gaffie2110e042015-03-24 08:41:51 +01006482
jiabin29230182023-04-04 21:02:36 +00006483 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6484 // at the end of this function.
6485 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006486 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6487 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6488
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006489 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006490 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006491 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006492
Eric Laurent3a4311c2014-03-17 12:00:47 -07006493 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006494 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6495 defaultOutputDevice == nullptr ||
6496 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6497 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6498 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006499 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006500 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006501 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006502
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006503 // Silence ALOGV statements
6504 property_set("log.tag." LOG_TAG, "D");
6505
Eric Laurente552edb2014-03-10 17:42:56 -07006506 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006507 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006508}
6509
Eric Laurente0720872014-03-11 09:30:41 -07006510AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006511{
Eric Laurente552edb2014-03-10 17:42:56 -07006512 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006513 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006514 }
6515 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006516 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006517 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006518 mAvailableOutputDevices.clear();
6519 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006520 mOutputs.clear();
6521 mInputs.clear();
6522 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006523 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006524 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006525}
6526
Eric Laurente0720872014-03-11 09:30:41 -07006527status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006528{
Eric Laurent87ffa392015-05-22 10:32:38 -07006529 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006530}
6531
Eric Laurente552edb2014-03-10 17:42:56 -07006532// ---
6533
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006534void AudioPolicyManager::onNewAudioModulesAvailable()
6535{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006536 DeviceVector newDevices;
6537 onNewAudioModulesAvailableInt(&newDevices);
6538 if (!newDevices.empty()) {
6539 nextAudioPortGeneration();
6540 mpClientInterface->onAudioPortListUpdate();
6541 }
6542}
6543
6544void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6545{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006546 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006547 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6548 continue;
6549 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006550 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006551 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6552 handle != AUDIO_MODULE_HANDLE_NONE) {
6553 hwModule->setHandle(handle);
6554 } else {
6555 ALOGW("could not load HW module %s", hwModule->getName());
6556 continue;
6557 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006558 }
6559 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006560 // open all output streams needed to access attached devices.
6561 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006562 // This also validates mAvailableOutputDevices list
6563 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6564 if (!outProfile->canOpenNewIo()) {
6565 ALOGE("Invalid Output profile max open count %u for profile %s",
6566 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6567 continue;
6568 }
6569 if (!outProfile->hasSupportedDevices()) {
6570 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6571 continue;
6572 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006573 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6574 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006575 mTtsOutputAvailable = true;
6576 }
6577
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006578 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006579 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006580 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006581 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6582 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006583 } else {
6584 // choose first device present in profile's SupportedDevices also part of
6585 // mAvailableOutputDevices.
6586 if (availProfileDevices.isEmpty()) {
6587 continue;
6588 }
6589 supportedDevice = availProfileDevices.itemAt(0);
6590 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006591 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006592 continue;
6593 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306594
6595 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6596 && availProfileDevices.areAllDevicesAttached()) {
6597 ALOGV("%s skip opening output for mmap profile %s", __func__,
6598 outProfile->getTagName().c_str());
6599 continue;
6600 }
6601
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006602 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6603 mpClientInterface);
6604 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006605 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006606 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6607 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006608 AUDIO_STREAM_DEFAULT,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006609 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006610 if (status != NO_ERROR) {
6611 ALOGW("Cannot open output stream for devices %s on hw module %s",
6612 supportedDevice->toString().c_str(), hwModule->getName());
6613 continue;
6614 }
6615 for (const auto &device : availProfileDevices) {
6616 // give a valid ID to an attached device once confirmed it is reachable
6617 if (!device->isAttached()) {
6618 device->attach(hwModule);
6619 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006620 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006621 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006622 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6623 }
6624 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006625 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006626 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6627 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006628 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006629 }
Eric Laurent39095982021-08-24 18:29:27 +02006630 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006631 outputDesc->close();
6632 } else {
6633 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306634 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006635 DeviceVector(supportedDevice),
6636 true,
6637 0,
6638 NULL);
6639 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006640 }
6641 // open input streams needed to access attached devices to validate
6642 // mAvailableInputDevices list
6643 for (const auto& inProfile : hwModule->getInputProfiles()) {
6644 if (!inProfile->canOpenNewIo()) {
6645 ALOGE("Invalid Input profile max open count %u for profile %s",
6646 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6647 continue;
6648 }
6649 if (!inProfile->hasSupportedDevices()) {
6650 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6651 continue;
6652 }
6653 // chose first device present in profile's SupportedDevices also part of
6654 // available input devices
6655 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006656 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006657 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006658 ALOGV("%s: Input device list is empty! for profile %s",
6659 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006660 continue;
6661 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306662
6663 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6664 && availProfileDevices.areAllDevicesAttached()) {
6665 ALOGV("%s skip opening input for mmap profile %s", __func__,
6666 inProfile->getTagName().c_str());
6667 continue;
6668 }
6669
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006670 sp<AudioInputDescriptor> inputDesc =
6671 new AudioInputDescriptor(inProfile, mpClientInterface);
6672
6673 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6674 status_t status = inputDesc->open(nullptr,
6675 availProfileDevices.itemAt(0),
6676 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006677 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006678 &input);
6679 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306680 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6681 __func__, availProfileDevices.toString().c_str(),
6682 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006683 continue;
6684 }
6685 for (const auto &device : availProfileDevices) {
6686 // give a valid ID to an attached device once confirmed it is reachable
6687 if (!device->isAttached()) {
6688 device->attach(hwModule);
6689 device->importAudioPortAndPickAudioProfile(inProfile, true);
6690 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006691 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006692 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6693 }
6694 }
6695 inputDesc->close();
6696 }
6697 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006698
6699 // Check if spatializer outputs can be closed until used.
6700 // mOutputs vector never contains duplicated outputs at this point.
6701 std::vector<audio_io_handle_t> outputsClosed;
6702 for (size_t i = 0; i < mOutputs.size(); i++) {
6703 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6704 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6705 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6706 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006707 nextAudioPortGeneration();
6708 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6709 if (index >= 0) {
6710 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6711 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6712 patchDesc->getAfHandle(), 0);
6713 mAudioPatches.removeItemsAt(index);
6714 mpClientInterface->onAudioPatchListUpdate();
6715 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006716 desc->close();
6717 }
6718 }
6719 for (auto output : outputsClosed) {
6720 removeOutput(output);
6721 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006722}
6723
Eric Laurent98e38192018-02-15 18:31:53 -08006724void AudioPolicyManager::addOutput(audio_io_handle_t output,
6725 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006726{
Eric Laurent1c333e22014-05-20 10:48:17 -07006727 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006728 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006729 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006730 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006731 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006732}
6733
François Gaffie53615e22015-03-19 09:24:12 +01006734void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6735{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006736 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6737 ALOGV("%s: removing primary output", __func__);
6738 mPrimaryOutput = nullptr;
6739 }
François Gaffie53615e22015-03-19 09:24:12 +01006740 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006741 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006742}
6743
Eric Laurent98e38192018-02-15 18:31:53 -08006744void AudioPolicyManager::addInput(audio_io_handle_t input,
6745 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006746{
Eric Laurent1c333e22014-05-20 10:48:17 -07006747 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006748 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006749}
Eric Laurente552edb2014-03-10 17:42:56 -07006750
François Gaffie11d30102018-11-02 16:09:09 +01006751status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006752 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006753 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006754{
François Gaffie11d30102018-11-02 16:09:09 +01006755 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006756 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006757 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006758
François Gaffie11d30102018-11-02 16:09:09 +01006759 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006760 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006761 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006762 }
Eric Laurente552edb2014-03-10 17:42:56 -07006763
Eric Laurent3b73df72014-03-11 09:06:29 -07006764 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006765 // first call getAudioPort to get the supported attributes from the HAL
6766 struct audio_port_v7 port = {};
6767 device->toAudioPort(&port);
6768 status_t status = mpClientInterface->getAudioPort(&port);
6769 if (status == NO_ERROR) {
6770 device->importAudioPort(port);
6771 }
6772
6773 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006774 for (size_t i = 0; i < mOutputs.size(); i++) {
6775 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006776 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006777 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006778 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6779 mOutputs.keyAt(i), device->toString().c_str());
6780 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006781 }
6782 }
6783 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006784 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006785 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006786 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6787 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006788 if (profile->supportsDevice(device)) {
6789 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306790 ALOGV("%s(): adding profile %s from module %s",
6791 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006792 }
6793 }
6794 }
6795
Eric Laurent7b279bb2015-12-14 10:18:23 -08006796 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006797
Eric Laurente552edb2014-03-10 17:42:56 -07006798 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006799 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006800 return BAD_VALUE;
6801 }
6802
6803 // open outputs for matching profiles if needed. Direct outputs are also opened to
6804 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6805 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006806 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006807
6808 // nothing to do if one output is already opened for this profile
6809 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006810 for (j = 0; j < outputs.size(); j++) {
6811 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006812 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006813 // matching profile: save the sample rates, format and channel masks supported
6814 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006815 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006816 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006817 }
Eric Laurente552edb2014-03-10 17:42:56 -07006818 break;
6819 }
6820 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006821 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006822 continue;
6823 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306824 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6825 ALOGV("%s skip opening output for mmap profile %s",
6826 __func__, profile->getTagName().c_str());
6827 continue;
6828 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006829 if (!profile->canOpenNewIo()) {
6830 ALOGW("Max Output number %u already opened for this profile %s",
6831 profile->maxOpenCount, profile->getTagName().c_str());
6832 continue;
6833 }
6834
Eric Laurent83efe1c2017-07-09 16:51:08 -07006835 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006836 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006837 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6838 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006839 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006840 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006841 profiles.removeAt(profile_index);
6842 profile_index--;
6843 } else {
6844 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006845 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006846 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006847 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6848 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006849 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006850 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006851
François Gaffie11d30102018-11-02 16:09:09 +01006852 if (device_distinguishes_on_address(deviceType)) {
6853 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6854 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306855 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6856 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006857 }
Eric Laurente552edb2014-03-10 17:42:56 -07006858 ALOGV("checkOutputsForDevice(): adding output %d", output);
6859 }
6860 }
6861
6862 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006863 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006864 return BAD_VALUE;
6865 }
Eric Laurentd4692962014-05-05 18:13:44 -07006866 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006867 // check if one opened output is not needed any more after disconnecting one device
6868 for (size_t i = 0; i < mOutputs.size(); i++) {
6869 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006870 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006871 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006872 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006873 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006874 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006875 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006876 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6877 mOutputs.keyAt(i));
6878 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006879 }
Eric Laurente552edb2014-03-10 17:42:56 -07006880 }
6881 }
Eric Laurentd4692962014-05-05 18:13:44 -07006882 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006883 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006884 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6885 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006886 if (!profile->supportsDevice(device)) {
6887 continue;
6888 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306889 ALOGV("%s(): clearing direct output profile %s on module %s",
6890 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006891 profile->clearAudioProfiles();
6892 if (!profile->hasDynamicAudioProfile()) {
6893 continue;
6894 }
6895 // When a device is disconnected, if there is an IOProfile that contains dynamic
6896 // profiles and supports the disconnected device, call getAudioPort to repopulate
6897 // the capabilities of the devices that is supported by the IOProfile.
6898 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6899 if (supportedDevice == device ||
6900 !mAvailableOutputDevices.contains(supportedDevice)) {
6901 continue;
6902 }
6903 struct audio_port_v7 port;
6904 supportedDevice->toAudioPort(&port);
6905 status_t status = mpClientInterface->getAudioPort(&port);
6906 if (status == NO_ERROR) {
6907 supportedDevice->importAudioPort(port);
6908 }
Eric Laurente552edb2014-03-10 17:42:56 -07006909 }
6910 }
6911 }
6912 }
6913 return NO_ERROR;
6914}
6915
François Gaffie11d30102018-11-02 16:09:09 +01006916status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006917 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006918{
François Gaffie11d30102018-11-02 16:09:09 +01006919 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006920 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006921 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006922 }
6923
Eric Laurentd4692962014-05-05 18:13:44 -07006924 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006925 sp<AudioInputDescriptor> desc;
6926
jiabinbf5f4262023-04-12 21:48:34 +00006927 // first call getAudioPort to get the supported attributes from the HAL
6928 struct audio_port_v7 port = {};
6929 device->toAudioPort(&port);
6930 status_t status = mpClientInterface->getAudioPort(&port);
6931 if (status == NO_ERROR) {
6932 device->importAudioPort(port);
6933 }
6934
Eric Laurent0dd51852019-04-19 18:18:58 -07006935 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006936 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006937 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006938 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006939 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006940 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006941 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006942
François Gaffie11d30102018-11-02 16:09:09 +01006943 if (profile->supportsDevice(device)) {
6944 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306945 ALOGV("%s : adding profile %s from module %s", __func__,
6946 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006947 }
6948 }
6949 }
6950
Eric Laurent0dd51852019-04-19 18:18:58 -07006951 if (profiles.isEmpty()) {
6952 ALOGW("%s: No input profile available for device %s",
6953 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006954 return BAD_VALUE;
6955 }
6956
6957 // open inputs for matching profiles if needed. Direct inputs are also opened to
6958 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6959 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6960
Eric Laurent1c333e22014-05-20 10:48:17 -07006961 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006962
Eric Laurentd4692962014-05-05 18:13:44 -07006963 // nothing to do if one input is already opened for this profile
6964 size_t input_index;
6965 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6966 desc = mInputs.valueAt(input_index);
6967 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006968 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006969 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006970 }
Eric Laurentd4692962014-05-05 18:13:44 -07006971 break;
6972 }
6973 }
6974 if (input_index != mInputs.size()) {
6975 continue;
6976 }
6977
Jaideep Sharma44824a22024-06-18 16:32:34 +05306978 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6979 ALOGV("%s skip opening input for mmap profile %s",
6980 __func__, profile->getTagName().c_str());
6981 continue;
6982 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006983 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306984 ALOGW("%s Max Input number %u already opened for this profile %s",
6985 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08006986 continue;
6987 }
6988
Eric Laurentfe231122017-11-17 17:48:06 -08006989 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006990 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306991 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00006992 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
6993 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006994
Eric Laurentcf2c0212014-07-25 16:20:43 -07006995 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006996 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006997 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006998 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006999 mpClientInterface->setParameters(input, String8(param));
7000 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007001 }
jiabin12537fc2023-10-12 17:56:08 +00007002 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007003 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307004 ALOGW("%s direct input missing param for profile %s", __func__,
7005 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007006 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007007 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007008 }
7009
Eric Laurent0dd51852019-04-19 18:18:58 -07007010 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007011 addInput(input, desc);
7012 }
7013 } // endif input != 0
7014
Eric Laurentcf2c0212014-07-25 16:20:43 -07007015 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307016 ALOGW("%s could not open input for device %s on profile %s", __func__,
7017 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007018 profiles.removeAt(profile_index);
7019 profile_index--;
7020 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007021 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007022 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007023 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307024 ALOGV("%s: adding input %d for profile %s", __func__,
7025 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007026
7027 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307028 ALOGV("%s: closing input %d for profile %s", __func__,
7029 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007030 closeInput(input);
7031 }
Eric Laurentd4692962014-05-05 18:13:44 -07007032 }
7033 } // end scan profiles
7034
7035 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007036 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007037 return BAD_VALUE;
7038 }
7039 } else {
7040 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007041 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007042 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007043 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007044 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007045 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007046 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007047 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307048 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7049 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007050 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007051 }
7052 }
7053 }
7054 } // end disconnect
7055
7056 return NO_ERROR;
7057}
7058
7059
Eric Laurente0720872014-03-11 09:30:41 -07007060void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007061{
7062 ALOGV("closeOutput(%d)", output);
7063
François Gaffie1c878552018-11-22 16:53:21 +01007064 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7065 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007066 ALOGW("closeOutput() unknown output %d", output);
7067 return;
7068 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007069 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007070 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007071
Eric Laurente552edb2014-03-10 17:42:56 -07007072 // look for duplicated outputs connected to the output being removed.
7073 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007074 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7075 if (dupOutput->isDuplicated() &&
7076 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7077 sp<SwAudioOutputDescriptor> remainingOutput =
7078 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007079 // As all active tracks on duplicated output will be deleted,
7080 // and as they were also referenced on the other output, the reference
7081 // count for their stream type must be adjusted accordingly on
7082 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007083 const bool wasActive = remainingOutput->isActive();
7084 // Note: no-op on the closing output where all clients has already been set inactive
7085 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007086 // stop() will be a no op if the output is still active but is needed in case all
7087 // active streams refcounts where cleared above
7088 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007089 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007090 }
Eric Laurente552edb2014-03-10 17:42:56 -07007091 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7092 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7093
7094 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007095 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007096 }
7097 }
7098
Eric Laurent05b90f82014-08-27 15:32:29 -07007099 nextAudioPortGeneration();
7100
François Gaffie1c878552018-11-22 16:53:21 +01007101 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007102 if (index >= 0) {
7103 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007104 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7105 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007106 mAudioPatches.removeItemsAt(index);
7107 mpClientInterface->onAudioPatchListUpdate();
7108 }
7109
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007110 if (closingOutputWasActive) {
7111 closingOutput->stop();
7112 }
François Gaffie1c878552018-11-22 16:53:21 +01007113 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007114 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007115 for (const auto device : closingOutput->devices()) {
7116 device->setPreferredConfig(nullptr);
7117 }
7118 }
Eric Laurente552edb2014-03-10 17:42:56 -07007119
François Gaffie53615e22015-03-19 09:24:12 +01007120 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007121 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007122 if (closingOutput == mSpatializerOutput) {
7123 mSpatializerOutput.clear();
7124 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007125
7126 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7127 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007128 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007129 bool directOutputOpen = false;
7130 for (size_t i = 0; i < mOutputs.size(); i++) {
7131 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7132 directOutputOpen = true;
7133 break;
7134 }
7135 }
7136 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007137 ALOGV("no direct outputs open, reset MSD patches");
7138 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7139 // how output devices for patching are resolved. Avoid by caching and reusing the
7140 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7141 // devices to patch to. This may be complicated by the fact that devices may become
7142 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007143 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007144 }
7145 }
jiabin220eea12024-05-17 17:55:20 +00007146
7147 if (closingOutput->mPreferredAttrInfo != nullptr) {
7148 closingOutput->mPreferredAttrInfo->resetActiveClient();
7149 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007150}
7151
7152void AudioPolicyManager::closeInput(audio_io_handle_t input)
7153{
7154 ALOGV("closeInput(%d)", input);
7155
7156 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7157 if (inputDesc == NULL) {
7158 ALOGW("closeInput() unknown input %d", input);
7159 return;
7160 }
7161
Eric Laurent6a94d692014-05-20 11:18:06 -07007162 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007163
François Gaffie11d30102018-11-02 16:09:09 +01007164 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007165 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007166 if (index >= 0) {
7167 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007168 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7169 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007170 mAudioPatches.removeItemsAt(index);
7171 mpClientInterface->onAudioPatchListUpdate();
7172 }
7173
François Gaffie6ebbce02023-07-19 13:27:53 +02007174 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007175 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007176 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007177
François Gaffie11d30102018-11-02 16:09:09 +01007178 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7179 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007180 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007181 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007182 }
Eric Laurente552edb2014-03-10 17:42:56 -07007183}
7184
François Gaffie11d30102018-11-02 16:09:09 +01007185SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7186 const DeviceVector &devices,
7187 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007188{
7189 SortedVector<audio_io_handle_t> outputs;
7190
François Gaffie11d30102018-11-02 16:09:09 +01007191 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007192 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007193 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007194 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007195 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007196 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007197 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007198 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007199 outputs.add(openOutputs.keyAt(i));
7200 }
7201 }
7202 return outputs;
7203}
7204
Mikhail Naganov37977152018-07-11 15:54:44 -07007205void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7206{
7207 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7208 // output is suspended before any tracks are moved to it
7209 checkA2dpSuspend();
7210 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007211 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007212 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007213 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007214 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007215 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7216 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7217 // configuration changes will ultimately be rerouted correctly. We can still avoid
7218 // unnecessary rerouting by caching and reusing the arguments to
7219 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7220 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007221 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007222 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007223 // an event that changed routing likely occurred, inform upper layers
7224 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007225}
7226
François Gaffiec005e562018-11-06 15:04:49 +01007227bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7228 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007229{
François Gaffiec005e562018-11-06 15:04:49 +01007230 return mEngine->getProductStrategyForAttributes(lAttr) ==
7231 mEngine->getProductStrategyForAttributes(rAttr);
7232}
7233
Francois Gaffieff1eb522020-05-06 18:37:04 +02007234void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7235{
7236 for (size_t i = 0; i < mAudioSources.size(); i++) {
7237 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7238 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007239 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007240 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007241 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007242 }
7243 }
7244}
7245
7246void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7247{
7248 for (size_t i = 0; i < mAudioSources.size(); i++) {
7249 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7250 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7251 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7252 disconnectAudioSource(sourceDesc);
7253 }
7254 }
7255}
7256
François Gaffiec005e562018-11-06 15:04:49 +01007257void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7258{
7259 auto psId = mEngine->getProductStrategyForAttributes(attr);
7260
7261 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7262 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007263
François Gaffie11d30102018-11-02 16:09:09 +01007264 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7265 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007266
Eric Laurentc209fe42020-06-05 18:11:23 -07007267 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007268 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007269 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007270 // take into account dynamic audio policies related changes: if a client is now associated
7271 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007272 // invalidate clients on outputs that do not support all the newly selected devices for the
7273 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007274 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007275 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007276 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007277 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007278 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007279
Eric Laurentc209fe42020-06-05 18:11:23 -07007280 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7281 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7282 continue;
7283 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007284 if (!desc->supportsAllDevices(newDevices)) {
7285 invalidatedOutputs.push_back(desc);
7286 break;
7287 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007288 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007289 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007290 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7291 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7292 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007293 if (status == OK) {
7294 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7295 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7296 maxLatency = desc->latency();
7297 }
7298 invalidatedOutputs.push_back(desc);
7299 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007300 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007301 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007302 }
7303 }
7304
Eric Laurent56ed8842022-11-15 16:04:41 +01007305 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007306 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7307 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007308 for (audio_io_handle_t srcOut : srcOutputs) {
7309 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007310 if (desc == nullptr) continue;
7311
7312 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007313 maxLatency = desc->latency();
7314 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007315
Eric Laurent56ed8842022-11-15 16:04:41 +01007316 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007317 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007318 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007319 // a client on a non direct outputs has necessarily a linear PCM format
7320 // so we can call selectOutput() safely
7321 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7322 client->flags(),
7323 client->config().format,
7324 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007325 client->config().sample_rate,
7326 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007327 if (newOutput != srcOut) {
7328 invalidate = true;
7329 break;
7330 }
7331 } else {
7332 sp<IOProfile> profile = getProfileForOutput(newDevices,
7333 client->config().sample_rate,
7334 client->config().format,
7335 client->config().channel_mask,
7336 client->flags(),
7337 true /* directOnly */);
7338 if (profile != desc->mProfile) {
7339 invalidate = true;
7340 break;
7341 }
7342 }
7343 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007344 // mute strategy while moving tracks from one output to another
7345 if (invalidate) {
7346 invalidatedOutputs.push_back(desc);
7347 if (desc->isStrategyActive(psId)) {
7348 setStrategyMute(psId, true, desc);
7349 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7350 newDevices.types());
7351 }
Eric Laurente552edb2014-03-10 17:42:56 -07007352 }
François Gaffiec005e562018-11-06 15:04:49 +01007353 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007354 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007355 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007356 }
Eric Laurente552edb2014-03-10 17:42:56 -07007357 }
7358
Eric Laurent56ed8842022-11-15 16:04:41 +01007359 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7360 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7361 std::to_string(srcOutputs[0]).c_str(),
7362 std::to_string(dstOutputs[0]).c_str());
7363
François Gaffiec005e562018-11-06 15:04:49 +01007364 // Move effects associated to this stream from previous output to new output
7365 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007366 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007367 }
François Gaffiec005e562018-11-06 15:04:49 +01007368 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007369 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007370 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007371 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007372 desc->setTracksInvalidatedStatusByStrategy(psId);
7373 }
Eric Laurente552edb2014-03-10 17:42:56 -07007374 }
7375 }
7376}
7377
Eric Laurente0720872014-03-11 09:30:41 -07007378void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007379{
François Gaffiec005e562018-11-06 15:04:49 +01007380 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7381 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7382 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007383 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007384 }
Eric Laurente552edb2014-03-10 17:42:56 -07007385}
7386
Kevin Rocard153f92d2018-12-18 18:33:28 -08007387void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007388 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007389 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007390 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007391 for (size_t i = 0; i < mOutputs.size(); i++) {
7392 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7393 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007394 sp<AudioPolicyMix> primaryMix;
7395 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007396 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007397 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7398 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7399 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007400 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7401 for (auto &secondaryMix : secondaryMixes) {
7402 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7403 if (outputDesc != nullptr &&
7404 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7405 secondaryDescs.push_back(outputDesc);
7406 }
7407 }
7408
jiabinc44b3462022-12-08 12:52:31 -08007409 if (status != OK &&
7410 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7411 // When it failed to query secondary output, only invalidate the client that is not
7412 // MMAP. The reason is that MMAP stream will not support secondary output.
7413 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007414 } else if (!std::equal(
7415 client->getSecondaryOutputs().begin(),
7416 client->getSecondaryOutputs().end(),
7417 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007418 if (!audio_is_linear_pcm(client->config().format)) {
7419 // If the format is not PCM, the tracks should be invalidated to get correct
7420 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007421 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007422 } else {
7423 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7424 std::vector<audio_io_handle_t> secondaryOutputIds;
7425 for (const auto &secondaryDesc: secondaryDescs) {
7426 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7427 weakSecondaryDescs.push_back(secondaryDesc);
7428 }
7429 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7430 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007431 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007432 }
7433 }
7434 }
jiabin10a03f12021-05-07 23:46:28 +00007435 if (!trackSecondaryOutputs.empty()) {
7436 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7437 }
jiabinc44b3462022-12-08 12:52:31 -08007438 if (!clientsToInvalidate.empty()) {
7439 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7440 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007441 }
7442}
7443
Eric Laurent2517af32020-11-25 15:31:27 +01007444bool AudioPolicyManager::isScoRequestedForComm() const {
7445 AudioDeviceTypeAddrVector devices;
7446 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7447 for (const auto &device : devices) {
7448 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7449 return true;
7450 }
7451 }
7452 return false;
7453}
7454
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007455bool AudioPolicyManager::isHearingAidUsedForComm() const {
7456 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7457 true /*fromCache*/);
7458 for (const auto &device : devices) {
7459 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7460 return true;
7461 }
7462 }
7463 return false;
7464}
7465
7466
Eric Laurente0720872014-03-11 09:30:41 -07007467void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007468{
François Gaffie53615e22015-03-19 09:24:12 +01007469 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007470 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007471 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007472 return;
7473 }
7474
Eric Laurent3a4311c2014-03-17 12:00:47 -07007475 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007476 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7477 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007478 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007479
7480 // if suspended, restore A2DP output if:
7481 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007482 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007483 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007484 //
Eric Laurentf732e072016-08-03 19:30:28 -07007485 // if not suspended, suspend A2DP output if:
7486 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007487 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007488 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007489 //
7490 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007491 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007492 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007493 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007494 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007495
7496 mpClientInterface->restoreOutput(a2dpOutput);
7497 mA2dpSuspended = false;
7498 }
7499 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007500 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007501 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007502 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007503 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007504
7505 mpClientInterface->suspendOutput(a2dpOutput);
7506 mA2dpSuspended = true;
7507 }
7508 }
7509}
7510
François Gaffie11d30102018-11-02 16:09:09 +01007511DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7512 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007513{
François Gaffiedb1755b2023-09-01 11:50:35 +02007514 if (outputDesc == nullptr) {
7515 return DeviceVector{};
7516 }
François Gaffie11d30102018-11-02 16:09:09 +01007517
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007518 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007519 if (index >= 0) {
7520 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007521 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007522 ALOGV("%s device %s forced by patch %d", __func__,
7523 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7524 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007525 }
7526 }
7527
Dean Wheatley514b4312020-06-17 21:45:00 +10007528 // Do not retrieve engine device for outputs through MSD
7529 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7530 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7531 return outputDesc->devices();
7532 }
7533
Eric Laurent97ac8712018-07-27 18:59:02 -07007534 // Honor explicit routing requests only if no client using default routing is active on this
7535 // input: a specific app can not force routing for other apps by setting a preferred device.
7536 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007537 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007538 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007539 if (device != nullptr) {
7540 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007541 }
7542
François Gaffiea807ef92018-11-05 10:44:33 +01007543 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7544 // of setForceUse / Default Bus device here
7545 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7546 if (device != nullptr) {
7547 return DeviceVector(device);
7548 }
7549
François Gaffiedb1755b2023-09-01 11:50:35 +02007550 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007551 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7552 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307553 auto hasStreamActive = [&](auto stream) {
7554 return hasStream(streams, stream) && isStreamActive(stream, 0);
7555 };
Eric Laurent484e9272018-06-07 17:29:23 -07007556
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307557 auto doGetOutputDevicesForVoice = [&]() {
7558 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007559 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307560 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007561 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7562 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307563 };
7564
7565 // With low-latency playing on speaker, music on WFD, when the first low-latency
7566 // output is stopped, getNewOutputDevices checks for a product strategy
7567 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007568 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307569 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7570 // stream is associated to the output descriptor.
7571 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7572 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7573 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7574 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007575 // Retrieval of devices for voice DL is done on primary output profile, cannot
7576 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007577 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007578 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7579 break;
7580 }
Eric Laurente552edb2014-03-10 17:42:56 -07007581 }
François Gaffiec005e562018-11-06 15:04:49 +01007582 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007583 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007584}
7585
François Gaffie11d30102018-11-02 16:09:09 +01007586sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7587 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007588{
François Gaffie11d30102018-11-02 16:09:09 +01007589 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007590
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007591 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007592 if (index >= 0) {
7593 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007594 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007595 ALOGV("getNewInputDevice() device %s forced by patch %d",
7596 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7597 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007598 }
7599 }
7600
Eric Laurent97ac8712018-07-27 18:59:02 -07007601 // Honor explicit routing requests only if no client using default routing is active on this
7602 // input: a specific app can not force routing for other apps by setting a preferred device.
7603 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007604 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7605 if (device != nullptr) {
7606 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007607 }
7608
Eric Laurentdc95a252018-04-12 12:46:56 -07007609 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007610 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007611 audio_attributes_t attributes;
7612 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007613 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007614 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7615 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007616 attributes = topClient->attributes();
7617 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007618 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007619 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007620 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7621 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007622 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007623 }
7624
Francois Gaffie716e1432019-01-14 16:58:59 +01007625 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7626 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007627 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007628 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007629 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007630 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007631
Eric Laurente552edb2014-03-10 17:42:56 -07007632 return device;
7633}
7634
Eric Laurent794fde22016-03-11 09:50:45 -08007635bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7636 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007637 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007638}
7639
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007640status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007641 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007642 if (devices == nullptr) {
7643 return BAD_VALUE;
7644 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007645
Andy Hung6d23c0f2022-02-16 09:37:15 -08007646 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007647 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7648 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007649 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007650 for (const auto& device : curDevices) {
7651 devices->push_back(device->getDeviceTypeAddr());
7652 }
7653 return NO_ERROR;
7654}
7655
Eric Laurente0720872014-03-11 09:30:41 -07007656void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007657 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007658 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007659 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007660 updateDevicesAndOutputs();
7661 break;
7662 default:
7663 break;
7664 }
7665}
7666
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007667uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007668
7669 // skip beacon mute management if a dedicated TTS output is available
7670 if (mTtsOutputAvailable) {
7671 return 0;
7672 }
7673
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007674 switch(event) {
7675 case STARTING_OUTPUT:
7676 mBeaconMuteRefCount++;
7677 break;
7678 case STOPPING_OUTPUT:
7679 if (mBeaconMuteRefCount > 0) {
7680 mBeaconMuteRefCount--;
7681 }
7682 break;
7683 case STARTING_BEACON:
7684 mBeaconPlayingRefCount++;
7685 break;
7686 case STOPPING_BEACON:
7687 if (mBeaconPlayingRefCount > 0) {
7688 mBeaconPlayingRefCount--;
7689 }
7690 break;
7691 }
7692
7693 if (mBeaconMuteRefCount > 0) {
7694 // any playback causes beacon to be muted
7695 return setBeaconMute(true);
7696 } else {
7697 // no other playback: unmute when beacon starts playing, mute when it stops
7698 return setBeaconMute(mBeaconPlayingRefCount == 0);
7699 }
7700}
7701
7702uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7703 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7704 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7705 // keep track of muted state to avoid repeating mute/unmute operations
7706 if (mBeaconMuted != mute) {
7707 // mute/unmute AUDIO_STREAM_TTS on all outputs
7708 ALOGV("\t muting %d", mute);
7709 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007710 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7711 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7712 ALOGV("\t no tts volume source available");
7713 return 0;
7714 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007715 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007716 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007717 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007718 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007719 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007720 maxLatency = latency;
7721 }
7722 }
7723 mBeaconMuted = mute;
7724 return maxLatency;
7725 }
7726 return 0;
7727}
7728
Eric Laurente0720872014-03-11 09:30:41 -07007729void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007730{
François Gaffiec005e562018-11-06 15:04:49 +01007731 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007732 mPreviousOutputs = mOutputs;
7733}
7734
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007735uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007736 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007737 uint32_t delayMs)
7738{
7739 // mute/unmute strategies using an incompatible device combination
7740 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7741 // if unmuting, unmute only after the specified delay
7742 if (outputDesc->isDuplicated()) {
7743 return 0;
7744 }
7745
7746 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007747 DeviceVector devices = outputDesc->devices();
7748 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007749
François Gaffiec005e562018-11-06 15:04:49 +01007750 auto productStrategies = mEngine->getOrderedProductStrategies();
7751 for (const auto &productStrategy : productStrategies) {
7752 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7753 DeviceVector curDevices =
7754 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7755 curDevices = curDevices.filter(outputDesc->supportedDevices());
7756 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007757 bool doMute = false;
7758
François Gaffiec005e562018-11-06 15:04:49 +01007759 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007760 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007761 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7762 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007763 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007764 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007765 }
Eric Laurent99401132014-05-07 19:48:15 -07007766 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007767 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007768 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007769 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007770 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007771 continue;
7772 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307773 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007774 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7775 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7776 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007777 if (mute) {
7778 // FIXME: should not need to double latency if volume could be applied
7779 // immediately by the audioflinger mixer. We must account for the delay
7780 // between now and the next time the audioflinger thread for this output
7781 // will process a buffer (which corresponds to one buffer size,
7782 // usually 1/2 or 1/4 of the latency).
7783 if (muteWaitMs < desc->latency() * 2) {
7784 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007785 }
7786 }
7787 }
7788 }
7789 }
7790 }
7791
Eric Laurent99401132014-05-07 19:48:15 -07007792 // temporary mute output if device selection changes to avoid volume bursts due to
7793 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007794 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007795 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007796
Eric Laurentdc462862016-07-19 12:29:53 -07007797 if (muteWaitMs < tempMuteWaitMs) {
7798 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007799 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007800
7801 // If recommended duration is defined, replace temporary mute duration to avoid
7802 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7803 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7804 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7805 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7806 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7807
François Gaffieaaac0fd2018-11-22 17:56:39 +01007808 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7809 // make sure that we do not start the temporary mute period too early in case of
7810 // delayed device change
7811 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7812 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007813 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007814 }
7815 }
7816
Eric Laurente552edb2014-03-10 17:42:56 -07007817 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7818 if (muteWaitMs > delayMs) {
7819 muteWaitMs -= delayMs;
7820 usleep(muteWaitMs * 1000);
7821 return muteWaitMs;
7822 }
7823 return 0;
7824}
7825
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307826uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7827 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007828 const DeviceVector &devices,
7829 bool force,
7830 int delayMs,
7831 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007832 bool requiresMuteCheck, bool requiresVolumeCheck,
7833 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007834{
jiabin3ff8d7d2022-12-13 06:27:44 +00007835 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307836 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7837 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7838 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007839 uint32_t muteWaitMs;
7840
7841 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307842 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007843 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307844 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007845 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007846 return muteWaitMs;
7847 }
Eric Laurente552edb2014-03-10 17:42:56 -07007848
7849 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007850 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007851 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007852 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007853
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307854 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7855 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007856
7857 if (!filteredDevices.isEmpty()) {
7858 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007859 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007860
7861 // if the outputs are not materially active, there is no need to mute.
7862 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007863 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007864 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307865 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7866 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007867 muteWaitMs = 0;
7868 }
Eric Laurente552edb2014-03-10 17:42:56 -07007869
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007870 bool outputRouted = outputDesc->isRouted();
7871
Eric Laurent79ea9582020-06-11 18:49:24 -07007872 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7873 // output profile or if new device is not supported AND previous device(s) is(are) still
7874 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007875 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307876 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7877 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007878 // restore previous device after evaluating strategy mute state
7879 outputDesc->setDevices(prevDevices);
7880 return muteWaitMs;
7881 }
7882
Eric Laurente552edb2014-03-10 17:42:56 -07007883 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007884 // the requested device is AUDIO_DEVICE_NONE
7885 // OR the requested device is the same as current device
7886 // AND force is not specified
7887 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007888 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007889 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307890 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7891 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7892 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007893 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307894 ALOGV("%s %s setting same device on routed output, force apply volumes",
7895 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007896 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7897 }
Eric Laurente552edb2014-03-10 17:42:56 -07007898 return muteWaitMs;
7899 }
7900
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307901 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7902 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007903
Eric Laurente552edb2014-03-10 17:42:56 -07007904 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007905 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007906 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007907 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007908 PatchBuilder patchBuilder;
7909 patchBuilder.addSource(outputDesc);
7910 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7911 for (const auto &filteredDevice : filteredDevices) {
7912 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007913 }
7914
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007915 // Add half reported latency to delayMs when muteWaitMs is null in order
7916 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007917 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7918 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7919 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007920 }
Eric Laurente552edb2014-03-10 17:42:56 -07007921
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007922 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7923 if (!skipMuteDelay) {
7924 // update stream volumes according to new device
7925 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7926 }
Eric Laurente552edb2014-03-10 17:42:56 -07007927
7928 return muteWaitMs;
7929}
7930
Eric Laurentc75307b2015-03-17 15:29:32 -07007931status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007932 int delayMs,
7933 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007934{
Eric Laurent6a94d692014-05-20 11:18:06 -07007935 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007936 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7937 return INVALID_OPERATION;
7938 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007939 if (patchHandle) {
7940 index = mAudioPatches.indexOfKey(*patchHandle);
7941 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007942 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007943 }
7944 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007945 return INVALID_OPERATION;
7946 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007947 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007948 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007949 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007950 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007951 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007952 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007953 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007954 return status;
7955}
7956
7957status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007958 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007959 bool force,
7960 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007961{
7962 status_t status = NO_ERROR;
7963
Eric Laurent1f2f2232014-06-02 12:01:23 -07007964 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007965 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7966 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007967
François Gaffie11d30102018-11-02 16:09:09 +01007968 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007969 PatchBuilder patchBuilder;
7970 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007971 // AUDIO_SOURCE_HOTWORD is for internal use only:
7972 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007973 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7974 auto result = usecase;
7975 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7976 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7977 }
7978 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007979 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007980 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007981 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007982 }
7983 }
7984 return status;
7985}
7986
Eric Laurent6a94d692014-05-20 11:18:06 -07007987status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7988 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007989{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007990 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007991 ssize_t index;
7992 if (patchHandle) {
7993 index = mAudioPatches.indexOfKey(*patchHandle);
7994 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007995 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007996 }
7997 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007998 return INVALID_OPERATION;
7999 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008000 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008001 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008002 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008003 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008004 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008005 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008006 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008007 return status;
8008}
8009
François Gaffie11d30102018-11-02 16:09:09 +01008010sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008011 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008012 audio_format_t& format,
8013 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008014 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008015{
8016 // Choose an input profile based on the requested capture parameters: select the first available
8017 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008018 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008019
Atneya Nair0f0a8032022-12-12 16:20:12 -08008020 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8021 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8022 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8023
8024 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008025
jiabin2fd710d2022-05-02 23:20:22 +00008026 for (;;) {
8027 sp<IOProfile> firstInexact = nullptr;
8028 uint32_t updatedSamplingRate = 0;
8029 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8030 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8031 for (const auto& hwModule : mHwModules) {
8032 for (const auto& profile : hwModule->getInputProfiles()) {
8033 // profile->log();
8034 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008035 if (profile->getCompatibilityScore(
8036 DeviceVector(device),
8037 samplingRate,
8038 &updatedSamplingRate,
8039 format,
8040 &updatedFormat,
8041 channelMask,
8042 &updatedChannelMask,
8043 // FIXME ugly cast
8044 (audio_output_flags_t) flags,
8045 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8046 samplingRate = updatedSamplingRate;
8047 format = updatedFormat;
8048 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008049 return profile;
8050 }
jiabin66acc432024-02-06 00:57:36 +00008051 if (firstInexact == nullptr
8052 && profile->getCompatibilityScore(
8053 DeviceVector(device),
8054 samplingRate,
8055 &updatedSamplingRate,
8056 format,
8057 &updatedFormat,
8058 channelMask,
8059 &updatedChannelMask,
8060 // FIXME ugly cast
8061 (audio_output_flags_t) flags,
8062 false /*exactMatchRequiredForInputFlags*/)
8063 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008064 firstInexact = profile;
8065 }
8066 }
8067 }
8068
8069 if (firstInexact != nullptr) {
8070 samplingRate = updatedSamplingRate;
8071 format = updatedFormat;
8072 channelMask = updatedChannelMask;
8073 return firstInexact;
8074 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8075 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8076 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8077 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8078 flags = AUDIO_INPUT_FLAG_NONE;
8079 } else { // fail
8080 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8081 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8082 samplingRate, format, channelMask, oriFlags);
8083 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008084 }
8085 }
jiabin2fd710d2022-05-02 23:20:22 +00008086
8087 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008088}
8089
Vlad Popa87e0e582024-05-20 18:49:20 -07008090float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8091 VolumeSource volumeSource,
8092 int index,
8093 const DeviceTypeSet &deviceTypes)
8094{
8095 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8096 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8097 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8098
8099 if (com_android_media_audio_abs_volume_index_fix()) {
8100 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8101 mAbsoluteVolumeDrivingStreams.end()) {
8102 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8103 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8104 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8105 ALOGD("%s: no group matching with %s", __FUNCTION__,
8106 toString(attributesToDriveAbs).c_str());
8107 return volumeDb;
8108 }
8109
8110 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8111 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8112 if (vsToDriveAbs == volumeSource) {
8113 // attenuation is applied by the abs volume controller
8114 return volumeDbMax;
8115 } else {
8116 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8117 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8118 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8119 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8120 curvesAbs.getVolumeIndexMax());
8121 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8122 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8123 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8124 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8125 return newVolumeDb;
8126 }
8127 }
8128 return volumeDb;
8129 } else {
8130 return volumeDb;
8131 }
8132}
8133
François Gaffieaaac0fd2018-11-22 17:56:39 +01008134float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8135 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008136 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008137 const DeviceTypeSet& deviceTypes,
8138 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008139{
Vlad Popa87e0e582024-05-20 18:49:20 -07008140 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008141 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8142 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8143
8144 if (!computeInternalInteraction) {
8145 return volumeDb;
8146 }
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008147
8148 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8149 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8150 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8151 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008152 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8153 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8154 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8155 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8156 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008157 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008158 mOutputs.isActive(ringVolumeSrc, 0)) {
8159 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008160 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8161 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008162 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008163 }
8164
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008165 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008166 if ((volumeSource != callVolumeSrc && (isInCall() ||
8167 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008168 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008169 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8170 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008171 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8172 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8173 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008174 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008175 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008176 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008177 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008178 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8179 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008180 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008181 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8182 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8183 // programmatically muted.
8184 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8185 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8186 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008187 bool exemptFromCapping =
8188 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8189 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008190 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8191 volumeSource, volumeDb);
8192 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008193 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8194 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8195 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008196 }
8197 }
Eric Laurente552edb2014-03-10 17:42:56 -07008198 // if a headset is connected, apply the following rules to ring tones and notifications
8199 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008200 // - always attenuate notifications volume by 6dB
8201 // - attenuate ring tones volume by 6dB unless music is not playing and
8202 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008203 // - if music is playing, always limit the volume to current music volume,
8204 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008205 if (!Intersection(deviceTypes,
8206 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8207 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008208 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8209 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008210 ((volumeSource == alarmVolumeSrc ||
8211 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008212 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8213 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8214 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008215 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8216 curves.canBeMuted()) {
8217
Eric Laurente552edb2014-03-10 17:42:56 -07008218 // when the phone is ringing we must consider that music could have been paused just before
8219 // by the music application and behave as if music was active if the last music track was
8220 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008221 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8222 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008223 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008224 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008225 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8226 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008227 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008228 float musicVolDb = computeVolume(musicCurves,
8229 musicVolumeSrc,
8230 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008231 musicDevice,
8232 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008233 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8234 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8235 if (volumeDb > minVolDb) {
8236 volumeDb = minVolDb;
8237 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008238 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008239 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8240 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008241 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8242 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8243 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8244 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008245 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008246 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008247 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8248 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008249 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8250 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008251 }
8252 }
jiabin9a3361e2019-10-01 09:38:30 -07008253 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008254 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008255 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008256 }
8257 }
8258
François Gaffie43c73442018-11-08 08:21:55 +01008259 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008260}
8261
Eric Laurent3839bc02018-07-10 18:33:34 -07008262int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008263 VolumeSource fromVolumeSource,
8264 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008265{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008266 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008267 return srcIndex;
8268 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008269 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8270 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008271 float minSrc = (float)srcCurves.getVolumeIndexMin();
8272 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8273 float minDst = (float)dstCurves.getVolumeIndexMin();
8274 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008275
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008276 // preserve mute request or correct range
8277 if (srcIndex < minSrc) {
8278 if (srcIndex == 0) {
8279 return 0;
8280 }
8281 srcIndex = minSrc;
8282 } else if (srcIndex > maxSrc) {
8283 srcIndex = maxSrc;
8284 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008285 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8286}
8287
François Gaffieaaac0fd2018-11-22 17:56:39 +01008288status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8289 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008290 int index,
8291 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008292 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008293 int delayMs,
8294 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008295{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008296 // APM is single threaded, and single instance.
8297 static std::set<IVolumeCurves*> invalidCurvesReported;
8298
François Gaffieaaac0fd2018-11-22 17:56:39 +01008299 // do not change actual attributes volume if the attributes is muted
8300 if (outputDesc->isMuted(volumeSource)) {
8301 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8302 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008303 return NO_ERROR;
8304 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008305
Eric Laurent5baf07c2024-01-11 16:57:27 +00008306 bool isVoiceVolSrc;
8307 bool isBtScoVolSrc;
8308 if (!isVolumeConsistentForCalls(
8309 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008310 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008311 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008312 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008313 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008314
jiabin9a3361e2019-10-01 09:38:30 -07008315 if (deviceTypes.empty()) {
8316 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008317 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008318 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008319 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008320 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008321
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008322 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008323 if (!invalidCurvesReported.count(&curves)) {
8324 invalidCurvesReported.insert(&curves);
8325 String8 dump;
8326 curves.dump(&dump);
8327 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8328 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008329 return BAD_VALUE;
8330 }
8331
jiabin9a3361e2019-10-01 09:38:30 -07008332 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8333 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008334 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008335 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008336 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8337 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008338 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008339 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008340 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008341 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8342 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008343
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008344 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008345 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8346 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8347 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008348 }
Eric Laurente552edb2014-03-10 17:42:56 -07008349 return NO_ERROR;
8350}
8351
Eric Laurent5baf07c2024-01-11 16:57:27 +00008352void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008353 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008354 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008355 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008356 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008357 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008358 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8359 } else {
8360 voiceVolume = index == 0 ? 0.0 : 1.0;
8361 }
8362 if (voiceVolume != mLastVoiceVolume) {
8363 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8364 mLastVoiceVolume = voiceVolume;
8365 }
8366}
8367
8368bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8369 const DeviceTypeSet& deviceTypes,
8370 bool& isVoiceVolSrc,
8371 bool& isBtScoVolSrc,
8372 const char* caller) {
8373 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8374 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8375 const bool isScoRequested = isScoRequestedForComm();
8376 const bool isHAUsed = isHearingAidUsedForComm();
8377
8378 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8379 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8380
8381 if ((callVolSrc != btScoVolSrc) &&
8382 ((isVoiceVolSrc && isScoRequested) ||
8383 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8384 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8385 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8386 volumeSource, isScoRequested ? " " : " not ");
8387 return false;
8388 }
8389 return true;
8390}
8391
Eric Laurentc75307b2015-03-17 15:29:32 -07008392void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008393 const DeviceTypeSet& deviceTypes,
8394 int delayMs,
8395 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008396{
jiabincd510522020-01-22 09:40:55 -08008397 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008398 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8399 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8400 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008401 curves.getVolumeIndex(deviceTypes),
8402 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008403 }
8404}
8405
François Gaffiec005e562018-11-06 15:04:49 +01008406void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8407 bool on,
8408 const sp<AudioOutputDescriptor>& outputDesc,
8409 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008410 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008411{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008412 std::vector<VolumeSource> sourcesToMute;
8413 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8414 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8415 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008416 VolumeSource source = toVolumeSource(attributes, false);
8417 if ((source != VOLUME_SOURCE_NONE) &&
8418 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8419 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008420 sourcesToMute.push_back(source);
8421 }
Eric Laurente552edb2014-03-10 17:42:56 -07008422 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008423 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008424 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008425 }
8426
Eric Laurente552edb2014-03-10 17:42:56 -07008427}
8428
François Gaffieaaac0fd2018-11-22 17:56:39 +01008429void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8430 bool on,
8431 const sp<AudioOutputDescriptor>& outputDesc,
8432 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008433 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008434{
jiabin9a3361e2019-10-01 09:38:30 -07008435 if (deviceTypes.empty()) {
8436 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008437 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008438 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008439 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008440 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008441 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008442 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008443 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8444 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008445 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008446 }
8447 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008448 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8449 // ignored
8450 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008451 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008452 if (!outputDesc->isMuted(volumeSource)) {
8453 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008454 return;
8455 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008456 if (outputDesc->decMuteCount(volumeSource) == 0) {
8457 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008458 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008459 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008460 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008461 delayMs);
8462 }
8463 }
8464}
8465
François Gaffie53615e22015-03-19 09:24:12 +01008466bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8467{
François Gaffiec005e562018-11-06 15:04:49 +01008468 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008469 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8470 return true;
8471 }
8472
8473 // has known usage?
8474 switch (paa->usage) {
8475 case AUDIO_USAGE_UNKNOWN:
8476 case AUDIO_USAGE_MEDIA:
8477 case AUDIO_USAGE_VOICE_COMMUNICATION:
8478 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8479 case AUDIO_USAGE_ALARM:
8480 case AUDIO_USAGE_NOTIFICATION:
8481 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8482 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8483 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8484 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8485 case AUDIO_USAGE_NOTIFICATION_EVENT:
8486 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8487 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8488 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8489 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008490 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008491 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008492 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008493 case AUDIO_USAGE_EMERGENCY:
8494 case AUDIO_USAGE_SAFETY:
8495 case AUDIO_USAGE_VEHICLE_STATUS:
8496 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008497 break;
8498 default:
8499 return false;
8500 }
8501 return true;
8502}
8503
François Gaffie2110e042015-03-24 08:41:51 +01008504audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8505{
8506 return mEngine->getForceUse(usage);
8507}
8508
Eric Laurent96d1dda2022-03-14 17:14:19 +01008509bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008510 return isStateInCall(mEngine->getPhoneState());
8511}
8512
Eric Laurent96d1dda2022-03-14 17:14:19 +01008513bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008514 return is_state_in_call(state);
8515}
8516
Eric Laurentf9cccec2022-11-16 19:12:00 +01008517bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008518 audio_mode_t mode = mEngine->getPhoneState();
8519 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008520 || (mode == AUDIO_MODE_CALL_SCREEN)
8521 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008522}
8523
Eric Laurentf9cccec2022-11-16 19:12:00 +01008524bool AudioPolicyManager::isInCallOrScreening() const {
8525 audio_mode_t mode = mEngine->getPhoneState();
8526 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8527}
8528
Eric Laurentd60560a2015-04-10 11:31:20 -07008529void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8530{
8531 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008532 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008533 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008534 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008535 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008536 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008537 }
8538 }
8539
8540 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8541 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8542 bool release = false;
8543 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8544 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8545 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8546 source->ext.device.type == deviceDesc->type()) {
8547 release = true;
8548 }
8549 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008550 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008551 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8552 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8553 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008554 sink->ext.device.type == deviceDesc->type() &&
8555 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8556 || strncmp(sink->ext.device.address, address,
8557 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008558 release = true;
8559 }
8560 }
8561 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008562 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8563 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008564 }
8565 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008566
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008567 mInputs.clearSessionRoutesForDevice(deviceDesc);
8568
Francois Gaffie716e1432019-01-14 16:58:59 +01008569 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008570}
8571
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008572void AudioPolicyManager::modifySurroundFormats(
8573 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008574 std::unordered_set<audio_format_t> enforcedSurround(
8575 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008576 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008577 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008578 allSurround.insert(pair.first);
8579 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8580 }
Phil Burk09bc4612016-02-24 15:58:15 -08008581
8582 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8583 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008584 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008585 // This is the resulting set of formats depending on the surround mode:
8586 // 'all surround' = allSurround
8587 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8588 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8589 // 'manual surround' = mManualSurroundFormats
8590 // AUTO: formats v 'enforced surround'
8591 // ALWAYS: formats v 'all surround' v 'enforced surround'
8592 // NEVER: formats ^ 'non-surround'
8593 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008594
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008595 std::unordered_set<audio_format_t> formatSet;
8596 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8597 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008598 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008599 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008600 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008601 formatSet.insert(*formatIter);
8602 }
8603 }
8604 } else {
8605 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8606 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008607 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008608
jiabin81772902018-04-02 17:52:27 -07008609 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008610 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008611 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8612 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8613 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008614 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008615 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8616 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8617 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008618 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008619 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008620 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008621 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008622 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008623 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008624}
8625
jiabin06e4bab2019-07-29 10:13:34 -07008626void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8627 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008628 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8629 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8630
8631 // If NEVER, then remove support for channelMasks > stereo.
8632 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008633 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8634 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008635 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008636 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008637 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008638 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008639 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008640 }
8641 }
jiabin81772902018-04-02 17:52:27 -07008642 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8643 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8644 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008645 bool supports5dot1 = false;
8646 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008647 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008648 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8649 supports5dot1 = true;
8650 break;
8651 }
8652 }
8653 // If not then add 5.1 support.
8654 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008655 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008656 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008657 }
Phil Burk09bc4612016-02-24 15:58:15 -08008658 }
8659}
8660
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008661void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008662 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008663 const sp<IOProfile>& profile) {
8664 if (!profile->hasDynamicAudioProfile()) {
8665 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008666 }
François Gaffie112b0af2015-11-19 16:13:25 +01008667
jiabin12537fc2023-10-12 17:56:08 +00008668 audio_port_v7 devicePort;
8669 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008670
jiabin12537fc2023-10-12 17:56:08 +00008671 audio_port_v7 mixPort;
8672 profile->toAudioPort(&mixPort);
8673 mixPort.ext.mix.handle = ioHandle;
8674
8675 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8676 if (status != NO_ERROR) {
8677 ALOGE("%s failed to query the attributes of the mix port", __func__);
8678 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008679 }
jiabin12537fc2023-10-12 17:56:08 +00008680
8681 std::set<audio_format_t> supportedFormats;
8682 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8683 supportedFormats.insert(mixPort.audio_profiles[i].format);
8684 }
8685 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8686 mReportedFormatsMap[devDesc] = formats;
8687
8688 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8689 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8690 modifySurroundFormats(devDesc, &formats);
8691 size_t modifiedNumProfiles = 0;
8692 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8693 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8694 formats.end()) {
8695 // Skip the format that is not present after modifying surround formats.
8696 continue;
8697 }
8698 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8699 sizeof(struct audio_profile));
8700 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8701 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8702 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8703 modifySurroundChannelMasks(&channels);
8704 std::copy(channels.begin(), channels.end(),
8705 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8706 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8707 }
8708 mixPort.num_audio_profiles = modifiedNumProfiles;
8709 }
8710 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008711}
Eric Laurentd60560a2015-04-10 11:31:20 -07008712
Mikhail Naganovdc769682018-05-04 15:34:08 -07008713status_t AudioPolicyManager::installPatch(const char *caller,
8714 audio_patch_handle_t *patchHandle,
8715 AudioIODescriptorInterface *ioDescriptor,
8716 const struct audio_patch *patch,
8717 int delayMs)
8718{
8719 ssize_t index = mAudioPatches.indexOfKey(
8720 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8721 *patchHandle : ioDescriptor->getPatchHandle());
8722 sp<AudioPatch> patchDesc;
8723 status_t status = installPatch(
8724 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8725 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008726 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008727 }
8728 return status;
8729}
8730
8731status_t AudioPolicyManager::installPatch(const char *caller,
8732 ssize_t index,
8733 audio_patch_handle_t *patchHandle,
8734 const struct audio_patch *patch,
8735 int delayMs,
8736 uid_t uid,
8737 sp<AudioPatch> *patchDescPtr)
8738{
8739 sp<AudioPatch> patchDesc;
8740 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8741 if (index >= 0) {
8742 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008743 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008744 }
8745
8746 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8747 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8748 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8749 if (status == NO_ERROR) {
8750 if (index < 0) {
8751 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008752 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008753 } else {
8754 patchDesc->mPatch = *patch;
8755 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008756 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008757 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008758 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008759 }
8760 nextAudioPortGeneration();
8761 mpClientInterface->onAudioPatchListUpdate();
8762 }
8763 if (patchDescPtr) *patchDescPtr = patchDesc;
8764 return status;
8765}
8766
jiabinbce0c1d2020-10-05 11:20:18 -07008767bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8768{
8769 const TrackClientVector activeClients = output->getActiveClients();
8770 if (activeClients.empty()) {
8771 return true;
8772 }
8773 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8774 if (index < 0) {
8775 ALOGE("%s, no audio patch found while there are active clients on output %d",
8776 __func__, output->getId());
8777 return false;
8778 }
8779 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8780 DeviceVector routedDevices;
8781 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8782 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8783 patchDesc->mPatch.sinks[i].id);
8784 if (device == nullptr) {
8785 ALOGE("%s, no audio device found with id(%d)",
8786 __func__, patchDesc->mPatch.sinks[i].id);
8787 return false;
8788 }
8789 routedDevices.add(device);
8790 }
8791 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008792 if (client->isInvalid()) {
8793 // No need to take care about invalidated clients.
8794 continue;
8795 }
jiabinbce0c1d2020-10-05 11:20:18 -07008796 sp<DeviceDescriptor> preferredDevice =
8797 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8798 if (mEngine->getOutputDevicesForAttributes(
8799 client->attributes(), preferredDevice, false) == routedDevices) {
8800 return false;
8801 }
8802 }
8803 return true;
8804}
8805
8806sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008807 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008808 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8809 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008810{
8811 for (const auto& device : devices) {
8812 // TODO: This should be checking if the profile supports the device combo.
8813 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008814 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8815 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008816 return nullptr;
8817 }
8818 }
8819 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8820 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008821 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008822 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008823 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008824 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008825 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008826 return nullptr;
8827 }
jiabin14b50cc2023-12-13 19:01:52 +00008828 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8829 auto portConfig = desc->getConfig();
8830 for (const auto& device : devices) {
8831 device->setPreferredConfig(&portConfig);
8832 }
8833 }
jiabinbce0c1d2020-10-05 11:20:18 -07008834
8835 // Here is where the out_set_parameters() for card & device gets called
8836 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8837 const audio_devices_t deviceType = device->type();
8838 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008839 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008840 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8841 mpClientInterface->setParameters(output, String8(param));
8842 free(param);
8843 }
jiabin12537fc2023-10-12 17:56:08 +00008844 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008845 if (!profile->hasValidAudioProfile()) {
8846 ALOGW("%s() missing param", __func__);
8847 desc->close();
8848 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008849 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8850 // Reopen the output with the best audio profile picked by APM when the profile supports
8851 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008852 desc->close();
8853 output = AUDIO_IO_HANDLE_NONE;
8854 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8855 profile->pickAudioProfile(
8856 config.sample_rate, config.channel_mask, config.format);
8857 config.offload_info.sample_rate = config.sample_rate;
8858 config.offload_info.channel_mask = config.channel_mask;
8859 config.offload_info.format = config.format;
8860
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008861 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
8862 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008863 if (status != NO_ERROR) {
8864 return nullptr;
8865 }
8866 }
8867
8868 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008869 setOutputDevices(__func__, desc,
8870 devices,
8871 true,
8872 0,
8873 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008874 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8875 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8876
jiabinbce0c1d2020-10-05 11:20:18 -07008877 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8878 sp<AudioPolicyMix> policyMix;
8879 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8880 policyMix->setOutput(desc);
8881 desc->mPolicyMix = policyMix;
8882 } else {
8883 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008884 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008885 }
8886
baek.kim -61c20122022-07-27 10:05:32 +00008887 } else if (hasPrimaryOutput() && speaker != nullptr
8888 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008889 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8890 // no duplicated output for:
8891 // - direct outputs
8892 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008893 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008894 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8895
8896 //TODO: configure audio effect output stage here
8897
8898 // open a duplicating output thread for the new output and the primary output
8899 sp<SwAudioOutputDescriptor> dupOutputDesc =
8900 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8901 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8902 if (status == NO_ERROR) {
8903 // add duplicated output descriptor
8904 addOutput(duplicatedOutput, dupOutputDesc);
8905 } else {
8906 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8907 mPrimaryOutput->mIoHandle, output);
8908 desc->close();
8909 removeOutput(output);
8910 nextAudioPortGeneration();
8911 return nullptr;
8912 }
8913 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008914 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8915 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8916 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008917 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008918 }
jiabinbce0c1d2020-10-05 11:20:18 -07008919 return desc;
8920}
8921
jiabinf1c73972022-04-14 16:28:52 -07008922status_t AudioPolicyManager::getDevicesForAttributes(
8923 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8924 // Devices are determined in the following precedence:
8925 //
8926 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8927 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8928 //
8929 // If no such dynamic policy then
8930 // 2) Devices containing an active client using setPreferredDevice
8931 // with same strategy as the attributes.
8932 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8933 //
8934 // If no corresponding active client with setPreferredDevice then
8935 // 3) Devices associated with the strategy determined by the attributes
8936 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8937 //
8938 // See related getOutputForAttrInt().
8939
8940 // check dynamic policies but only for primary descriptors (secondary not used for audible
8941 // audio routing, only used for duplication for playback capture)
8942 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008943 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008944 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008945 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8946 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8947 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008948 if (status != OK) {
8949 return status;
8950 }
8951
8952 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8953 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8954 // as they are unaffected by device/stream volume
8955 // (per SwAudioOutputDescriptor::isFixedVolume()).
8956 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8957 ) {
8958 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8959 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8960 devices.add(deviceDesc);
8961 } else {
8962 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8963 // which selects setPreferredDevice if active. This means forVolume call
8964 // will take an active setPreferredDevice, if such exists.
8965
8966 devices = mEngine->getOutputDevicesForAttributes(
8967 attr, nullptr /* preferredDevice */, false /* fromCache */);
8968 }
8969
8970 if (forVolume) {
8971 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8972 // for single volume control in AudioService (such relationship should exist if
8973 // SPEAKER_SAFE is present).
8974 //
8975 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8976 DeviceVector speakerSafeDevices =
8977 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8978 if (!speakerSafeDevices.isEmpty()) {
8979 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8980 devices.remove(speakerSafeDevices);
8981 }
8982 }
8983
8984 return NO_ERROR;
8985}
8986
8987status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8988 AudioProfileVector& audioProfiles,
8989 uint32_t flags,
8990 bool isInput) {
8991 for (const auto& hwModule : mHwModules) {
8992 // the MSD module checks for different conditions
8993 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8994 continue;
8995 }
8996 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8997 : hwModule->getOutputProfiles();
8998 for (const auto& profile : ioProfiles) {
8999 if (!profile->areAllDevicesSupported(devices) ||
9000 !profile->isCompatibleProfileForFlags(
9001 flags, false /*exactMatchRequiredForInputFlags*/)) {
9002 continue;
9003 }
9004 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9005 }
9006 }
9007
9008 if (!isInput) {
9009 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9010 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9011 if (msdModule != nullptr) {
9012 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9013 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9014 for (const auto &profile: msdModule->getOutputProfiles()) {
9015 if (!profile->asAudioPort()->isDirectOutput()) {
9016 continue;
9017 }
9018 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9019 }
9020 } else {
9021 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9022 }
9023 }
9024 }
9025
9026 return NO_ERROR;
9027}
9028
jiabin3ff8d7d2022-12-13 06:27:44 +00009029sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9030 const audio_config_t *config,
9031 audio_output_flags_t flags,
9032 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009033 closeOutput(outputDesc->mIoHandle);
9034 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9035 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9036 if (preferredOutput == nullptr) {
9037 ALOGE("%s failed to reopen output device=%d, caller=%s",
9038 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009039 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009040 return preferredOutput;
9041}
9042
9043void AudioPolicyManager::reopenOutputsWithDevices(
9044 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9045 for (const auto& [output, devices] : outputsToReopen) {
9046 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9047 closeOutput(output);
9048 openOutputWithProfileAndDevice(desc->mProfile, devices);
9049 }
jiabina84c3d32022-12-02 18:59:55 +00009050}
9051
jiabinc44b3462022-12-08 12:52:31 -08009052PortHandleVector AudioPolicyManager::getClientsForStream(
9053 audio_stream_type_t streamType) const {
9054 PortHandleVector clients;
9055 for (size_t i = 0; i < mOutputs.size(); ++i) {
9056 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9057 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9058 }
9059 return clients;
9060}
9061
9062void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9063 PortHandleVector clients;
9064 for (auto stream : streams) {
9065 PortHandleVector clientsForStream = getClientsForStream(stream);
9066 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9067 }
9068 mpClientInterface->invalidateTracks(clients);
9069}
9070
jiabin220eea12024-05-17 17:55:20 +00009071void AudioPolicyManager::updateClientsInternalMute(
9072 const sp<android::SwAudioOutputDescriptor> &desc) {
9073 if (!desc->isBitPerfect() ||
9074 !com::android::media::audioserver::
9075 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9076 // This is only used for bit perfect output now.
9077 return;
9078 }
9079 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9080 bool bitPerfectClientInternalMute = false;
9081 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9082 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9083 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9084 bitPerfectClient = client;
9085 continue;
9086 }
9087 bool muted = false;
9088 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9089 // System sound is muted.
9090 muted = true;
9091 } else {
9092 bitPerfectClientInternalMute = true;
9093 }
9094 if (client->setInternalMute(muted)) {
9095 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9096 if (!result.ok()) {
9097 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9098 continue;
9099 }
9100 media::TrackInternalMuteInfo info;
9101 info.portId = result.value();
9102 info.muted = client->getInternalMute();
9103 clientsInternalMute.push_back(std::move(info));
9104 }
9105 }
9106 if (bitPerfectClient != nullptr &&
9107 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9108 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9109 if (result.ok()) {
9110 media::TrackInternalMuteInfo info;
9111 info.portId = result.value();
9112 info.muted = bitPerfectClient->getInternalMute();
9113 clientsInternalMute.push_back(std::move(info));
9114 } else {
9115 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9116 __func__, bitPerfectClient->portId());
9117 }
9118 }
9119 if (!clientsInternalMute.empty()) {
9120 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9121 status != NO_ERROR) {
9122 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9123 }
9124 }
9125}
9126
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009127} // namespace android