blob: 2ff2907d9dfb89bac01ef01b2689e9e7d986bc11 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
131 status != OK) {
132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganov3754b642024-04-17 18:31:04 +0000222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530377 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700378 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } // end if is output device
380
Eric Laurente552edb2014-03-10 17:42:56 -0700381 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700382 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700384 switch (state)
385 {
386 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700390 return INVALID_OPERATION;
391 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700392
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530393 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (mAvailableInputDevices.add(device) < 0) {
396 return NO_MEMORY;
397 }
398
François Gaffie44481e72016-04-20 07:49:57 +0200399 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
400 // parameters on newly connected devices (instead of opening the inputs...)
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000401 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700402 // Propagate device availability to Engine
403 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200404
Eric Laurent0dd51852019-04-19 18:18:58 -0700405 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700406 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
407
Eric Laurent0dd51852019-04-19 18:18:58 -0700408 mAvailableInputDevices.remove(device);
409
jiabinc0048632023-04-27 22:04:31 +0000410 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100411
412 mHwModules.cleanUpForDevice(device);
413
Eric Laurentd4692962014-05-05 18:13:44 -0700414 return INVALID_OPERATION;
415 }
416
Eric Laurentd4692962014-05-05 18:13:44 -0700417 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700418
419 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700420 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700421 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return INVALID_OPERATION;
424 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700425
François Gaffie11d30102018-11-02 16:09:09 +0100426 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700427
jiabinc0048632023-04-27 22:04:31 +0000428 // Notify the HAL to prepare to disconnect device
429 broadcastDeviceConnectionState(
430 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700431
François Gaffie11d30102018-11-02 16:09:09 +0100432 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700433
434 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100435
jiabinc0048632023-04-27 22:04:31 +0000436 // Set Disconnect to HALs
437 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
438
Kriti Dangef6be8f2020-11-05 11:58:19 +0100439 // remove device from mReportedFormatsMap cache
440 mReportedFormatsMap.erase(device);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700441
442 // Propagate device availability to Engine
443 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700444 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700445
446 default:
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449 }
450
Eric Laurent0dd51852019-04-19 18:18:58 -0700451 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700452 // As the input device list can impact the output device selection, update
453 // getDeviceForStrategy() cache
454 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700455
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100456 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200457 // Reconnect Audio Source
458 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
459 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
460 checkAudioSourceForAttributes(attributes);
461 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700462 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100463 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700464 }
465
Eric Laurentb52c1522014-05-20 11:27:36 -0700466 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530467 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700468 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700469 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700470
François Gaffie11d30102018-11-02 16:09:09 +0100471 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700472 return BAD_VALUE;
473}
474
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100475status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
476 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800477 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000478 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
479 devDescr->setName(device_name);
480 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100481}
482
Eric Laurent736a1022019-03-27 18:28:46 -0700483void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
484 audio_policy_dev_state_t state) {
485
486 // the Engine does not have to know about remote submix devices used by dynamic audio policies
487 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
488 return;
489 }
490 mEngine->setDeviceConnectionState(device, state);
491}
492
493
Eric Laurente0720872014-03-11 09:30:41 -0700494audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100495 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700496{
Eric Laurent634b7142016-04-20 13:48:02 -0700497 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800498 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
499 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700500 (strlen(device_address) != 0)/*matchAddress*/);
501
502 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100503 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700504 device, device_address);
505 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
506 }
François Gaffie53615e22015-03-19 09:24:12 +0100507
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 DeviceVector *deviceVector;
509
Eric Laurente552edb2014-03-10 17:42:56 -0700510 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700511 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700512 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700513 deviceVector = &mAvailableInputDevices;
514 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100515 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700516 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700517 }
Eric Laurent634b7142016-04-20 13:48:02 -0700518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 return (deviceVector->getDevice(
520 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800522}
523
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
525 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 const char *device_name,
527 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
530 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800532 // connect/disconnect only 1 device at a time
533 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
534
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800535 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700536 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538 // Nothing to do: device is not connected
539 return NO_ERROR;
540 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800542
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700543 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 // configure codecs.
545 // Handle two specific cases by sending a set parameter to
546 // configure A2DP codecs. No need to toggle device state.
547 // Case 1: A2DP active device switches from primary to primary
548 // module
549 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100550 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700551 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800552 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
553 if (availablePrimaryOutputDevices().contains(devDesc) &&
554 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100555 bool isA2dp = audio_is_a2dp_out_device(device);
556 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
557 : String8(AudioParameter::keyReconfigLeSupported);
558 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800559 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100560 int isReconfigSupported;
561 repliedParameters.getInt(supportKey, isReconfigSupported);
562 if (isReconfigSupported) {
563 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
564 : String8(AudioParameter::keyReconfigLe);
565 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 param.add(key, String8("true"));
567 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
568 devDesc->setEncodedFormat(encodedFormat);
569 return NO_ERROR;
570 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700571 }
572 }
cnx421bd2dcc42020-07-11 14:58:44 +0800573 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000574 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800575 for (size_t i = 0; i < mOutputs.size(); i++) {
576 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000577 // mute media strategies to avoid sending the music tail into
578 // the earpiece or headset.
579 if (desc->isStrategyActive(musicStrategy)) {
580 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
581 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
582 tempRecommendedMuteDuration : desc->latency() * 4;
583 if (muteWaitMs < tempMuteDurationMs) {
584 muteWaitMs = tempMuteDurationMs;
585 }
586 }
cnx421bd2dcc42020-07-11 14:58:44 +0800587 setStrategyMute(musicStrategy, true, desc);
588 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
589 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
590 nullptr, true /*fromCache*/).types());
591 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000592 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
593 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
594 // happens after the actual device switch.
595 if (muteWaitMs > 0) {
596 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
597 usleep(muteWaitMs * 1000);
598 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800599 // Toggle the device state: UNAVAILABLE -> AVAILABLE
600 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100601 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800602 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800603 device_address, device_name,
604 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800605 if (status != NO_ERROR) {
606 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
607 status);
608 return status;
609 }
610
611 status = setDeviceConnectionState(device,
612 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800613 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800614 if (status != NO_ERROR) {
615 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
616 status);
617 return status;
618 }
619
620 return NO_ERROR;
621}
622
Pattydd807582021-11-04 21:01:03 +0800623status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
624 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800625{
Pattydd807582021-11-04 21:01:03 +0800626 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800627 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800628 std::unordered_set<audio_format_t> formatSet;
629 sp<HwModule> primaryModule =
630 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700631 if (primaryModule == nullptr) {
632 ALOGE("%s() unable to get primary module", __func__);
633 return NO_INIT;
634 }
Pattydd807582021-11-04 21:01:03 +0800635
636 DeviceTypeSet audioDeviceSet;
637
638 switch(device) {
639 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
640 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
641 break;
642 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800643 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
644 break;
645 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
646 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800647 break;
648 default:
649 ALOGE("%s() device type 0x%08x not supported", __func__, device);
650 return BAD_VALUE;
651 }
652
jiabin9a3361e2019-10-01 09:38:30 -0700653 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800654 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800655 for (const auto& device : declaredDevices) {
656 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800657 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800658 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800659 return status;
660}
661
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
663{
664 DeviceVector rxSinkdevices{};
665 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
666 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
667 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
668 auto rxSinkDevice = rxSinkdevices.itemAt(0);
669 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
670 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
671 // retrieve Rx Source device descriptor
672 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
673 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
674
675 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
676 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
677 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
678 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
679 return DeviceVector(rxSinkDevice);
680 }
681 }
682 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
683 // the device returned is not necessarily reachable via this output
684 // (filter later by setOutputDevices())
685 return getNewOutputDevices(mPrimaryOutput, fromCache);
686}
687
688status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
689{
François Gaffiedb1755b2023-09-01 11:50:35 +0200690 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100691 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
692 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
693 }
694 return INVALID_OPERATION;
695}
696
697status_t AudioPolicyManager::updateCallRoutingInternal(
698 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700699{
700 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100701 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700702 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200703 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700704 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100705 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700706 }
François Gaffie11d30102018-11-02 16:09:09 +0100707
Francois Gaffie716e1432019-01-14 16:58:59 +0100708 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100709 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200710
711 disconnectTelephonyAudioSource(mCallRxSourceClient);
712 disconnectTelephonyAudioSource(mCallTxSourceClient);
713
714 if (rxDevices.isEmpty()) {
715 ALOGW("%s() no selected output device", __func__);
716 return INVALID_OPERATION;
717 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000718 if (txSourceDevice == nullptr) {
719 ALOGE("%s() selected input device not available", __func__);
720 return INVALID_OPERATION;
721 }
François Gaffiec005e562018-11-06 15:04:49 +0100722
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100723 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100724 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700725
François Gaffie9eb18552018-11-05 10:33:26 +0100726 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700727 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100728 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700729 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100730 // retrieve Rx Source and Tx Sink device descriptors
731 sp<DeviceDescriptor> rxSourceDevice =
732 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
733 String8(),
734 AUDIO_FORMAT_DEFAULT);
735 sp<DeviceDescriptor> txSinkDevice =
736 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
737 String8(),
738 AUDIO_FORMAT_DEFAULT);
739
740 // RX and TX Telephony device are declared by Primary Audio HAL
741 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
742 (telephonyRxModule->getHalVersionMajor() >= 3)) {
743 if (rxSourceDevice == 0 || txSinkDevice == 0) {
744 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100745 ALOGE("%s() no telephony Tx and/or RX device", __func__);
746 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100747 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100748 // createAudioPatchInternal now supports both HW / SW bridging
749 createRxPatch = true;
750 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100751 } else {
752 // If the RX device is on the primary HW module, then use legacy routing method for
753 // voice calls via setOutputDevice() on primary output.
754 // Otherwise, create two audio patches for TX and RX path.
755 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
756 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700757 // If the TX device is also on the primary HW module, setOutputDevice() will take care
758 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100759 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
760 (txSinkDevice != 0);
761 }
762 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
763 // Otherwise, create two audio patches for TX and RX path.
764 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200765 if (!hasPrimaryOutput()) {
766 ALOGW("%s() no primary output available", __func__);
767 return INVALID_OPERATION;
768 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530769 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700770 } else { // create RX path audio patch
David Li48b6a832024-07-01 13:14:10 +0000771 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800772 // If the TX device is on the primary HW module but RX device is
773 // on other HW module, SinkMetaData of telephony input should handle it
774 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700775 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700776 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100777 // terminate active capture if on the same HW module as the call TX source device
778 // FIXME: would be better to refine to only inputs whose profile connects to the
779 // call TX device but this information is not in the audio patch and logic here must be
780 // symmetric to the one in startInput()
781 for (const auto& activeDesc : mInputs.getActiveInputs()) {
782 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
783 closeActiveClients(activeDesc);
784 }
785 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200786 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800787 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100788 if (waitMs != nullptr) {
789 *waitMs = muteWaitMs;
790 }
791 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800792}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700793
Mikhail Naganov100f0122018-11-29 11:22:16 -0800794bool AudioPolicyManager::isDeviceOfModule(
795 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
796 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
797 if (module != 0) {
798 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
799 .indexOf(devDesc) != NAME_NOT_FOUND
800 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
801 .indexOf(devDesc) != NAME_NOT_FOUND;
802 }
803 return false;
804}
805
David Li48b6a832024-07-01 13:14:10 +0000806void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200807{
Francois Gaffie601801d2021-06-22 13:27:39 +0200808 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200809 const struct audio_port_config source = {
810 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
811 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
812 };
813 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100814
815 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent963dbcc2024-06-20 12:34:15 +0000816 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Li48b6a832024-07-01 13:14:10 +0000817 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100818 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
819 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200820 ALOGE_IF(mCallRxSourceClient == nullptr,
821 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200822}
823
Francois Gaffie601801d2021-06-22 13:27:39 +0200824void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200825{
Francois Gaffie601801d2021-06-22 13:27:39 +0200826 if (clientDesc == nullptr) {
827 return;
828 }
829 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
830 "%s error stopping audio source", __func__);
831 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200832}
833
834void AudioPolicyManager::connectTelephonyTxAudioSource(
835 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
836 uint32_t delayMs)
837{
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200839 if (srcDevice == nullptr || sinkDevice == nullptr) {
840 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
841 return;
842 }
843 PatchBuilder patchBuilder;
844 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
845 ALOGV("%s between source %s and sink %s", __func__,
846 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200847 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200848 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
849
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200850 struct audio_port_config source = {};
851 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100852 mCallTxSourceClient = new SourceClientDescriptor(
853 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurent963dbcc2024-06-20 12:34:15 +0000854 mCommunnicationStrategy, toVolumeSource(aa), true,
855 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100856 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
857
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200858 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
859 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200860 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
861 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200862 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
863 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200864 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200865 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200866}
867
Eric Laurente0720872014-03-11 09:30:41 -0700868void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700869{
870 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100871 // store previous phone state for management of sonification strategy below
872 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100873 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100874
875 if (mEngine->setPhoneState(state) != NO_ERROR) {
876 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700877 return;
878 }
François Gaffie2110e042015-03-24 08:41:51 +0100879 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700880 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700881 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700882 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800883 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700884 }
885
François Gaffie2110e042015-03-24 08:41:51 +0100886 /**
887 * Switching to or from incall state or switching between telephony and VoIP lead to force
888 * routing command.
889 */
Eric Laurent74b71512019-11-06 17:21:57 -0800890 bool force = ((isStateInCall(oldState) != isStateInCall(state))
891 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700892
893 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700894 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700895
Eric Laurente552edb2014-03-10 17:42:56 -0700896 int delayMs = 0;
897 if (isStateInCall(state)) {
898 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100899 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
900 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700901 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700902 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700903 // mute media and sonification strategies and delay device switch by the largest
904 // latency of any output where either strategy is active.
905 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100906 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
907 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
908 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700909 (delayMs < (int)desc->latency()*2)) {
910 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700911 }
François Gaffiec005e562018-11-06 15:04:49 +0100912 setStrategyMute(musicStrategy, true, desc);
913 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
914 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
915 nullptr, true /*fromCache*/).types());
916 setStrategyMute(sonificationStrategy, true, desc);
917 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
918 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
919 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700920 }
921 }
922
François Gaffiedb1755b2023-09-01 11:50:35 +0200923 if (state == AUDIO_MODE_IN_CALL) {
924 (void)updateCallRouting(false /*fromCache*/, delayMs);
925 } else {
926 if (oldState == AUDIO_MODE_IN_CALL) {
927 disconnectTelephonyAudioSource(mCallRxSourceClient);
928 disconnectTelephonyAudioSource(mCallTxSourceClient);
929 }
930 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100931 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
932 // force routing command to audio hardware when ending call
933 // even if no device change is needed
934 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
935 rxDevices = mPrimaryOutput->devices();
936 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530937 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700938 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700939 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700940
jiabin3ff8d7d2022-12-13 06:27:44 +0000941 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700942 // reevaluate routing on all outputs in case tracks have been started during the call
943 for (size_t i = 0; i < mOutputs.size(); i++) {
944 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100945 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000946 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
947 && desc->mPreferredAttrInfo != nullptr) {
948 // If the output is using preferred mixer attributes and the audio mode is not normal,
949 // the output need to reopen with default configuration.
950 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
951 continue;
952 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200953 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
954 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530955 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200956 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700957 }
958 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000959 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700960
Eric Laurent96d1dda2022-03-14 17:14:19 +0100961 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
962
Eric Laurente552edb2014-03-10 17:42:56 -0700963 if (isStateInCall(state)) {
964 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700965 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800966 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
968
969 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100970 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
971 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700972}
973
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700974audio_mode_t AudioPolicyManager::getPhoneState() {
975 return mEngine->getPhoneState();
976}
977
Eric Laurente0720872014-03-11 09:30:41 -0700978void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100979 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700980{
François Gaffie2110e042015-03-24 08:41:51 +0100981 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700982 if (config == mEngine->getForceUse(usage)) {
983 return;
984 }
Eric Laurente552edb2014-03-10 17:42:56 -0700985
François Gaffie2110e042015-03-24 08:41:51 +0100986 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
987 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
988 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700989 }
François Gaffie2110e042015-03-24 08:41:51 +0100990 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
991 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
992 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700993
994 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700995 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800996
Eric Laurent22fcda22019-05-17 16:28:47 -0700997 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
998 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800999 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001000 }
1001
Eric Laurentdc462862016-07-19 12:29:53 -07001002 //FIXME: workaround for truncated touch sounds
1003 // to be removed when the problem is handled by system UI
1004 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001005 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1006 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1007 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001008
1009 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001010 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001011}
1012
Eric Laurente0720872014-03-11 09:30:41 -07001013void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001014{
1015 ALOGV("setSystemProperty() property %s, value %s", property, value);
1016}
1017
Dorin Drimusecc9f422022-03-09 17:57:40 +01001018// Find an MSD output profile compatible with the parameters passed.
1019// When "directOnly" is set, restrict search to profiles for direct outputs.
1020sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1021 const DeviceVector& devices,
1022 uint32_t samplingRate,
1023 audio_format_t format,
1024 audio_channel_mask_t channelMask,
1025 audio_output_flags_t flags,
1026 bool directOnly)
1027{
1028 flags = getRelevantFlags(flags, directOnly);
1029
1030 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1031 if (msdModule != nullptr) {
1032 // for the msd module check if there are patches to the output devices
1033 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1034 HwModuleCollection modules;
1035 modules.add(msdModule);
1036 return searchCompatibleProfileHwModules(
1037 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1038 flags, directOnly);
1039 }
1040 }
1041 return nullptr;
1042}
1043
Michael Chana94fbb22018-04-24 14:31:19 +10001044// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1045// search to profiles for direct outputs.
1046sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001047 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001048 uint32_t samplingRate,
1049 audio_format_t format,
1050 audio_channel_mask_t channelMask,
1051 audio_output_flags_t flags,
1052 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001053{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001054 flags = getRelevantFlags(flags, directOnly);
1055
1056 return searchCompatibleProfileHwModules(
1057 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1058}
1059
1060audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1061 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001062 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 // only retain flags that will drive the direct output profile selection
1064 // if explicitly requested
1065 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001066 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1068 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001069 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001070 return flags;
1071}
Eric Laurent861a6282015-05-18 15:40:16 -07001072
Dorin Drimusecc9f422022-03-09 17:57:40 +01001073sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1074 const HwModuleCollection& hwModules,
1075 const DeviceVector& devices,
1076 uint32_t samplingRate,
1077 audio_format_t format,
1078 audio_channel_mask_t channelMask,
1079 audio_output_flags_t flags,
1080 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001081 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001082 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001083 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001084 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001085 samplingRate, NULL /*updatedSamplingRate*/,
1086 format, NULL /*updatedFormat*/,
1087 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001088 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001089 continue;
1090 }
1091 // reject profiles not corresponding to a device currently available
1092 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1093 continue;
1094 }
1095 // reject profiles if connected device does not support codec
1096 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1097 continue;
1098 }
1099 if (!directOnly) {
1100 return curProfile;
1101 }
1102
1103 // when searching for direct outputs, if several profiles are compatible, give priority
1104 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001105 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001106 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001107 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001108 }
1109 profile = curProfile;
1110 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1111 break;
1112 }
Eric Laurente552edb2014-03-10 17:42:56 -07001113 }
1114 }
Eric Laurent861a6282015-05-18 15:40:16 -07001115 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001116}
1117
Eric Laurentfa0f6742021-08-17 18:39:44 +02001118sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001119 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001120{
1121 for (const auto& hwModule : mHwModules) {
1122 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001123 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001124 continue;
1125 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001126 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001127 // reject profiles not corresponding to a device currently available
1128 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1129 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1130 continue;
1131 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001132 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1133 != devices.size()) {
1134 continue;
1135 }
1136 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001137 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1138 return curProfile;
1139 }
1140 }
1141 return nullptr;
1142}
1143
Eric Laurentf4e63452017-11-06 19:31:46 +00001144audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001145{
François Gaffiec005e562018-11-06 15:04:49 +01001146 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001147
1148 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1149 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1150 // format, flags, etc. This may result in some discrepancy for functions that utilize
1151 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1152 // and AudioSystem::getOutputSamplingRate().
1153
François Gaffie11d30102018-11-02 16:09:09 +01001154 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001155 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov285c1732024-09-05 17:26:50 -07001156 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001157 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1158 }
1159 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001160
François Gaffie11d30102018-11-02 16:09:09 +01001161 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1162 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001163 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001164}
1165
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001166status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1167 const audio_attributes_t *srcAttr,
1168 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001169{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001170 if (srcAttr != NULL) {
1171 if (!isValidAttributes(srcAttr)) {
1172 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1173 __func__,
1174 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1175 srcAttr->tags);
1176 return BAD_VALUE;
1177 }
1178 *dstAttr = *srcAttr;
1179 } else {
1180 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1181 ALOGE("%s: invalid stream type", __func__);
1182 return BAD_VALUE;
1183 }
François Gaffiec005e562018-11-06 15:04:49 +01001184 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001185 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001186
1187 // Only honor audibility enforced when required. The client will be
1188 // forced to reconnect if the forced usage changes.
1189 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001190 dstAttr->flags = static_cast<audio_flags_mask_t>(
1191 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001192 }
1193
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001194 return NO_ERROR;
1195}
1196
Kevin Rocard153f92d2018-12-18 18:33:28 -08001197status_t AudioPolicyManager::getOutputForAttrInt(
1198 audio_attributes_t *resultAttr,
1199 audio_io_handle_t *output,
1200 audio_session_t session,
1201 const audio_attributes_t *attr,
1202 audio_stream_type_t *stream,
1203 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001204 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001205 audio_output_flags_t *flags,
1206 audio_port_handle_t *selectedDeviceId,
1207 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001208 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001209 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001210 bool *isSpatialized,
1211 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001212{
François Gaffiec005e562018-11-06 15:04:49 +01001213 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001214 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001215 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001216 const sp<DeviceDescriptor> requestedDevice =
1217 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1218
Eric Laurent8a1095a2019-11-08 14:44:16 -08001219 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001220 *isSpatialized = false;
1221
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001222 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1223 if (status != NO_ERROR) {
1224 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001225 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001226 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001227 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001228 }
François Gaffiec005e562018-11-06 15:04:49 +01001229 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001230
François Gaffiec005e562018-11-06 15:04:49 +01001231 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1232 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001233
Oscar Azucena873d10f2023-01-12 18:34:42 -08001234 bool usePrimaryOutputFromPolicyMixes = false;
1235
Kevin Rocard153f92d2018-12-18 18:33:28 -08001236 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1237 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1238 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001239 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001240 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1241 .channel_mask = config->channel_mask,
1242 .format = config->format,
1243 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001244 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001245 mAvailableOutputDevices, requestedDevice, primaryMix,
1246 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001247 if (status != OK) {
1248 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001249 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001250
Kevin Rocard153f92d2018-12-18 18:33:28 -08001251 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001252 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungced57302024-08-14 11:37:57 -07001253 && (!audio_is_linear_pcm(config->format) ||
1254 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001255 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001256 return BAD_VALUE;
1257 }
1258 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001259 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001260 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1261 primaryMix->mDeviceAddress,
1262 AUDIO_FORMAT_DEFAULT);
1263 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001264 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001265 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1266 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001267 // if a direct output can be opened to deliver the track's multi-channel content to the
1268 // output rather than being downmixed by the primary output, then use this direct
1269 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1270 // mix.
1271 bool tryDirectForChannelMask = policyDesc != nullptr
1272 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1273 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001274 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001275 audio_io_handle_t newOutput;
1276 status = openDirectOutput(
1277 *stream, session, config,
1278 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001279 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001280 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001281 policyDesc = mOutputs.valueFor(newOutput);
1282 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001283 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001284 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001285 policyDesc = nullptr;
1286 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001287 }
1288 if (policyDesc != nullptr) {
1289 policyDesc->mPolicyMix = primaryMix;
1290 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001291 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1292 : AUDIO_PORT_HANDLE_NONE;
1293 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1294 // Remove direct flag as it is not on a direct output.
1295 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1296 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001297
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001298 ALOGV("getOutputForAttr() returns output %d", *output);
1299 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1300 *outputType = API_OUT_MIX_PLAYBACK;
1301 } else {
1302 *outputType = API_OUTPUT_LEGACY;
1303 }
1304 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001305 } else {
1306 if (policyMixDevice != nullptr) {
1307 ALOGE("%s, try to use primary mix but no output found", __func__);
1308 return INVALID_OPERATION;
1309 }
1310 // Fallback to default engine selection as the selected primary mix device is not
1311 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001312 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001313 }
François Gaffiec005e562018-11-06 15:04:49 +01001314 // Virtual sources must always be dynamicaly or explicitly routed
1315 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1316 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1317 return BAD_VALUE;
1318 }
1319 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1320 // in order to let the choice of the order to future vendor engine
1321 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001322
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001323 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001324 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001325 }
1326
Nadav Barb2f18162018-07-18 13:01:53 +03001327 // Set incall music only if device was explicitly set, and fallback to the device which is
1328 // chosen by the engine if not.
1329 // FIXME: provide a more generic approach which is not device specific and move this back
1330 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001331 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001332 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001333 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001334 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001335 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001336 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001337 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001338 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001339 }
1340 }
1341
François Gaffiec005e562018-11-06 15:04:49 +01001342 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1343 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1344 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001345
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001347 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001348 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001349 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001350 ALOGV("%s() Using MSD devices %s instead of devices %s",
1351 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001352 } else {
1353 *output = AUDIO_IO_HANDLE_NONE;
1354 }
1355 }
1356 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001357 sp<PreferredMixerAttributesInfo> info = nullptr;
1358 if (outputDevices.size() == 1) {
1359 info = getPreferredMixerAttributesInfo(
1360 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001361 mEngine->getProductStrategyForAttributes(*resultAttr),
1362 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001363 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1364 // and it is currently active.
1365 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001366 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001367 info = nullptr;
1368 }
jiabin220eea12024-05-17 17:55:20 +00001369 if (com::android::media::audioserver::
1370 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1371 if (info != nullptr && info->getUid() == uid &&
1372 info->configMatches(*config) &&
1373 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1374 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1375 [this, &outputDevices](audio_usage_t usage) {
1376 return mOutputs.isUsageActiveOnDevice(
1377 usage, outputDevices[0]); }))) {
1378 // Bit-perfect request is not allowed when the phone mode is not normal or
1379 // there is any higher priority user case active.
1380 return INVALID_OPERATION;
1381 }
1382 }
jiabina84c3d32022-12-02 18:59:55 +00001383 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001384 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001385 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001386 // The client will be active if the client is currently preferred mixer owner and the
1387 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001388 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001389 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001390 && info->getUid() == uid
1391 && *output != AUDIO_IO_HANDLE_NONE
1392 // When bit-perfect output is selected for the preferred mixer attributes owner,
1393 // only need to consider the config matches.
1394 && mOutputs.valueFor(*output)->isConfigurationMatched(
1395 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001396
1397 if (*isBitPerfect) {
1398 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1399 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001400 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001401 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001402 AudioProfileVector profiles;
1403 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1404 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001405 const auto channels = profiles[0]->getChannels();
1406 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1407 config->channel_mask = *channels.begin();
1408 }
1409 const auto sampleRates = profiles[0]->getSampleRates();
1410 if (!sampleRates.empty() &&
1411 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1412 config->sample_rate = *sampleRates.begin();
1413 }
jiabinf1c73972022-04-14 16:28:52 -07001414 config->format = profiles[0]->getFormat();
1415 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001416 return INVALID_OPERATION;
1417 }
Paul McLeanaa981192015-03-21 09:55:15 -07001418
François Gaffiec005e562018-11-06 15:04:49 +01001419 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001420 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001421 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001422 *selectedDeviceId = outputDevice->getId();
1423 break;
1424 }
1425 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001426
Eric Laurent8a1095a2019-11-08 14:44:16 -08001427 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1428 *outputType = API_OUTPUT_TELEPHONY_TX;
1429 } else {
1430 *outputType = API_OUTPUT_LEGACY;
1431 }
1432
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001433 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1434
1435 return NO_ERROR;
1436}
1437
1438status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1439 audio_io_handle_t *output,
1440 audio_session_t session,
1441 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001442 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001443 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001444 audio_output_flags_t *flags,
1445 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001446 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001447 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001448 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001449 bool *isSpatialized,
1450 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001451{
1452 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1453 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1454 return INVALID_OPERATION;
1455 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001456 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001457 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001458 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001459 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001460 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001461 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001462 const sp<DeviceDescriptor> requestedDevice =
1463 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1464
1465 // Prevent from storing invalid requested device id in clients
1466 const audio_port_handle_t sanitizedRequestedPortId =
1467 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1468 *selectedDeviceId = sanitizedRequestedPortId;
1469
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001470 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001471 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001472 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1473 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001474 if (status != NO_ERROR) {
1475 return status;
1476 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001477 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001478 if (secondaryOutputs != nullptr) {
1479 for (auto &secondaryMix : secondaryMixes) {
1480 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1481 if (outputDesc != nullptr &&
1482 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1483 secondaryOutputs->push_back(outputDesc->mIoHandle);
1484 weakSecondaryOutputDescs.push_back(outputDesc);
1485 }
1486 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001487 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001488
Eric Laurent8fc147b2018-07-22 19:13:55 -07001489 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001490 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001491 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001492 };
jiabin4ef93452019-09-10 14:29:54 -07001493 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001494
Eric Laurentc209fe42020-06-05 18:11:23 -07001495 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001496 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001497 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001498 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001499 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001500 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001501 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001502 std::move(weakSecondaryOutputDescs),
1503 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001504 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001505
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001506 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1507 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001508
Eric Laurente83b55d2014-11-14 10:06:21 -08001509 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001510}
1511
Eric Laurentc529cf62020-04-17 18:19:10 -07001512status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1513 audio_session_t session,
1514 const audio_config_t *config,
1515 audio_output_flags_t flags,
1516 const DeviceVector &devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001517 audio_io_handle_t *output,
1518 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001519
1520 *output = AUDIO_IO_HANDLE_NONE;
1521
1522 // skip direct output selection if the request can obviously be attached to a mixed output
1523 // and not explicitly requested
1524 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1525 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1526 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1527 return NAME_NOT_FOUND;
1528 }
1529
Mikhail Naganov285c1732024-09-05 17:26:50 -07001530 // Reject flag combinations that do not make sense. Note that the requested flags might not
1531 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1532 // combine the requested flags with its own flags, yielding an unsupported combination.
1533 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1534 return NAME_NOT_FOUND;
1535 }
1536
Eric Laurentc529cf62020-04-17 18:19:10 -07001537 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1538 // This prevents creating an offloaded track and tearing it down immediately after start
1539 // when audioflinger detects there is an active non offloadable effect.
1540 // FIXME: We should check the audio session here but we do not have it in this context.
1541 // This may prevent offloading in rare situations where effects are left active by apps
1542 // in the background.
1543 sp<IOProfile> profile;
1544 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1545 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1546 profile = getProfileForOutput(
1547 devices, config->sample_rate, config->format, config->channel_mask,
1548 flags, true /* directOnly */);
1549 }
1550
1551 if (profile == nullptr) {
1552 return NAME_NOT_FOUND;
1553 }
1554
1555 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1556 for (size_t i = 0; i < mOutputs.size(); i++) {
1557 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1558 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1559 // reuse direct output if currently open by the same client
1560 // and configured with same parameters
1561 if ((config->sample_rate == desc->getSamplingRate()) &&
1562 (config->format == desc->getFormat()) &&
1563 (config->channel_mask == desc->getChannelMask()) &&
1564 (session == desc->mDirectClientSession)) {
1565 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301566 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001567 mOutputs.keyAt(i), session);
1568 *output = mOutputs.keyAt(i);
1569 return NO_ERROR;
1570 }
1571 }
1572 }
1573
1574 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001575 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301576 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1577 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001578 return NAME_NOT_FOUND;
1579 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1580 // MMAP gracefully handles lack of an exclusive track resource by mixing
1581 // above the audio framework. For AAudio to know that the limit is reached,
1582 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301583 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1584 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001585 return NAME_NOT_FOUND;
1586 } else {
1587 // Close outputs on this profile, if available, to free resources for this request
1588 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1589 const auto desc = mOutputs.valueAt(i);
1590 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301591 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1592 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001593 closeOutput(desc->mIoHandle);
1594 }
1595 }
1596 }
1597 }
1598
1599 // Unable to close streams to find free resources for this request
1600 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301601 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1602 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001603 return NAME_NOT_FOUND;
1604 }
1605
Atneya Nairb16666a2023-12-11 20:18:33 -08001606 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001607
Michael Chan6fb34492020-12-08 15:44:49 +11001608 // An MSD patch may be using the only output stream that can service this request. Release
1609 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001610 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001611
Eric Laurentf1f22e72021-07-13 14:04:14 +02001612 status_t status =
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001613 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1614 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001615
1616 // only accept an output with the requested parameters
1617 if (status != NO_ERROR ||
1618 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1619 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1620 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1621 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1622 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1623 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1624 config->channel_mask, outputDesc->getChannelMask());
1625 if (*output != AUDIO_IO_HANDLE_NONE) {
1626 outputDesc->close();
1627 }
1628 // fall back to mixer output if possible when the direct output could not be open
1629 if (audio_is_linear_pcm(config->format) &&
1630 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1631 return NAME_NOT_FOUND;
1632 }
1633 *output = AUDIO_IO_HANDLE_NONE;
1634 return BAD_VALUE;
1635 }
1636 outputDesc->mDirectOpenCount = 1;
1637 outputDesc->mDirectClientSession = session;
1638
1639 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001640 setOutputDevices(__func__, outputDesc,
1641 devices,
1642 true,
1643 0,
1644 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001645 mPreviousOutputs = mOutputs;
1646 ALOGV("%s returns new direct output %d", __func__, *output);
1647 mpClientInterface->onAudioPortListUpdate();
1648 return NO_ERROR;
1649}
1650
François Gaffie11d30102018-11-02 16:09:09 +01001651audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1652 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001653 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001654 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001655 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001656 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001657 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001658 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001659 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001660{
Andy Hungc88b0642018-04-27 15:42:35 -07001661 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001662
jiabine375d412019-02-26 12:54:53 -08001663 // Discard haptic channel mask when forcing muting haptic channels.
1664 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001665 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1666 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001667
Eric Laurente552edb2014-03-10 17:42:56 -07001668 // open a direct output if required by specified parameters
1669 //force direct flag if offload flag is set: offloading implies a direct output stream
1670 // and all common behaviors are driven by checking only the direct flag
1671 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001672 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1673 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001674 }
Nadav Bar766fb022018-01-07 12:18:03 +02001675 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1676 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001677 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001678
1679 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1680
Eric Laurente83b55d2014-11-14 10:06:21 -08001681 // only allow deep buffering for music stream type
1682 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001683 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001684 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov285c1732024-09-05 17:26:50 -07001685 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001686 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001687 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001688 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001689 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001690 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001691 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001692 audio_is_linear_pcm(config->format) &&
1693 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001694 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001695 AUDIO_OUTPUT_FLAG_DIRECT);
1696 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001697 }
Eric Laurente552edb2014-03-10 17:42:56 -07001698
Carter Hsua3abb402021-10-26 11:11:20 +08001699 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1700 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1701 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1702 }
1703
Eric Laurentf9230d52024-01-26 18:49:09 +01001704 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001705 // was specified and offload or direct playback is not explicitly requested, and there is no
1706 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001707 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001708 if (mSpatializerOutput != nullptr &&
1709 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1710 prefMixerConfigInfo == nullptr &&
1711 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1712 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001713 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001714 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001715 }
1716
Eric Laurentc529cf62020-04-17 18:19:10 -07001717 audio_config_t directConfig = *config;
1718 directConfig.channel_mask = channelMask;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001719
1720 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1721 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001722 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001723 return output;
1724 }
1725
Eric Laurent14cbfca2016-03-17 09:42:16 -07001726 // A request for HW A/V sync cannot fallback to a mixed output because time
1727 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001728 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001729 return AUDIO_IO_HANDLE_NONE;
1730 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001731 // A request for Tuner cannot fallback to a mixed output
1732 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1733 return AUDIO_IO_HANDLE_NONE;
1734 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001735
Eric Laurente552edb2014-03-10 17:42:56 -07001736 // ignoring channel mask due to downmix capability in mixer
1737
1738 // open a non direct output
1739
1740 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001741 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001742 // get which output is suitable for the specified stream. The actual
1743 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001744 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001745 if (prefMixerConfigInfo != nullptr) {
1746 for (audio_io_handle_t outputHandle : outputs) {
1747 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1748 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1749 output = outputHandle;
1750 break;
1751 }
1752 }
1753 if (output == AUDIO_IO_HANDLE_NONE) {
1754 // No output open with the preferred profile. Open a new one.
1755 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1756 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1757 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1758 config.format = prefMixerConfigInfo->getConfigBase().format;
1759 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1760 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1761 &config, prefMixerConfigInfo->getFlags());
1762 if (preferredOutput == nullptr) {
1763 ALOGE("%s failed to open output with preferred mixer config", __func__);
1764 } else {
1765 output = preferredOutput->mIoHandle;
1766 }
1767 }
1768 } else {
1769 // at this stage we should ignore the DIRECT flag as no direct output could be
1770 // found earlier
1771 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001772 if (com::android::media::audioserver::
1773 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1774 // If the preferred mixer attributes is null, do not select the bit-perfect output
1775 // unless the bit-perfect output is the only output.
1776 // The bit-perfect output can exist while the passed in preferred mixer attributes
1777 // info is null when it is a high priority client. The high priority clients are
1778 // ringtone or alarm, which is not a bit-perfect use case.
1779 size_t i = 0;
1780 while (i < outputs.size() && outputs.size() > 1) {
1781 auto desc = mOutputs.valueFor(outputs[i]);
1782 // The output descriptor must not be null here.
1783 if (desc->isBitPerfect()) {
1784 outputs.removeItemsAt(i);
1785 } else {
1786 i += 1;
1787 }
1788 }
1789 }
jiabina84c3d32022-12-02 18:59:55 +00001790 output = selectOutput(
1791 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1792 }
Eric Laurente552edb2014-03-10 17:42:56 -07001793 }
François Gaffie11d30102018-11-02 16:09:09 +01001794 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001795 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001796 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001797
Eric Laurente552edb2014-03-10 17:42:56 -07001798 return output;
1799}
1800
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001801sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001802 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1803 mAvailableInputDevices);
1804 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1805}
1806
1807DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1808 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1809 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001810}
1811
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001812const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001813 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001814 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1815 if (msdModule != 0) {
1816 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1817 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1818 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1819 const struct audio_port_config *source = &patch->mPatch.sources[j];
1820 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1821 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001822 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001823 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001824 }
1825 }
1826 }
1827 return msdPatches;
1828}
1829
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001830bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1831 ssize_t index = mAudioPatches.indexOfKey(handle);
1832 if (index < 0) {
1833 return false;
1834 }
1835 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1836 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1837 if (msdModule == nullptr) {
1838 return false;
1839 }
1840 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1841 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1842 return true;
1843 }
1844 index = getMsdOutputPatches().indexOfKey(handle);
1845 if (index < 0) {
1846 return false;
1847 }
1848 return true;
1849}
1850
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001851status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1852 const InputProfileCollection &inputProfiles,
1853 const OutputProfileCollection &outputProfiles,
1854 const sp<DeviceDescriptor> &sourceDevice,
1855 const sp<DeviceDescriptor> &sinkDevice,
1856 AudioProfileVector& sourceProfiles,
1857 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001858 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001859 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001860 return NO_INIT;
1861 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001862 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001863 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001864 return NO_INIT;
1865 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001866 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001867 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1868 inProfile->supportsDevice(sourceDevice)) {
1869 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001870 }
1871 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001872 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001873 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001874 outProfile->supportsDevice(sinkDevice)) {
1875 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001876 }
1877 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001878 return NO_ERROR;
1879}
1880
1881status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1882 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1883 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1884{
Dean Wheatley16809da2022-12-09 14:55:46 +11001885 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1886 static const std::vector<audio_format_t> formatsOrder = {{
1887 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001888 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1889 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001890 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1891 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1892 // preferred).
1893 std::vector<audio_channel_mask_t> masks = {{
1894 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1895 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1896 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1897 // insert index masks (higher counts most preferred) as preferred over position masks
1898 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1899 masks.insert(
1900 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1901 }
1902 return masks;
1903 }();
1904
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001905 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001906 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1907 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001908 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001909 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1910 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001911 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001912 }
1913 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1914 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1915 sinkConfig->format = bestSinkConfig.format;
1916 // For encoded streams force direct flag to prevent downstream mixing.
1917 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1918 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001919 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1920 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001921 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001922 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1923 // raw and IEC61937 framed streams.
1924 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1925 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1926 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001927 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1928 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001929 sourceConfig->channel_mask =
1930 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1931 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1932 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001933 sourceConfig->format = bestSinkConfig.format;
1934 // Copy input stream directly without any processing (e.g. resampling).
1935 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1936 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1937 if (hwAvSync) {
1938 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1939 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1940 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1941 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1942 }
1943 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1944 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1945 sinkConfig->config_mask |= config_mask;
1946 sourceConfig->config_mask |= config_mask;
1947 return NO_ERROR;
1948}
1949
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001950PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1951 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952{
1953 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001954 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1955 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1956 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1957 if (deviceModule == nullptr) {
1958 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1959 return patchBuilder;
1960 }
1961 const InputProfileCollection inputProfiles = msdIsSource ?
1962 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1963 const OutputProfileCollection outputProfiles = msdIsSource ?
1964 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1965
1966 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1967 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1968 device : getMsdAudioOutDevices().itemAt(0);
1969 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1970
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001971 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1972 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001973 AudioProfileVector sourceProfiles;
1974 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001975 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1976 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001977 for (auto hwAvSync : { true, false }) {
1978 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1979 sourceProfiles, sinkProfiles) != NO_ERROR) {
1980 continue;
1981 }
1982 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1983 &sinkConfig) == NO_ERROR) {
1984 // Found a matching config. Re-create PatchBuilder with this config.
1985 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1986 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001987 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001988 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001989 " supporting PCM format conversion.", __func__);
1990 return patchBuilder;
1991}
1992
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001993status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001994 DeviceVector devices;
1995 if (outputDevices != nullptr && outputDevices->size() > 0) {
1996 devices.add(*outputDevices);
1997 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001998 // Use media strategy for unspecified output device. This should only
1999 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2000 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002001 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002002 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002003 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002004 }
Michael Chan6fb34492020-12-08 15:44:49 +11002005 std::vector<PatchBuilder> patchesToCreate;
2006 for (auto i = 0u; i < devices.size(); ++i) {
2007 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002008 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002009 }
2010 // Retain only the MSD patches associated with outputDevices request.
2011 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002012 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002013 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2014 auto retainedPatch = false;
2015 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2016 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2017 patchesToRemove.removeItemsAt(i);
2018 retainedPatch = true;
2019 break;
2020 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002021 }
Michael Chan6fb34492020-12-08 15:44:49 +11002022 if (retainedPatch) {
2023 it = patchesToCreate.erase(it);
2024 continue;
2025 }
2026 ++it;
2027 }
2028 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2029 return NO_ERROR;
2030 }
2031 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2032 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002033 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002034 }
Michael Chan6fb34492020-12-08 15:44:49 +11002035 status_t status = NO_ERROR;
2036 for (const auto &p : patchesToCreate) {
2037 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2038 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2039 char message[256];
2040 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2041 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2042 currStatus == NO_ERROR ? "Success" : "Error",
2043 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2044 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2045 if (currStatus == NO_ERROR) {
2046 ALOGD("%s", message);
2047 } else {
2048 ALOGE("%s", message);
2049 if (status == NO_ERROR) {
2050 status = currStatus;
2051 }
2052 }
2053 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002054 return status;
2055}
2056
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002057void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2058 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002059 for (size_t i = 0; i < msdPatches.size(); i++) {
2060 const auto& patch = msdPatches[i];
2061 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2062 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2063 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2064 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2065 releaseAudioPatch(patch->getHandle(), mUidCached);
2066 break;
2067 }
2068 }
2069 }
2070}
2071
Dorin Drimus94d94412022-02-02 09:05:02 +01002072bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002073 DeviceVector devicesToCheck =
2074 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002075 AudioPatchCollection msdPatches = getMsdOutputPatches();
2076 for (size_t i = 0; i < msdPatches.size(); i++) {
2077 const auto& patch = msdPatches[i];
2078 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2079 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2080 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2081 const auto& foundDevice = devicesToCheck.getDevice(
2082 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2083 if (foundDevice != nullptr) {
2084 devicesToCheck.remove(foundDevice);
2085 if (devicesToCheck.isEmpty()) {
2086 return true;
2087 }
2088 }
2089 }
2090 }
2091 }
2092 return false;
2093}
2094
Eric Laurente0720872014-03-11 09:30:41 -07002095audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002096 audio_output_flags_t flags,
2097 audio_format_t format,
2098 audio_channel_mask_t channelMask,
2099 uint32_t samplingRate,
2100 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002101{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002102 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2103 "%s called with format %#x", __func__, format);
2104
jiabinebb6af42020-06-09 17:31:17 -07002105 // Return the output that haptic-generating attached to when 1) session id is specified,
2106 // 2) haptic-generating effect exists for given session id and 3) the output that
2107 // haptic-generating effect attached to is in given outputs.
2108 if (sessionId != AUDIO_SESSION_NONE) {
2109 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2110 sessionId, FX_IID_HAPTICGENERATOR);
2111 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2112 return hapticGeneratingOutput;
2113 }
2114 }
2115
Eric Laurent16c66dd2019-05-01 17:54:10 -07002116 // Flags disqualifying an output: the match must happen before calling selectOutput()
2117 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2118 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2119
2120 // Flags expressing a functional request: must be honored in priority over
2121 // other criteria
2122 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2123 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002124 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2125 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002126 // Flags expressing a performance request: have lower priority than serving
2127 // requested sampling rate or channel mask
2128 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2129 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2130 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2131
2132 const audio_output_flags_t functionalFlags =
2133 (audio_output_flags_t)(flags & kFunctionalFlags);
2134 const audio_output_flags_t performanceFlags =
2135 (audio_output_flags_t)(flags & kPerformanceFlags);
2136
2137 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2138
Eric Laurente552edb2014-03-10 17:42:56 -07002139 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002140 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002141 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002142 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002143 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002144 // with tiebreak preferring the minimum number of extra functional flags
2145 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002146 // 3: the output supporting the exact channel mask
2147 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002148 // 5: the output with the highest sampling rate if the requested sample rate is
2149 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002150 // 6: the output with the highest number of requested performance flags
2151 // 7: the output with the bit depth the closest to the requested one
2152 // 8: the primary output
2153 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002154
Eric Laurent16c66dd2019-05-01 17:54:10 -07002155 // matching criteria values in priority order for best matching output so far
2156 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002157
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002158 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002159 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2160 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2161 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002162
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002163 for (audio_io_handle_t output : outputs) {
2164 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002165 // matching criteria values in priority order for current output
2166 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002167
Eric Laurent16c66dd2019-05-01 17:54:10 -07002168 if (outputDesc->isDuplicated()) {
2169 continue;
2170 }
2171 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2172 continue;
2173 }
Eric Laurent8838a382014-09-08 16:44:28 -07002174
Eric Laurent16c66dd2019-05-01 17:54:10 -07002175 // If haptic channel is specified, use the haptic output if present.
2176 // When using haptic output, same audio format and sample rate are required.
2177 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002178 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002179 // skip if haptic channel specified but output does not support it, or output support haptic
2180 // but there is no haptic channel requested AND no orphan haptic effect exist
2181 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2182 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002183 continue;
2184 }
Shunkai Yao808da212024-04-05 22:50:56 +00002185 // In the case of audio-coupled-haptic playback, there is no format conversion and
2186 // resampling in the framework, same format/channel/sampleRate for client and the output
2187 // thread is required. In the case of HapticGenerator effect, do not require format
2188 // matching.
2189 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2190 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002191 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002192 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002193 }
2194
2195 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002196 const int matchingFunctionalFlags =
2197 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2198 const int totalFunctionalFlags =
2199 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2200 // Prefer matching functional flags, but subtract unnecessary functional flags.
2201 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002202
2203 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002204 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2205 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002206 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2207 channelCount <= outputChannelCount) {
2208 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002209 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2210 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002211 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002212 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002213 currentMatchCriteria[3] = outputChannelCount;
2214 }
2215
2216 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002217 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002218 int diff; // avoid unsigned integer overflow.
2219 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2220
2221 // prefer the closest output sampling rate greater than or equal to target
2222 // if none exists, prefer the closest output sampling rate less than target.
2223 //
2224 // criteria is offset to make non-negative.
2225 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002226 }
2227
2228 // performance flags match
2229 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2230
2231 // format match
2232 if (format != AUDIO_FORMAT_INVALID) {
2233 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002234 PolicyAudioPort::kFormatDistanceMax -
2235 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002236 }
2237
2238 // primary output match
2239 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2240
2241 // compare match criteria by priority then value
2242 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2243 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2244 bestMatchCriteria = currentMatchCriteria;
2245 bestOutput = output;
2246
2247 std::stringstream result;
2248 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2249 std::ostream_iterator<int>(result, " "));
2250 ALOGV("%s new bestOutput %d criteria %s",
2251 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002252 }
2253 }
2254
Eric Laurent16c66dd2019-05-01 17:54:10 -07002255 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002256}
2257
Eric Laurent8fc147b2018-07-22 19:13:55 -07002258status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002259{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002260 ALOGV("%s portId %d", __FUNCTION__, portId);
2261
2262 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2263 if (outputDesc == 0) {
2264 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002265 return BAD_VALUE;
2266 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002267 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002268
Eric Laurent8fc147b2018-07-22 19:13:55 -07002269 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002270 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002271
jiabin220eea12024-05-17 17:55:20 +00002272 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2273 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2274 && outputDesc->isBitPerfect()) {
2275 // Usually, APM selects bit-perfect output for high priority use cases only when
2276 // bit-perfect output is the only output that can be routed to the selected device.
2277 // However, here is no need to play high priority use cases such as ringtone and alarm
2278 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2279 // can attach to new output.
2280 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2281 __func__, client->stream());
2282 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2283 return DEAD_OBJECT;
2284 }
2285
Eric Laurent733ce942017-12-07 12:18:25 -08002286 status_t status = outputDesc->start();
2287 if (status != NO_ERROR) {
2288 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002289 }
2290
Eric Laurent97ac8712018-07-27 18:59:02 -07002291 uint32_t delayMs;
2292 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002293
2294 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002295 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002296 if (status == DEAD_OBJECT) {
2297 sp<SwAudioOutputDescriptor> desc =
2298 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2299 if (desc == nullptr) {
2300 // This is not common, it may indicate something wrong with the HAL.
2301 ALOGE("%s unable to open output with default config", __func__);
2302 return status;
2303 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002304 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002305 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002306 }
jiabina84c3d32022-12-02 18:59:55 +00002307
2308 // If the client is the first one active on preferred mixer parameters, reopen the output
2309 // if the current mixer parameters doesn't match the preferred one.
2310 if (outputDesc->devices().size() == 1) {
2311 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2312 outputDesc->devices()[0]->getId(), client->strategy());
2313 if (info != nullptr && info->getUid() == client->uid()) {
2314 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2315 info->getConfigBase(), info->getFlags())) {
2316 stopSource(outputDesc, client);
2317 outputDesc->stop();
2318 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2319 config.channel_mask = info->getConfigBase().channel_mask;
2320 config.sample_rate = info->getConfigBase().sample_rate;
2321 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002322 sp<SwAudioOutputDescriptor> desc =
2323 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2324 if (desc == nullptr) {
2325 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002326 }
jiabin220eea12024-05-17 17:55:20 +00002327 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002328 // Intentionally return error to let the client side resending request for
2329 // creating and starting.
2330 return DEAD_OBJECT;
2331 }
2332 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002333 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002334 // If it is first bit-perfect client, reroute all clients that will be routed to
2335 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2336 PortHandleVector clientsToInvalidate;
2337 for (size_t i = 0; i < mOutputs.size(); i++) {
2338 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002339 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002340 continue;
2341 }
2342 for (const auto& c : mOutputs[i]->getClientIterable()) {
2343 clientsToInvalidate.push_back(c->portId());
2344 }
2345 }
2346 if (!clientsToInvalidate.empty()) {
2347 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2348 __func__);
2349 mpClientInterface->invalidateTracks(clientsToInvalidate);
2350 }
2351 }
jiabina84c3d32022-12-02 18:59:55 +00002352 }
2353 }
2354
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002355 if (client->hasPreferredDevice()) {
2356 // playback activity with preferred device impacts routing occurred, inform upper layers
2357 mpClientInterface->onRoutingUpdated();
2358 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002359 if (delayMs != 0) {
2360 usleep(delayMs * 1000);
2361 }
2362
jiabin220eea12024-05-17 17:55:20 +00002363 if (status == NO_ERROR &&
2364 outputDesc->mPreferredAttrInfo != nullptr &&
2365 outputDesc->isBitPerfect() &&
2366 com::android::media::audioserver::
2367 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2368 // A new client is started on bit-perfect output, update all clients internal mute.
2369 updateClientsInternalMute(outputDesc);
2370 }
2371
Eric Laurentc75307b2015-03-17 15:29:32 -07002372 return status;
2373}
2374
Eric Laurent96d1dda2022-03-14 17:14:19 +01002375bool AudioPolicyManager::isLeUnicastActive() const {
2376 if (isInCall()) {
2377 return true;
2378 }
2379 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2380}
2381
2382bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2383 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2384 return false;
2385 }
2386 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2387 ALOGV("%s active %d", __func__, active);
2388 return active;
2389}
2390
Eric Laurent97ac8712018-07-27 18:59:02 -07002391status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2392 const sp<TrackClientDescriptor>& client,
2393 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002394{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002395 // cannot start playback of STREAM_TTS if any other output is being used
2396 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002397
2398 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002399 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002400 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002401 auto clientStrategy = client->strategy();
2402 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002403 if (stream == AUDIO_STREAM_TTS) {
2404 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002405 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002406 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002407 return INVALID_OPERATION;
2408 } else {
2409 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2410 }
2411 } else {
2412 // some playback other than beacon starts
2413 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2414 }
2415
Eric Laurent77305a62016-07-25 16:39:22 -07002416 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002417 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002418 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002419
François Gaffie11d30102018-11-02 16:09:09 +01002420 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002421 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002422 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002423 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002424 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002425 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002426 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002427 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002428 } else {
2429 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002430 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002431 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2432 AUDIO_FORMAT_DEFAULT);
2433 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2434 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002435 }
2436
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002437 // requiresMuteCheck is false when we can bypass mute strategy.
2438 // It covers a common case when there is no materially active audio
2439 // and muting would result in unnecessary delay and dropped audio.
2440 const uint32_t outputLatencyMs = outputDesc->latency();
2441 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002442 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002443
Eric Laurente552edb2014-03-10 17:42:56 -07002444 // increment usage count for this stream on the requested output:
2445 // NOTE that the usage count is the same for duplicated output and hardware output which is
2446 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002447 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002448
2449 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002450 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002451 // Preferred device may be exclusive, use only if no other active clients on this output
2452 devices = DeviceVector(
2453 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2454 } else {
2455 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2456 }
François Gaffie11d30102018-11-02 16:09:09 +01002457 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002458 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002459 }
2460 }
Eric Laurente552edb2014-03-10 17:42:56 -07002461
François Gaffiec005e562018-11-06 15:04:49 +01002462 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002463 selectOutputForMusicEffects();
2464 }
2465
François Gaffie1c878552018-11-22 16:53:21 +01002466 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002467 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002468 if (devices.isEmpty()) {
2469 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002470 }
François Gaffiec005e562018-11-06 15:04:49 +01002471 bool shouldWait =
2472 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2473 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2474 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002475 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002476 const bool needToCloseBitPerfectOutput =
2477 (com::android::media::audioserver::
2478 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2479 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2480 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002481 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002482 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002483 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002484 // An output has a shared device if
2485 // - managed by the same hw module
2486 // - supports the currently selected device
2487 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002488 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002489
Eric Laurent77305a62016-07-25 16:39:22 -07002490 // force a device change if any other output is:
2491 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002492 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002493 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002494 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002495 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002496 // change the device currently selected by the other output.
2497 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002498 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002499 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002500 force = true;
2501 }
2502 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002503 // a notification so that audio focus effect can propagate, or that a mute/unmute
2504 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002505 const uint32_t latencyMs = desc->latency();
2506 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2507
2508 if (shouldWait && isActive && (waitMs < latencyMs)) {
2509 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002510 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002511
2512 // Require mute check if another output is on a shared device
2513 // and currently active to have proper drain and avoid pops.
2514 // Note restoring AudioTracks onto this output needs to invoke
2515 // a volume ramp if there is no mute.
2516 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002517
2518 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2519 outputsToReopen.push_back(desc);
2520 }
Eric Laurente552edb2014-03-10 17:42:56 -07002521 }
2522 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002523
jiabin220eea12024-05-17 17:55:20 +00002524 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002525 // If the output is open with preferred mixer attributes, but the routed device is
2526 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2527 // changed.
2528 return DEAD_OBJECT;
2529 }
jiabin220eea12024-05-17 17:55:20 +00002530 for (auto& outputToReopen : outputsToReopen) {
2531 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2532 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002533 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302534 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2535 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002536
Eric Laurente552edb2014-03-10 17:42:56 -07002537 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002538 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002539 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002540 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002541 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002542 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002543 outputDesc->useHwGain() /*force*/)) {
2544 // request AudioService to reinitialize the volume curves asynchronously
2545 ALOGE("checkAndSetVolume failed, requesting volume range init");
2546 mpClientInterface->onVolumeRangeInitRequest();
2547 };
Eric Laurente552edb2014-03-10 17:42:56 -07002548
2549 // update the outputs if starting an output with a stream that can affect notification
2550 // routing
2551 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002552
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002553 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002554 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002555 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002556 }
Eric Laurentdc462862016-07-19 12:29:53 -07002557
2558 if (waitMs > muteWaitMs) {
2559 *delayMs = waitMs - muteWaitMs;
2560 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002561
2562 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2563 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2564 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2565 // change occurs after the MixerThread starts and causes a stream volume
2566 // glitch.
2567 //
2568 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002569 }
Eric Laurentdc462862016-07-19 12:29:53 -07002570
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002571 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002572 mEngine->getForceUse(
2573 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002574 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002575 }
2576
Eric Laurent97ac8712018-07-27 18:59:02 -07002577 // Automatically enable the remote submix input when output is started on a re routing mix
2578 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002579 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2580 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002581 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2582 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2583 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002584 "remote-submix",
2585 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002586 }
2587
Eric Laurent96d1dda2022-03-14 17:14:19 +01002588 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2589
Eric Laurente552edb2014-03-10 17:42:56 -07002590 return NO_ERROR;
2591}
2592
Eric Laurent96d1dda2022-03-14 17:14:19 +01002593void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2594 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2595 bool isUnicastActive = isLeUnicastActive();
2596
2597 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002598 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002599 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2600 for (size_t i = 0; i < mOutputs.size(); i++) {
2601 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2602 if (desc != ignoredOutput && desc->isActive()
2603 && ((isUnicastActive &&
2604 !desc->devices().
2605 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2606 || (wasUnicastActive &&
2607 !desc->devices().getDevicesFromTypes(
2608 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2609 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2610 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002611 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002612 // If the device is using preferred mixer attributes, the output need to reopen
2613 // with default configuration when the new selected devices are different from
2614 // current routing devices.
2615 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2616 continue;
2617 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302618 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002619 // re-apply device specific volume if not done by setOutputDevice()
2620 if (!force) {
2621 applyStreamVolumes(desc, newDevices.types(), delayMs);
2622 }
2623 }
2624 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002625 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002626 }
2627}
2628
Eric Laurent8fc147b2018-07-22 19:13:55 -07002629status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002630{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002631 ALOGV("%s portId %d", __FUNCTION__, portId);
2632
2633 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2634 if (outputDesc == 0) {
2635 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002636 return BAD_VALUE;
2637 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002638 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002639
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002640 if (client->hasPreferredDevice(true)) {
2641 // playback activity with preferred device impacts routing occurred, inform upper layers
2642 mpClientInterface->onRoutingUpdated();
2643 }
2644
Eric Laurent97ac8712018-07-27 18:59:02 -07002645 ALOGV("stopOutput() output %d, stream %d, session %d",
2646 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002647
Eric Laurent97ac8712018-07-27 18:59:02 -07002648 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002649
Eric Laurent733ce942017-12-07 12:18:25 -08002650 if (status == NO_ERROR ) {
2651 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002652 } else {
2653 return status;
2654 }
2655
2656 if (outputDesc->devices().size() == 1) {
2657 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2658 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002659 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002660 if (info != nullptr && info->getUid() == client->uid()) {
2661 info->decreaseActiveClient();
2662 if (info->getActiveClientCount() == 0) {
2663 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002664 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002665 }
2666 }
jiabin220eea12024-05-17 17:55:20 +00002667 if (com::android::media::audioserver::
2668 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2669 !outputReopened && outputDesc->isBitPerfect()) {
2670 // Only need to update the clients' internal mute when the output is bit-perfect and it
2671 // is not reopened.
2672 updateClientsInternalMute(outputDesc);
2673 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002674 }
2675 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002676}
2677
Eric Laurent97ac8712018-07-27 18:59:02 -07002678status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2679 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002680{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002681 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002682 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002683 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002684 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002685
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002686 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2687
François Gaffie1c878552018-11-22 16:53:21 +01002688 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2689 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002690 // Automatically disable the remote submix input when output is stopped on a
2691 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002692 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002693 if (isSingleDeviceType(
2694 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002695 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002696 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002697 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2698 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002699 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002700 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002701 }
2702 }
2703 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002704 if (client->hasPreferredDevice(true) &&
2705 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002706 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002707 forceDeviceUpdate = true;
2708 }
2709
Eric Laurente552edb2014-03-10 17:42:56 -07002710 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002711 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002712
Eric Laurente552edb2014-03-10 17:42:56 -07002713 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002714 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002715 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002716 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002717
2718 // If the routing does not change, if an output is routed on a device using HwGain
2719 // (aka setAudioPortConfig) and there are still active clients following different
2720 // volume group(s), force reapply volume
2721 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2722 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2723
Eric Laurente552edb2014-03-10 17:42:56 -07002724 // delay the device switch by twice the latency because stopOutput() is executed when
2725 // the track stop() command is received and at that time the audio track buffer can
2726 // still contain data that needs to be drained. The latency only covers the audio HAL
2727 // and kernel buffers. Also the latency does not always include additional delay in the
2728 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302729 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002730 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002731
2732 // force restoring the device selection on other active outputs if it differs from the
2733 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002734 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002735 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002736 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002737 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002738 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002739 desc->isActive() &&
2740 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002741 (newDevices != desc->devices())) {
2742 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2743 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002744
jiabin220eea12024-05-17 17:55:20 +00002745 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002746 // If the device is using preferred mixer attributes, the output need to
2747 // reopen with default configuration when the new selected devices are
2748 // different from current routing devices.
2749 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2750 continue;
2751 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302752 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002753
Eric Laurent57de36c2016-09-28 16:59:11 -07002754 // re-apply device specific volume if not done by setOutputDevice()
2755 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002756 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002757 }
Eric Laurente552edb2014-03-10 17:42:56 -07002758 }
2759 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002760 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002761 // update the outputs if stopping one with a stream that can affect notification routing
2762 handleNotificationRoutingForStream(stream);
2763 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002764
2765 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2766 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002767 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002768 }
2769
François Gaffiec005e562018-11-06 15:04:49 +01002770 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002771 selectOutputForMusicEffects();
2772 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002773
2774 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2775
Eric Laurente552edb2014-03-10 17:42:56 -07002776 return NO_ERROR;
2777 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002778 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002779 return INVALID_OPERATION;
2780 }
2781}
2782
jiabinbce0c1d2020-10-05 11:20:18 -07002783bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002784{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002785 ALOGV("%s portId %d", __FUNCTION__, portId);
2786
2787 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2788 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002789 // If an output descriptor is closed due to a device routing change,
2790 // then there are race conditions with releaseOutput from tracks
2791 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2792 // destroyed shortly thereafter.
2793 //
2794 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002795 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002796 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002797 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002798
2799 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002800
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302801 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2802 if (outputDesc->isClientActive(client)) {
2803 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2804 stopOutput(portId);
2805 }
2806
Eric Laurent8fc147b2018-07-22 19:13:55 -07002807 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2808 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002809 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002810 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002811 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002812 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002813 if (--outputDesc->mDirectOpenCount == 0) {
2814 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002815 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002816 }
2817 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302818
Andy Hung39efb7a2018-09-26 15:39:28 -07002819 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002820 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2821 // The output is pending reopened to query dynamic profiles and
2822 // there is no active clients
2823 closeOutput(outputDesc->mIoHandle);
2824 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2825 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2826 if (newOutputDesc == nullptr) {
2827 ALOGE("%s failed to open output", __func__);
2828 }
2829 return true;
2830 }
2831 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002832}
2833
Eric Laurentcaf7f482014-11-25 17:50:47 -08002834status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2835 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002836 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002837 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002838 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002839 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002840 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002841 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002842 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002843 audio_port_handle_t *portId,
2844 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002845{
François Gaffiec005e562018-11-06 15:04:49 +01002846 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002847 "flags %#x attributes=%s requested device ID %d",
2848 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2849 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002850
Eric Laurentad2e7b92017-09-14 20:06:42 -07002851 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002852 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002853 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002854 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002855 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002856 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002857 sp<RecordClientDescriptor> clientDesc;
2858 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002859 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002861
2862 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2863 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2864 return INVALID_OPERATION;
2865 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002866
Francois Gaffie716e1432019-01-14 16:58:59 +01002867 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2868 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002869 }
2870
Paul McLean466dc8e2015-04-17 13:15:36 -06002871 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002872 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002873 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002874
Eric Laurentad2e7b92017-09-14 20:06:42 -07002875 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2876 // possible
2877 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2878 *input != AUDIO_IO_HANDLE_NONE) {
2879 ssize_t index = mInputs.indexOfKey(*input);
2880 if (index < 0) {
2881 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2882 status = BAD_VALUE;
2883 goto error;
2884 }
2885 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002886 RecordClientVector clients = inputDesc->getClientsForSession(session);
2887 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002888 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2889 status = BAD_VALUE;
2890 goto error;
2891 }
2892 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2893 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002894 // corresponds to a new client and is only permitted from the same UID.
2895 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002896 if (clients.size() > 1) {
2897 for (const auto& client : clients) {
2898 // The client map is ordered by key values (portId) and portIds are allocated
2899 // incrementaly. So the first client in this list is the one opened by audio flinger
2900 // when the mmap stream is created and should be ignored as it does not correspond
2901 // to an actual client
2902 if (client == *clients.cbegin()) {
2903 continue;
2904 }
2905 if (uid != client->uid() && !client->isSilenced()) {
2906 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2907 uid, client->portId(), client->uid());
2908 status = INVALID_OPERATION;
2909 goto error;
2910 }
Eric Laurent331679c2018-04-16 17:03:16 -07002911 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002912 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002913 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002914 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002915
Eric Laurentfecbceb2021-02-09 14:46:43 +01002916 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002917 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002918 }
2919
2920 *input = AUDIO_IO_HANDLE_NONE;
2921 *inputType = API_INPUT_INVALID;
2922
Francois Gaffie716e1432019-01-14 16:58:59 +01002923 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002924 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002925 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002926 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002927 ALOGW("%s could not find input mix for attr %s",
2928 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002929 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002930 }
jiabinc1de2df2019-05-07 14:26:40 -07002931 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2932 String8(attr->tags + strlen("addr=")),
2933 AUDIO_FORMAT_DEFAULT);
2934 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002935 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002936 __func__, attributes.source, attributes.tags);
2937 status = BAD_VALUE;
2938 goto error;
2939 }
2940
Kevin Rocard25f9b052019-02-27 15:08:54 -08002941 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2942 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2943 } else {
2944 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2945 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002946 if (virtualDeviceId) {
2947 *virtualDeviceId = policyMix->mVirtualDeviceId;
2948 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002949 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002950 if (explicitRoutingDevice != nullptr) {
2951 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002952 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002953 // Prevent from storing invalid requested device id in clients
2954 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002955 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002956 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2957 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002958 }
François Gaffie11d30102018-11-02 16:09:09 +01002959 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002960 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002961 status = BAD_VALUE;
2962 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002963 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002964 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2965 *inputType = API_INPUT_MIX_CAPTURE;
2966 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002967 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2968 // there is an external policy, but this input is attached to a mix of recorders,
2969 // meaning it receives audio injected into the framework, so the recorder doesn't
2970 // know about it and is therefore considered "legacy"
2971 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002972
2973 if (virtualDeviceId) {
2974 *virtualDeviceId = policyMix->mVirtualDeviceId;
2975 }
François Gaffie11d30102018-11-02 16:09:09 +01002976 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002977 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002978 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002979 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002980 } else {
2981 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002982 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002983
Eric Laurent599c7582015-12-07 18:05:55 -08002984 }
2985
François Gaffiec005e562018-11-06 15:04:49 +01002986 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002987 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002988 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002989 AudioProfileVector profiles;
2990 status_t ret = getProfilesForDevices(
2991 DeviceVector(device), profiles, flags, true /*isInput*/);
2992 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002993 const auto channels = profiles[0]->getChannels();
2994 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2995 config->channel_mask = *channels.begin();
2996 }
2997 const auto sampleRates = profiles[0]->getSampleRates();
2998 if (!sampleRates.empty() &&
2999 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3000 config->sample_rate = *sampleRates.begin();
3001 }
jiabinf1c73972022-04-14 16:28:52 -07003002 config->format = profiles[0]->getFormat();
3003 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003004 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003005 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003006
Marvin Ramine5a122d2023-12-07 13:57:59 +01003007
3008 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3009 *virtualDeviceId = policyMix->mVirtualDeviceId;
3010 }
3011
Eric Laurent8f42ea12018-08-08 09:08:25 -07003012exit:
3013
François Gaffiec005e562018-11-06 15:04:49 +01003014 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3015 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003016
Francois Gaffie716e1432019-01-14 16:58:59 +01003017 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003018 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003019 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003020
Mikhail Naganov2996f672019-04-18 12:29:59 -07003021 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003022 requestedDeviceId, attributes.source, flags,
3023 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003024 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003025 // Move (if found) effect for the client session to its input
3026 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003027 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003028
3029 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3030 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003031
Eric Laurent599c7582015-12-07 18:05:55 -08003032 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003033
3034error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003035 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003036}
3037
3038
François Gaffie11d30102018-11-02 16:09:09 +01003039audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003040 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003041 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003042 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003043 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003044 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003045{
3046 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003047 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003048 bool isSoundTrigger = false;
3049
François Gaffiec005e562018-11-06 15:04:49 +01003050 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003051 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3052 if (index >= 0) {
3053 input = mSoundTriggerSessions.valueFor(session);
3054 isSoundTrigger = true;
3055 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3056 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3057 } else {
3058 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003059 }
François Gaffiec005e562018-11-06 15:04:49 +01003060 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003061 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003062 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003063 }
3064
Carter Hsua3abb402021-10-26 11:11:20 +08003065 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3066 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3067 }
3068
Eric Laurentfe231122017-11-17 17:48:06 -08003069 // sampling rate and flags may be updated by getInputProfile
3070 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3071 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003072 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003073 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003074 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003075 // find a compatible input profile (not necessarily identical in parameters)
3076 sp<IOProfile> profile = getInputProfile(
3077 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3078 if (profile == nullptr) {
3079 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003080 }
jiabin2fd710d2022-05-02 23:20:22 +00003081
Glenn Kasten05ddca52016-02-11 08:17:12 -08003082 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003083 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003084 if (samplingRate == 0) {
3085 samplingRate = profileSamplingRate;
3086 }
Eric Laurente552edb2014-03-10 17:42:56 -07003087
Eric Laurent322b4d22015-04-03 15:57:54 -07003088 if (profile->getModuleHandle() == 0) {
3089 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003090 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003091 }
3092
Eric Laurentec376dc2021-04-08 20:41:22 +02003093 // Reuse an already opened input if a client with the same session ID already exists
3094 // on that input
3095 for (size_t i = 0; i < mInputs.size(); i++) {
3096 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3097 if (desc->mProfile != profile) {
3098 continue;
3099 }
3100 RecordClientVector clients = desc->clientsList();
3101 for (const auto &client : clients) {
3102 if (session == client->session()) {
3103 return desc->mIoHandle;
3104 }
3105 }
3106 }
3107
Eric Laurent3974e3b2017-12-07 17:58:43 -08003108 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003109 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003110 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003111 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003112 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003113 continue;
3114 }
3115 // if sound trigger, reuse input if used by other sound trigger on same session
3116 // else
3117 // reuse input if active client app is not in IDLE state
3118 //
3119 RecordClientVector clients = desc->clientsList();
3120 bool doClose = false;
3121 for (const auto& client : clients) {
3122 if (isSoundTrigger != client->isSoundTrigger()) {
3123 continue;
3124 }
3125 if (client->isSoundTrigger()) {
3126 if (session == client->session()) {
3127 return desc->mIoHandle;
3128 }
3129 continue;
3130 }
3131 if (client->active() && client->appState() != APP_STATE_IDLE) {
3132 return desc->mIoHandle;
3133 }
3134 doClose = true;
3135 }
3136 if (doClose) {
3137 closeInput(desc->mIoHandle);
3138 } else {
3139 i++;
3140 }
3141 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003142 }
3143
Eric Laurentfe231122017-11-17 17:48:06 -08003144 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003145
Eric Laurentfe231122017-11-17 17:48:06 -08003146 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3147 lConfig.sample_rate = profileSamplingRate;
3148 lConfig.channel_mask = profileChannelMask;
3149 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003150
François Gaffie11d30102018-11-02 16:09:09 +01003151 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003152
3153 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003154 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003155 (profileSamplingRate != lConfig.sample_rate) ||
3156 !audio_formats_match(profileFormat, lConfig.format) ||
3157 (profileChannelMask != lConfig.channel_mask)) {
3158 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003159 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003160 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003161 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003162 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003163 }
Eric Laurent599c7582015-12-07 18:05:55 -08003164 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003165 }
3166
Eric Laurentc722f302014-12-10 11:21:49 -08003167 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003168
Eric Laurent599c7582015-12-07 18:05:55 -08003169 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003170 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003171
Eric Laurent599c7582015-12-07 18:05:55 -08003172 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003173}
3174
Eric Laurent4eb58f12018-12-07 16:41:02 -08003175status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003176{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003177 ALOGV("%s portId %d", __FUNCTION__, portId);
3178
3179 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3180 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003181 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003182 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003183 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003184 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003185 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003186 if (client->active()) {
3187 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3188 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003189 }
3190
Eric Laurent8f42ea12018-08-08 09:08:25 -07003191 audio_session_t session = client->session();
3192
Eric Laurent4eb58f12018-12-07 16:41:02 -08003193 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003194
Eric Laurent4eb58f12018-12-07 16:41:02 -08003195 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003196
Eric Laurent4eb58f12018-12-07 16:41:02 -08003197 status_t status = inputDesc->start();
3198 if (status != NO_ERROR) {
3199 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003200 }
Eric Laurente552edb2014-03-10 17:42:56 -07003201
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003202 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003203 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003204 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003205
Eric Laurent8f42ea12018-08-08 09:08:25 -07003206 // indicate active capture to sound trigger service if starting capture from a mic on
3207 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003208 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003209 if (device != nullptr) {
3210 status = setInputDevice(input, device, true /* force */);
3211 } else {
3212 ALOGW("%s no new input device can be found for descriptor %d",
3213 __FUNCTION__, inputDesc->getId());
3214 status = BAD_VALUE;
3215 }
Eric Laurente552edb2014-03-10 17:42:56 -07003216
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003217 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003218 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003219 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003220 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003221 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3222 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003223 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003224 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003225
François Gaffie11d30102018-11-02 16:09:09 +01003226 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3227 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003228 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003229 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003230 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003231
Eric Laurent8f42ea12018-08-08 09:08:25 -07003232 // automatically enable the remote submix output when input is started if not
3233 // used by a policy mix of type MIX_TYPE_RECORDERS
3234 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003235 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003236 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003237 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003238 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003239 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3240 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003241 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003242 if (address != "") {
3243 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3244 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003245 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003246 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003247 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003248 } else if (status != NO_ERROR) {
3249 // Restore client activity state.
3250 inputDesc->setClientActive(client, false);
3251 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003252 }
3253
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003254 ALOGV("%s input %d source = %d status = %d exit",
3255 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003256
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003257 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003258}
3259
Eric Laurent8fc147b2018-07-22 19:13:55 -07003260status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003261{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003262 ALOGV("%s portId %d", __FUNCTION__, portId);
3263
3264 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3265 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003266 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003267 return BAD_VALUE;
3268 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003269 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003270 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003271 if (!client->active()) {
3272 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003273 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003274 }
Carter Hsue6139d52021-07-08 10:30:20 +08003275 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003276 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003277
Eric Laurent8f42ea12018-08-08 09:08:25 -07003278 inputDesc->stop();
3279 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003280 auto current_source = inputDesc->source();
3281 setInputDevice(input, getNewInputDevice(inputDesc),
3282 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003283 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003284 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003285 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003286 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003287 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3288 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003289 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003290 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003291
3292 // automatically disable the remote submix output when input is stopped if not
3293 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003294 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003295 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003296 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003297 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003298 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3299 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003300 }
3301 if (address != "") {
3302 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3303 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003304 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003305 }
3306 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003307 resetInputDevice(input);
3308
3309 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3310 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003311 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3312 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003313 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003314 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003315 }
3316 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003317 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003318 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003319}
3320
Eric Laurent8fc147b2018-07-22 19:13:55 -07003321void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003322{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003323 ALOGV("%s portId %d", __FUNCTION__, portId);
3324
3325 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3326 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003327 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003328 return;
3329 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003330 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003331 audio_io_handle_t input = inputDesc->mIoHandle;
3332
Eric Laurent8f42ea12018-08-08 09:08:25 -07003333 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003334
Andy Hung39efb7a2018-09-26 15:39:28 -07003335 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003336
3337 // If no more clients are present in this session, park effects to an orphan chain
3338 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3339 if (clientsOnSession.size() == 0) {
3340 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3341 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003342 if (inputDesc->getClientCount() > 0) {
3343 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003344 return;
3345 }
3346
Eric Laurent05b90f82014-08-27 15:32:29 -07003347 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003348 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003349 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003350}
3351
Eric Laurent8f42ea12018-08-08 09:08:25 -07003352void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003353{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003354 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003355
3356 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003357 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003358 }
3359}
3360
Eric Laurent8f42ea12018-08-08 09:08:25 -07003361void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3362{
3363 stopInput(portId);
3364 releaseInput(portId);
3365}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003366
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003367bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3368 if (input->clientsList().size() == 0
3369 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3370 return true;
3371 }
3372 for (const auto& client : input->clientsList()) {
3373 sp<DeviceDescriptor> device =
3374 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3375 client->session());
3376 if (!input->supportedDevices().contains(device)) {
3377 return true;
3378 }
3379 }
3380 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3381 return false;
3382}
3383
Eric Laurent0dd51852019-04-19 18:18:58 -07003384void AudioPolicyManager::checkCloseInputs() {
3385 // After connecting or disconnecting an input device, close input if:
3386 // - it has no client (was just opened to check profile) OR
3387 // - none of its supported devices are connected anymore OR
3388 // - one of its clients cannot be routed to one of its supported
3389 // devices anymore. Otherwise update device selection
3390 std::vector<audio_io_handle_t> inputsToClose;
3391 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003392 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003393 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003394 }
3395 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003396 for (const audio_io_handle_t handle : inputsToClose) {
3397 ALOGV("%s closing input %d", __func__, handle);
3398 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003399 }
Eric Laurentd4692962014-05-05 18:13:44 -07003400}
3401
Vlad Popa87e0e582024-05-20 18:49:20 -07003402status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3403 const char *address __unused,
3404 bool enabled,
3405 audio_stream_type_t streamToDriveAbs)
3406{
3407 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3408 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3409 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3410 toString(streamToDriveAbs).c_str());
3411 return BAD_VALUE;
3412 }
3413
3414 if (enabled) {
3415 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3416 } else {
3417 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3418 }
3419
3420 return NO_ERROR;
3421}
3422
François Gaffie251c7f02018-11-07 10:41:08 +01003423void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003424{
3425 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003426 if (indexMin < 0 || indexMax < 0) {
3427 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3428 return;
3429 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003430 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003431
3432 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003433 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3434 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003435 continue;
3436 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003437 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003438 }
Eric Laurente552edb2014-03-10 17:42:56 -07003439}
3440
Eric Laurente0720872014-03-11 09:30:41 -07003441status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003442 int index,
3443 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003444{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003445 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003446 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3447 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3448 return NO_ERROR;
3449 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303450 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3451 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003452 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003453}
3454
Eric Laurente0720872014-03-11 09:30:41 -07003455status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003456 int *index,
3457 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003458{
François Gaffiec005e562018-11-06 15:04:49 +01003459 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3460 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003461 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003462 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003463 deviceTypes = mEngine->getOutputDevicesForStream(
3464 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003465 }
jiabin9a3361e2019-10-01 09:38:30 -07003466 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003467}
3468
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003469status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003470 int index,
3471 audio_devices_t device)
3472{
3473 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003474 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3475 if (group == VOLUME_GROUP_NONE) {
3476 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003477 return BAD_VALUE;
3478 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003479 ALOGV("%s: group %d matching with %s index %d",
3480 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003481 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003482 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003483 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003484 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3485 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3486 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3487 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003488 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3489
3490 status = setVolumeCurveIndex(index, device, curves);
3491 if (status != NO_ERROR) {
3492 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3493 return status;
3494 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003495
jiabin9a3361e2019-10-01 09:38:30 -07003496 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003497 auto curCurvAttrs = curves.getAttributes();
3498 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3499 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003500 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003501 } else if (!curves.getStreamTypes().empty()) {
3502 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003503 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003504 } else {
3505 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3506 return BAD_VALUE;
3507 }
jiabin9a3361e2019-10-01 09:38:30 -07003508 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3509 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003510
François Gaffiecfe17322018-11-07 13:41:29 +01003511 // update volume on all outputs and streams matching the following:
3512 // - The requested stream (or a stream matching for volume control) is active on the output
3513 // - The device (or devices) selected by the engine for this stream includes
3514 // the requested device
3515 // - For non default requested device, currently selected device on the output is either the
3516 // requested device or one of the devices selected by the engine for this stream
3517 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3518 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003519 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003520 for (size_t i = 0; i < mOutputs.size(); i++) {
3521 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003522 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003523
jiabin9a3361e2019-10-01 09:38:30 -07003524 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3525 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003526 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003527
3528 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003529 continue;
3530 }
3531 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3532 curDevices.find(device) == curDevices.end()) {
3533 continue;
3534 }
3535 bool applyVolume = false;
3536 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3537 curSrcDevices.insert(device);
3538 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003539 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3540 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003541 } else {
3542 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3543 }
3544 if (!applyVolume) {
3545 continue; // next output
3546 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003547 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3548 // If a higher priority strategy is active, and the output is routed to a device with a
3549 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003550 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003551 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003552 // If the volume source is active with higher priority source, ensure at least Sw Muted
3553 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003554 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3555 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3556 false /*preferredDevice*/);
3557 if (activeClients.empty()) {
3558 continue;
3559 }
3560 bool isPreempted = false;
3561 bool isHigherPriority = productStrategy < strategy;
3562 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003563 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003564 ALOGV("%s: Strategy=%d (\nrequester:\n"
3565 " group %d, volumeGroup=%d attributes=%s)\n"
3566 " higher priority source active:\n"
3567 " volumeGroup=%d attributes=%s) \n"
3568 " on output %zu, bailing out", __func__, productStrategy,
3569 group, group, toString(attributes).c_str(),
3570 client->volumeSource(), toString(client->attributes()).c_str(), i);
3571 applyVolume = false;
3572 isPreempted = true;
3573 break;
3574 }
3575 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003576 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003577 applyVolume = true;
3578 }
3579 }
3580 if (isPreempted || applyVolume) {
3581 break;
3582 }
3583 }
3584 if (!applyVolume) {
3585 continue; // next output
3586 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003587 }
François Gaffieed91f582020-01-31 10:35:37 +01003588 //FIXME: workaround for truncated touch sounds
3589 // delayed volume change for system stream to be removed when the problem is
3590 // handled by system UI
3591 status_t volStatus = checkAndSetVolume(
3592 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003593 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003594 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3595 if (volStatus != NO_ERROR) {
3596 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003597 }
3598 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003599
3600 // update voice volume if the an active call route exists
3601 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3602 && (curSrcDevices.find(
3603 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3604 != curSrcDevices.end())) {
3605 bool isVoiceVolSrc;
3606 bool isBtScoVolSrc;
3607 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3608 isVoiceVolSrc, isBtScoVolSrc, __func__)
3609 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003610 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3611 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3612 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003613 }
3614 }
3615
François Gaffiecfe17322018-11-07 13:41:29 +01003616 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3617 return status;
3618}
3619
François Gaffieaaac0fd2018-11-22 17:56:39 +01003620status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003621 audio_devices_t device,
3622 IVolumeCurves &volumeCurves)
3623{
3624 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3625 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003626 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3627 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003628 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303629 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3630 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003631 return BAD_VALUE;
3632 }
3633 if (!audio_is_output_device(device)) {
3634 return BAD_VALUE;
3635 }
3636
3637 // Force max volume if stream cannot be muted
3638 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3639
François Gaffieaaac0fd2018-11-22 17:56:39 +01003640 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003641 volumeCurves.addCurrentVolumeIndex(device, index);
3642 return NO_ERROR;
3643}
3644
3645status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3646 int &index,
3647 audio_devices_t device)
3648{
3649 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3650 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003651 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003652 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003653 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003654 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003655 }
jiabin9a3361e2019-10-01 09:38:30 -07003656 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003657}
3658
3659status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3660 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003661 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003662{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003663 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003664 return BAD_VALUE;
3665 }
jiabin9a3361e2019-10-01 09:38:30 -07003666 index = curves.getVolumeIndex(deviceTypes);
3667 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003668 return NO_ERROR;
3669}
3670
3671status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3672 int &index)
3673{
3674 index = getVolumeCurves(attr).getVolumeIndexMin();
3675 return NO_ERROR;
3676}
3677
3678status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3679 int &index)
3680{
3681 index = getVolumeCurves(attr).getVolumeIndexMax();
3682 return NO_ERROR;
3683}
3684
Eric Laurent36829f92017-04-07 19:04:42 -07003685audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003686{
3687 // select one output among several suitable for global effects.
3688 // The priority is as follows:
3689 // 1: An offloaded output. If the effect ends up not being offloadable,
3690 // AudioFlinger will invalidate the track and the offloaded output
3691 // will be closed causing the effect to be moved to a PCM output.
3692 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003693 // 3: The primary output
3694 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003695
François Gaffiec005e562018-11-06 15:04:49 +01003696 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3697 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003698 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003699
Eric Laurent36829f92017-04-07 19:04:42 -07003700 if (outputs.size() == 0) {
3701 return AUDIO_IO_HANDLE_NONE;
3702 }
Eric Laurente552edb2014-03-10 17:42:56 -07003703
Eric Laurent36829f92017-04-07 19:04:42 -07003704 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3705 bool activeOnly = true;
3706
3707 while (output == AUDIO_IO_HANDLE_NONE) {
3708 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3709 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3710 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3711
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003712 for (audio_io_handle_t output : outputs) {
3713 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003714 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003715 continue;
3716 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003717 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3718 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003719 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003720 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003721 }
3722 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003723 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003724 }
3725 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003726 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003727 }
3728 }
3729 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3730 output = outputOffloaded;
3731 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3732 output = outputDeepBuffer;
3733 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3734 output = outputPrimary;
3735 } else {
3736 output = outputs[0];
3737 }
3738 activeOnly = false;
3739 }
3740
3741 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003742 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3743 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003744 mMusicEffectOutput = output;
3745 }
3746
3747 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003748 return output;
3749}
3750
Eric Laurent36829f92017-04-07 19:04:42 -07003751audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3752{
3753 return selectOutputForMusicEffects();
3754}
3755
Eric Laurente0720872014-03-11 09:30:41 -07003756status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003757 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003758 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003759 int session,
3760 int id)
3761{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003762 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003763 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003764 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003765 index = mInputs.indexOfKey(io);
3766 if (index < 0) {
3767 ALOGW("registerEffect() unknown io %d", io);
3768 return INVALID_OPERATION;
3769 }
Eric Laurente552edb2014-03-10 17:42:56 -07003770 }
3771 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003772 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3773 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3774 || strategy == PRODUCT_STRATEGY_NONE));
3775 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003776}
3777
Eric Laurentc241b0d2018-11-28 09:08:49 -08003778status_t AudioPolicyManager::unregisterEffect(int id)
3779{
3780 if (mEffects.getEffect(id) == nullptr) {
3781 return INVALID_OPERATION;
3782 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003783 if (mEffects.isEffectEnabled(id)) {
3784 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3785 setEffectEnabled(id, false);
3786 }
3787 return mEffects.unregisterEffect(id);
3788}
3789
3790status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3791{
3792 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3793 if (effect == nullptr) {
3794 return INVALID_OPERATION;
3795 }
3796
3797 status_t status = mEffects.setEffectEnabled(id, enabled);
3798 if (status == NO_ERROR) {
3799 mInputs.trackEffectEnabled(effect, enabled);
3800 }
3801 return status;
3802}
3803
Eric Laurent6c796322019-04-09 14:13:17 -07003804
3805status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3806{
3807 mEffects.moveEffects(ids, io);
3808 return NO_ERROR;
3809}
3810
Eric Laurentc75307b2015-03-17 15:29:32 -07003811bool AudioPolicyManager::isStreamActive(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.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003815}
3816
3817bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3818{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003819 auto vs = toVolumeSource(stream, false);
3820 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003821}
3822
Eric Laurente0720872014-03-11 09:30:41 -07003823bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003824{
3825 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003826 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003827 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003828 return true;
3829 }
3830 }
3831 return false;
3832}
3833
Eric Laurent275e8e92014-11-30 15:14:47 -08003834// Register a list of custom mixes with their attributes and format.
3835// When a mix is registered, corresponding input and output profiles are
3836// added to the remote submix hw module. The profile contains only the
3837// parameters (sampling rate, format...) specified by the mix.
3838// The corresponding input remote submix device is also connected.
3839//
3840// When a remote submix device is connected, the address is checked to select the
3841// appropriate profile and the corresponding input or output stream is opened.
3842//
3843// When capture starts, getInputForAttr() will:
3844// - 1 look for a mix matching the address passed in attribtutes tags if any
3845// - 2 if none found, getDeviceForInputSource() will:
3846// - 2.1 look for a mix matching the attributes source
3847// - 2.2 if none found, default to device selection by policy rules
3848// At this time, the corresponding output remote submix device is also connected
3849// and active playback use cases can be transferred to this mix if needed when reconnecting
3850// after AudioTracks are invalidated
3851//
3852// When playback starts, getOutputForAttr() will:
3853// - 1 look for a mix matching the address passed in attribtutes tags if any
3854// - 2 if none found, look for a mix matching the attributes usage
3855// - 3 if none found, default to device and output selection by policy rules.
3856
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003857status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003858{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003859 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3860 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003861 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003862 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003863 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003864 // examine each mix's route type
3865 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003866 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003867 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3868 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3869 ALOGE("Unsupported Policy Mix %zu of %zu: "
3870 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3871 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003872 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003873 break;
3874 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003875 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3876 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003877 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003878 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3879 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003880 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003881 rSubmixModule = mHwModules.getModuleFromName(
3882 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3883 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003884 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003885 i);
3886 res = INVALID_OPERATION;
3887 break;
3888 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003889 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003890
Eric Laurent97ac8712018-07-27 18:59:02 -07003891 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003892 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003893 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003894 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003895 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3896 } else {
3897 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3898 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003899 }
François Gaffie036e1e92015-03-19 10:16:24 +01003900
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003901 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003902 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003903 res = INVALID_OPERATION;
3904 break;
3905 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003906 audio_config_t outputConfig = mix.mFormat;
3907 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003908 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3909 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003910 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3911 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003912 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003913 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3914 audio_is_linear_pcm(outputConfig.format)
3915 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003916 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003917 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3918 audio_is_linear_pcm(inputConfig.format)
3919 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003920
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003921 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003922 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003923 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003924 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003925 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003926 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003927 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003928 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3929 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003930 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003931 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003932 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003933
3934 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3935 mix.mDeviceType, mix.mDeviceAddress,
3936 String8(), AUDIO_FORMAT_DEFAULT);
3937 if (device == nullptr) {
3938 res = INVALID_OPERATION;
3939 break;
3940 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003941
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003942 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003943 // First try to find an already opened output supporting the device
3944 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003945 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003946
Eric Laurentc529cf62020-04-17 18:19:10 -07003947 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003948 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003949 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003950 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003951 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003952 } else {
3953 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003954 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003955 }
3956 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003957 // If no output found, try to find a direct output profile supporting the device
3958 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3959 sp<HwModule> module = mHwModules[i];
3960 for (size_t j = 0;
3961 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3962 j++) {
3963 sp<IOProfile> profile = module->getOutputProfiles()[j];
3964 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3965 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3966 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003967 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003968 res = INVALID_OPERATION;
3969 } else {
3970 foundOutput = true;
3971 }
3972 }
3973 }
3974 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003975 if (res != NO_ERROR) {
3976 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003977 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003978 res = INVALID_OPERATION;
3979 break;
3980 } else if (!foundOutput) {
3981 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003982 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003983 res = INVALID_OPERATION;
3984 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003985 } else {
3986 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003987 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003988 }
Eric Laurentc722f302014-12-10 11:21:49 -08003989 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003990 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003991 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003992 if (audio_flags::audio_mix_ownership()) {
3993 // Only unregister mixes that were actually registered to not accidentally unregister
3994 // mixes that already existed previously.
3995 unregisterPolicyMixes(registeredMixes);
3996 registeredMixes.clear();
3997 } else {
3998 unregisterPolicyMixes(mixes);
3999 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004000 } else if (checkOutputs) {
4001 checkForDeviceAndOutputChanges();
4002 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004003 }
4004 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004005}
4006
4007status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4008{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004009 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004010 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004011 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004012 sp<HwModule> rSubmixModule;
4013 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004014 for (const auto& mix : mixes) {
4015 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004016
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004017 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004018 rSubmixModule = mHwModules.getModuleFromName(
4019 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4020 if (rSubmixModule == 0) {
4021 res = INVALID_OPERATION;
4022 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004023 }
4024 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004025
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004026 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004027
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004028 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004029 res = INVALID_OPERATION;
4030 continue;
4031 }
4032
Marvin Ramin0783e202024-03-05 12:45:50 +01004033 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004034 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004035 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4036 status_t currentRes =
4037 setDeviceConnectionStateInt(device,
4038 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4039 address.c_str(),
4040 "remote-submix",
4041 AUDIO_FORMAT_DEFAULT);
4042 if (!audio_flags::audio_mix_ownership()) {
4043 res = currentRes;
4044 }
4045 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004046 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004047 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004048 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004049 }
4050 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004051 }
jiabin5740f082019-08-19 15:08:30 -07004052 rSubmixModule->removeOutputProfile(address.c_str());
4053 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004054
Kevin Rocard153f92d2018-12-18 18:33:28 -08004055 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004056 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004057 res = INVALID_OPERATION;
4058 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004059 } else {
4060 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004061 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004062 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004063 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004064
4065 if (res == NO_ERROR && checkOutputs) {
4066 checkForDeviceAndOutputChanges();
4067 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004068 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004069 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004070}
4071
Marvin Raminbdefaf02023-11-01 09:10:32 +01004072status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4073 if (!audio_flags::audio_mix_test_api()) {
4074 return INVALID_OPERATION;
4075 }
4076
4077 _aidl_return.clear();
4078 _aidl_return.reserve(mPolicyMixes.size());
4079 for (const auto &policyMix: mPolicyMixes) {
4080 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4081 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4082 policyMix->mCbFlags);
4083 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004084 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004085 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004086 }
4087
Vlad Popaa5d73f32024-03-08 16:05:38 -08004088 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004089 return OK;
4090}
4091
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004092status_t AudioPolicyManager::updatePolicyMix(
4093 const AudioMix& mix,
4094 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4095 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4096 if (res == NO_ERROR) {
4097 checkForDeviceAndOutputChanges();
4098 updateCallAndOutputRouting();
4099 }
4100 return res;
4101}
4102
Mikhail Naganov100f0122018-11-29 11:22:16 -08004103void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4104{
4105 size_t i = 0;
4106 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4107 for (const auto& fmt : mManualSurroundFormats) {
4108 if (i++ != 0) dst->append(", ");
4109 std::string sfmt;
4110 FormatConverter::toString(fmt, sfmt);
4111 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4112 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4113 }
4114}
4115
Eric Laurentc529cf62020-04-17 18:19:10 -07004116// Returns true if all devices types match the predicate and are supported by one HW module
4117bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004118 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004119 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004120 const char *context,
4121 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004122 for (size_t i = 0; i < devices.size(); i++) {
4123 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004124 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004125 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004126 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004127 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004128 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004129 return false;
4130 }
4131 }
4132 return true;
4133}
4134
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004135void AudioPolicyManager::changeOutputDevicesMuteState(
4136 const AudioDeviceTypeAddrVector& devices) {
4137 ALOGVV("%s() num devices %zu", __func__, devices.size());
4138
4139 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4140 getSoftwareOutputsForDevices(devices);
4141
4142 for (size_t i = 0; i < outputs.size(); i++) {
4143 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4144 DeviceVector prevDevices = outputDesc->devices();
4145 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4146 }
4147}
4148
4149std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4150 const AudioDeviceTypeAddrVector& devices) const
4151{
4152 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4153 DeviceVector deviceDescriptors;
4154 for (size_t j = 0; j < devices.size(); j++) {
4155 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4156 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4157 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4158 ALOGE("%s: device type %#x address %s not supported or not an output device",
4159 __func__, devices[j].mType, devices[j].getAddress());
4160 continue;
4161 }
4162 deviceDescriptors.add(desc);
4163 }
4164 for (size_t i = 0; i < mOutputs.size(); i++) {
4165 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4166 continue;
4167 }
4168 outputs.push_back(mOutputs.valueAt(i));
4169 }
4170 return outputs;
4171}
4172
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004173status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004174 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004175 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004176 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4177 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004178 }
4179 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004180 if (res != NO_ERROR) {
4181 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4182 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004183 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004184
4185 checkForDeviceAndOutputChanges();
4186 updateCallAndOutputRouting();
4187
4188 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004189}
4190
4191status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4192 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004193 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4194 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004195 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004196 __FUNCTION__, uid);
4197 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004198 }
4199
Eric Laurentc529cf62020-04-17 18:19:10 -07004200 checkForDeviceAndOutputChanges();
4201 updateCallAndOutputRouting();
4202
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004203 return res;
4204}
4205
Eric Laurent2517af32020-11-25 15:31:27 +01004206
jiabin0a488932020-08-07 17:32:40 -07004207status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4208 device_role_t role,
4209 const AudioDeviceTypeAddrVector &devices) {
4210 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4211 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004212
Eric Laurentc529cf62020-04-17 18:19:10 -07004213 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004214 return BAD_VALUE;
4215 }
jiabin0a488932020-08-07 17:32:40 -07004216 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004217 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004218 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4219 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004220 return status;
4221 }
4222
4223 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004224
4225 bool forceVolumeReeval = false;
4226 // FIXME: workaround for truncated touch sounds
4227 // to be removed when the problem is handled by system UI
4228 uint32_t delayMs = 0;
4229 if (strategy == mCommunnicationStrategy) {
4230 forceVolumeReeval = true;
4231 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4232 updateInputRouting();
4233 }
4234 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004235
4236 return NO_ERROR;
4237}
4238
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004239void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4240 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004241{
4242 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004243 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004244 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004245 // Only apply special touch sound delay once
4246 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004247 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004248 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004249 for (size_t i = 0; i < mOutputs.size(); i++) {
4250 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4251 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004252 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4253 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004254 // As done in setDeviceConnectionState, we could also fix default device issue by
4255 // preventing the force re-routing in case of default dev that distinguishes on address.
4256 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004257 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004258 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004259 // If the device is using preferred mixer attributes, the output need to reopen
4260 // with default configuration when the new selected devices are different from
4261 // current routing devices.
4262 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4263 continue;
4264 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304265
4266 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4267 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004268 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004269 // Only apply special touch sound delay once
4270 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004271 }
4272 if (forceVolumeReeval && !newDevices.isEmpty()) {
4273 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4274 }
4275 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004276 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004277 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004278}
4279
Eric Laurent2517af32020-11-25 15:31:27 +01004280void AudioPolicyManager::updateInputRouting() {
4281 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304282 // Skip for hotword recording as the input device switch
4283 // is handled within sound trigger HAL
4284 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4285 continue;
4286 }
Eric Laurent2517af32020-11-25 15:31:27 +01004287 auto newDevice = getNewInputDevice(activeDesc);
4288 // Force new input selection if the new device can not be reached via current input
4289 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4290 setInputDevice(activeDesc->mIoHandle, newDevice);
4291 } else {
4292 closeInput(activeDesc->mIoHandle);
4293 }
4294 }
4295}
4296
Paul Wang5d7cdb52022-11-22 09:45:06 +00004297status_t
4298AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4299 device_role_t role,
4300 const AudioDeviceTypeAddrVector &devices) {
4301 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4302 dumpAudioDeviceTypeAddrVector(devices).c_str());
4303
Eric Laurent78fedbf2023-03-09 14:40:44 +01004304 if (!areAllDevicesSupported(
4305 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004306 return BAD_VALUE;
4307 }
4308 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4309 if (status != NO_ERROR) {
4310 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4311 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4312 return status;
4313 }
4314
4315 checkForDeviceAndOutputChanges();
4316
4317 bool forceVolumeReeval = false;
4318 // TODO(b/263479999): workaround for truncated touch sounds
4319 // to be removed when the problem is handled by system UI
4320 uint32_t delayMs = 0;
4321 if (strategy == mCommunnicationStrategy) {
4322 forceVolumeReeval = true;
4323 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4324 updateInputRouting();
4325 }
4326 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4327
4328 return NO_ERROR;
4329}
4330
4331status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4332 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004333{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004334 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004335
Paul Wang5d7cdb52022-11-22 09:45:06 +00004336 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004337 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004338 ALOGW_IF(status != NAME_NOT_FOUND,
4339 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004340 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004341 return status;
4342 }
4343
4344 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004345
4346 bool forceVolumeReeval = false;
4347 // FIXME: workaround for truncated touch sounds
4348 // to be removed when the problem is handled by system UI
4349 uint32_t delayMs = 0;
4350 if (strategy == mCommunnicationStrategy) {
4351 forceVolumeReeval = true;
4352 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4353 updateInputRouting();
4354 }
4355 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004356
4357 return NO_ERROR;
4358}
4359
jiabin0a488932020-08-07 17:32:40 -07004360status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4361 device_role_t role,
4362 AudioDeviceTypeAddrVector &devices) {
4363 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004364}
4365
Jiabin Huang3b98d322020-09-03 17:54:16 +00004366status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4367 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4368 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4369 dumpAudioDeviceTypeAddrVector(devices).c_str());
4370
Mikhail Naganov55773032020-10-01 15:08:13 -07004371 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004372 return BAD_VALUE;
4373 }
4374 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4375 ALOGW_IF(status != NO_ERROR,
4376 "Engine could not set preferred devices %s for audio source %d role %d",
4377 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4378
4379 return status;
4380}
4381
4382status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4383 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4384 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4385 dumpAudioDeviceTypeAddrVector(devices).c_str());
4386
Mikhail Naganov55773032020-10-01 15:08:13 -07004387 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004388 return BAD_VALUE;
4389 }
4390 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4391 ALOGW_IF(status != NO_ERROR,
4392 "Engine could not add preferred devices %s for audio source %d role %d",
4393 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4394
Eric Laurent2517af32020-11-25 15:31:27 +01004395 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004396 return status;
4397}
4398
4399status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4400 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4401{
4402 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4403 dumpAudioDeviceTypeAddrVector(devices).c_str());
4404
Eric Laurent78fedbf2023-03-09 14:40:44 +01004405 if (!areAllDevicesSupported(
4406 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004407 return BAD_VALUE;
4408 }
4409
4410 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4411 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004412 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004413 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004414 if (status == NO_ERROR) {
4415 updateInputRouting();
4416 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004417 return status;
4418}
4419
4420status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4421 device_role_t role) {
4422 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4423
4424 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004425 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004426 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004427 if (status == NO_ERROR) {
4428 updateInputRouting();
4429 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004430 return status;
4431}
4432
4433status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4434 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4435 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4436}
4437
Oscar Azucena90e77632019-11-27 17:12:28 -08004438status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004439 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004440 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004441 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4442 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004443 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004444 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4445 if (status != NO_ERROR) {
4446 ALOGE("%s() could not set device affinity for userId %d",
4447 __FUNCTION__, userId);
4448 return status;
4449 }
4450
4451 // reevaluate outputs for all devices
4452 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004453 changeOutputDevicesMuteState(devices);
4454 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4455 true /* skipDelays */);
4456 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004457
4458 return NO_ERROR;
4459}
4460
4461status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004462 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004463 AudioDeviceTypeAddrVector devices;
4464 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004465 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4466 if (status != NO_ERROR) {
4467 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4468 __FUNCTION__, userId);
4469 return status;
4470 }
4471
4472 // reevaluate outputs for all devices
4473 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004474 changeOutputDevicesMuteState(devices);
4475 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4476 true /* skipDelays */);
4477 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004478
4479 return NO_ERROR;
4480}
4481
Andy Hungc29d82b2018-10-05 12:23:17 -07004482void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004483{
Andy Hungc29d82b2018-10-05 12:23:17 -07004484 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004485 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004486 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004487 std::string stateLiteral;
4488 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004489 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004490 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4491 "communications", "media", "record", "dock", "system",
4492 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4493 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4494 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004495 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4496 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4497 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4498 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4499 dst->append(" (MANUAL: ");
4500 dumpManualSurroundFormats(dst);
4501 dst->append(")");
4502 }
4503 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004504 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004505 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4506 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004507 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004508 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004509
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004510 dst->append("\n");
4511 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4512 dst->append("\n");
4513 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004514 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004515 mOutputs.dump(dst);
4516 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004517 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004518 mAudioPatches.dump(dst);
4519 mPolicyMixes.dump(dst);
4520 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004521
Kevin Rocardb99cc752019-03-21 20:52:24 -07004522 dst->appendFormat(" AllowedCapturePolicies:\n");
4523 for (auto& policy : mAllowedCapturePolicies) {
4524 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4525 }
4526
jiabina84c3d32022-12-02 18:59:55 +00004527 dst->appendFormat(" Preferred mixer audio configuration:\n");
4528 for (const auto it : mPreferredMixerAttrInfos) {
4529 dst->appendFormat(" - device port id: %d\n", it.first);
4530 for (const auto preferredMixerInfoIt : it.second) {
4531 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4532 preferredMixerInfoIt.second->dump(dst);
4533 }
4534 }
4535
François Gaffiec005e562018-11-06 15:04:49 +01004536 dst->appendFormat("\nPolicy Engine dump:\n");
4537 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004538
4539 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4540 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4541 dst->appendFormat(" - device type: %s, driving stream %d\n",
4542 dumpDeviceTypes({it.first}).c_str(),
4543 mEngine->getVolumeGroupForAttributes(it.second));
4544 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004545}
4546
4547status_t AudioPolicyManager::dump(int fd)
4548{
4549 String8 result;
4550 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004551 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004552 return NO_ERROR;
4553}
4554
Kevin Rocardb99cc752019-03-21 20:52:24 -07004555status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4556{
4557 mAllowedCapturePolicies[uid] = capturePolicy;
4558 return NO_ERROR;
4559}
4560
Eric Laurente552edb2014-03-10 17:42:56 -07004561// This function checks for the parameters which can be offloaded.
4562// This can be enhanced depending on the capability of the DSP and policy
4563// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004564audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004565{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004566 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004567 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004568 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004569 offloadInfo.format,
4570 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4571 offloadInfo.has_video);
4572
jiabin2b9d5a12021-12-10 01:06:29 +00004573 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004574 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004575 }
4576
4577 // See if there is a profile to support this.
4578 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004579 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004580 offloadInfo.sample_rate,
4581 offloadInfo.format,
4582 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004583 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4584 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004585 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4586 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4587 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004588 if (profile == nullptr) {
4589 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4590 }
4591 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4592 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4593 }
4594 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004595}
4596
Michael Chana94fbb22018-04-24 14:31:19 +10004597bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4598 const audio_attributes_t& attributes) {
4599 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004600 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004601 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4602 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004603 config.sample_rate,
4604 config.format,
4605 config.channel_mask,
4606 output_flags,
4607 true /* directOnly */);
4608 ALOGV("%s() profile %sfound with name: %s, "
4609 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4610 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004611 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004612 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004613
4614 // also try the MSD module if compatible profile not found
4615 if (profile == nullptr) {
4616 profile = getMsdProfileForOutput(outputDevices,
4617 config.sample_rate,
4618 config.format,
4619 config.channel_mask,
4620 output_flags,
4621 true /* directOnly */);
4622 ALOGV("%s() MSD profile %sfound with name: %s, "
4623 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4624 __FUNCTION__, profile != 0 ? "" : "NOT ",
4625 (profile != 0 ? profile->getTagName().c_str() : "null"),
4626 config.sample_rate, config.format, config.channel_mask, output_flags);
4627 }
4628 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004629}
4630
jiabin2b9d5a12021-12-10 01:06:29 +00004631bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4632 bool durationIgnored) {
4633 if (mMasterMono) {
4634 return false; // no offloading if mono is set.
4635 }
4636
4637 // Check if offload has been disabled
4638 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4639 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4640 return false;
4641 }
4642
4643 // Check if stream type is music, then only allow offload as of now.
4644 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4645 {
4646 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4647 return false;
4648 }
4649
4650 //TODO: enable audio offloading with video when ready
4651 const bool allowOffloadWithVideo =
4652 property_get_bool("audio.offload.video", false /* default_value */);
4653 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4654 ALOGV("%s: has_video == true, returning false", __func__);
4655 return false;
4656 }
4657
4658 //If duration is less than minimum value defined in property, return false
4659 const int min_duration_secs = property_get_int32(
4660 "audio.offload.min.duration.secs", -1 /* default_value */);
4661 if (!durationIgnored) {
4662 if (min_duration_secs >= 0) {
4663 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4664 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4665 __func__, min_duration_secs);
4666 return false;
4667 }
4668 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4669 ALOGV("%s: Offload denied by duration < default min(=%u)",
4670 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4671 return false;
4672 }
4673 }
4674
4675 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4676 // creating an offloaded track and tearing it down immediately after start when audioflinger
4677 // detects there is an active non offloadable effect.
4678 // FIXME: We should check the audio session here but we do not have it in this context.
4679 // This may prevent offloading in rare situations where effects are left active by apps
4680 // in the background.
4681 if (mEffects.isNonOffloadableEffectEnabled()) {
4682 return false;
4683 }
4684
4685 return true;
4686}
4687
4688audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4689 const audio_config_t *config) {
4690 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4691 offloadInfo.format = config->format;
4692 offloadInfo.sample_rate = config->sample_rate;
4693 offloadInfo.channel_mask = config->channel_mask;
4694 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4695 offloadInfo.has_video = false;
4696 offloadInfo.is_streaming = false;
4697 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4698
4699 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4700 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4701 audio_flags_to_audio_output_flags(attr->flags, &flags);
4702 // only retain flags that will drive compressed offload or passthrough
4703 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4704 if (offloadPossible) {
4705 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4706 }
4707 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4708
Dorin Drimusfae3c642022-03-17 18:36:30 +01004709 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004710 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004711 DeviceVector outputDevices = engineOutputDevices;
4712 // the MSD module checks for different conditions and output devices
4713 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4714 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4715 continue;
4716 }
4717 outputDevices = getMsdAudioOutDevices();
4718 }
jiabin2b9d5a12021-12-10 01:06:29 +00004719 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004720 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004721 config->sample_rate, nullptr /*updatedSamplingRate*/,
4722 config->format, nullptr /*updatedFormat*/,
4723 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004724 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004725 continue;
4726 }
4727 // reject profiles not corresponding to a device currently available
4728 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4729 continue;
4730 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004731 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4732 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004733 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004734 != AUDIO_DIRECT_NOT_SUPPORTED) {
4735 // Already reports offload gapless supported. No need to report offload support.
4736 continue;
4737 }
4738 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4739 != AUDIO_OUTPUT_FLAG_NONE) {
4740 // If offload gapless is reported, no need to report offload support.
4741 directMode = (audio_direct_mode_t) ((directMode &
4742 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4743 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4744 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004745 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004746 }
4747 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004748 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004749 }
4750 }
4751 }
4752 return directMode;
4753}
4754
Dorin Drimusf2196d82022-01-03 12:11:18 +01004755status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4756 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004757 if (mEffects.isNonOffloadableEffectEnabled()) {
4758 return OK;
4759 }
jiabinf1c73972022-04-14 16:28:52 -07004760 DeviceVector devices;
4761 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004762 if (status != OK) {
4763 return status;
4764 }
4765 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4766 if (devices.empty()) {
4767 return OK; // no output devices for the attributes
4768 }
jiabinf1c73972022-04-14 16:28:52 -07004769 return getProfilesForDevices(devices, audioProfilesVector,
4770 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004771}
4772
jiabina84c3d32022-12-02 18:59:55 +00004773status_t AudioPolicyManager::getSupportedMixerAttributes(
4774 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4775 ALOGV("%s, portId=%d", __func__, portId);
4776 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4777 if (deviceDescriptor == nullptr) {
4778 ALOGE("%s the requested device is currently unavailable", __func__);
4779 return BAD_VALUE;
4780 }
jiabin96daffc2023-05-11 17:51:55 +00004781 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4782 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4783 deviceDescriptor->type());
4784 return BAD_VALUE;
4785 }
jiabina84c3d32022-12-02 18:59:55 +00004786 for (const auto& hwModule : mHwModules) {
4787 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4788 if (curProfile->supportsDevice(deviceDescriptor)) {
4789 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4790 }
4791 }
4792 }
4793 return NO_ERROR;
4794}
4795
4796status_t AudioPolicyManager::setPreferredMixerAttributes(
4797 const audio_attributes_t *attr,
4798 audio_port_handle_t portId,
4799 uid_t uid,
4800 const audio_mixer_attributes_t *mixerAttributes) {
4801 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4802 "mixerBehavior=%d}, uid=%d, portId=%u",
4803 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4804 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4805 mixerAttributes->mixer_behavior, uid, portId);
4806 if (attr->usage != AUDIO_USAGE_MEDIA) {
4807 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4808 return BAD_VALUE;
4809 }
4810 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4811 if (deviceDescriptor == nullptr) {
4812 ALOGE("%s the requested device is currently unavailable", __func__);
4813 return BAD_VALUE;
4814 }
4815 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4816 ALOGE("%s(%d), type=%d, is not a usb output device",
4817 __func__, portId, deviceDescriptor->type());
4818 return BAD_VALUE;
4819 }
4820
4821 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4822 audio_flags_to_audio_output_flags(attr->flags, &flags);
4823 flags = (audio_output_flags_t) (flags |
4824 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4825 sp<IOProfile> profile = nullptr;
4826 DeviceVector devices(deviceDescriptor);
4827 for (const auto& hwModule : mHwModules) {
4828 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4829 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004830 && curProfile->getCompatibilityScore(
4831 devices,
4832 mixerAttributes->config.sample_rate,
4833 nullptr /*updatedSamplingRate*/,
4834 mixerAttributes->config.format,
4835 nullptr /*updatedFormat*/,
4836 mixerAttributes->config.channel_mask,
4837 nullptr /*updatedChannelMask*/,
4838 flags,
4839 false /*exactMatchRequiredForInputFlags*/)
4840 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004841 profile = curProfile;
4842 break;
4843 }
4844 }
4845 }
4846 if (profile == nullptr) {
4847 ALOGE("%s, there is no compatible profile found", __func__);
4848 return BAD_VALUE;
4849 }
4850
4851 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4852 sp<PreferredMixerAttributesInfo>::make(
4853 uid, portId, profile, flags, *mixerAttributes);
4854 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4855 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4856
4857 // If 1) there is any client from the preferred mixer configuration owner that is currently
4858 // active and matches the strategy and 2) current output is on the preferred device and the
4859 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4860 // configuration.
4861 std::vector<audio_io_handle_t> outputsToReopen;
4862 for (size_t i = 0; i < mOutputs.size(); i++) {
4863 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004864 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4865 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004866 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004867 } else {
4868 for (const auto &client: output->getActiveClients()) {
4869 if (client->uid() == uid && client->strategy() == strategy) {
4870 client->setIsInvalid();
4871 outputsToReopen.push_back(output->mIoHandle);
4872 }
jiabina84c3d32022-12-02 18:59:55 +00004873 }
4874 }
4875 }
4876 }
4877 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4878 config.sample_rate = mixerAttributes->config.sample_rate;
4879 config.channel_mask = mixerAttributes->config.channel_mask;
4880 config.format = mixerAttributes->config.format;
4881 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004882 sp<SwAudioOutputDescriptor> desc =
4883 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4884 if (desc == nullptr) {
4885 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4886 continue;
4887 }
jiabin220eea12024-05-17 17:55:20 +00004888 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004889 }
4890
4891 return NO_ERROR;
4892}
4893
4894sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004895 audio_port_handle_t devicePortId,
4896 product_strategy_t strategy,
4897 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004898 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4899 if (it == mPreferredMixerAttrInfos.end()) {
4900 return nullptr;
4901 }
jiabind9a58d32023-06-01 17:57:30 +00004902 if (activeBitPerfectPreferred) {
4903 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004904 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004905 return info;
4906 }
4907 }
jiabina84c3d32022-12-02 18:59:55 +00004908 }
jiabind9a58d32023-06-01 17:57:30 +00004909 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4910 return strategyMatchedMixerAttrInfoIt == it->second.end()
4911 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004912}
4913
4914status_t AudioPolicyManager::getPreferredMixerAttributes(
4915 const audio_attributes_t *attr,
4916 audio_port_handle_t portId,
4917 audio_mixer_attributes_t* mixerAttributes) {
4918 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4919 portId, mEngine->getProductStrategyForAttributes(*attr));
4920 if (info == nullptr) {
4921 return NAME_NOT_FOUND;
4922 }
4923 *mixerAttributes = info->getMixerAttributes();
4924 return NO_ERROR;
4925}
4926
4927status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4928 audio_port_handle_t portId,
4929 uid_t uid) {
4930 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4931 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4932 if (preferredMixerAttrInfo == nullptr) {
4933 return NAME_NOT_FOUND;
4934 }
4935 if (preferredMixerAttrInfo->getUid() != uid) {
4936 ALOGE("%s, requested uid=%d, owned uid=%d",
4937 __func__, uid, preferredMixerAttrInfo->getUid());
4938 return PERMISSION_DENIED;
4939 }
4940 mPreferredMixerAttrInfos[portId].erase(strategy);
4941 if (mPreferredMixerAttrInfos[portId].empty()) {
4942 mPreferredMixerAttrInfos.erase(portId);
4943 }
4944
4945 // Reconfig existing output
4946 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4947 for (size_t i = 0; i < mOutputs.size(); i++) {
4948 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4949 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4950 }
4951 }
4952 for (const auto output : potentialOutputsToReopen) {
4953 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4954 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4955 preferredMixerAttrInfo->getFlags())) {
4956 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4957 }
4958 }
4959 return NO_ERROR;
4960}
4961
Eric Laurent6a94d692014-05-20 11:18:06 -07004962status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4963 audio_port_type_t type,
4964 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004965 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004966 unsigned int *generation)
4967{
jiabin19cdba52020-11-24 11:28:58 -08004968 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4969 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004970 return BAD_VALUE;
4971 }
4972 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004973 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 *num_ports = 0;
4975 }
4976
4977 size_t portsWritten = 0;
4978 size_t portsMax = *num_ports;
4979 *num_ports = 0;
4980 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004981 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4982 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004983 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004984 for (const auto& dev : mAvailableOutputDevices) {
4985 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004986 continue;
4987 }
4988 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004989 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004990 }
4991 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004993 }
4994 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004995 for (const auto& dev : mAvailableInputDevices) {
4996 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004997 continue;
4998 }
4999 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005000 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005001 }
5002 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005003 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 }
5005 }
5006 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5007 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5008 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5009 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5010 }
5011 *num_ports += mInputs.size();
5012 }
5013 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005014 size_t numOutputs = 0;
5015 for (size_t i = 0; i < mOutputs.size(); i++) {
5016 if (!mOutputs[i]->isDuplicated()) {
5017 numOutputs++;
5018 if (portsWritten < portsMax) {
5019 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5020 }
5021 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005022 }
Eric Laurent84c70242014-06-23 08:46:27 -07005023 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 }
5025 }
jiabina84c3d32022-12-02 18:59:55 +00005026
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005028 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005029 return NO_ERROR;
5030}
5031
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005032status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5033 std::vector<media::AudioPortFw>* _aidl_return) {
5034 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5035 audio_port_v7 port;
5036 dev->toAudioPort(&port);
5037 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5038 _aidl_return->push_back(std::move(aidlPort));
5039 return OK;
5040 };
5041
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005042 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005043 for (const auto& dev : module->getDeclaredDevices()) {
5044 if (role == media::AudioPortRole::NONE ||
5045 ((role == media::AudioPortRole::SOURCE)
5046 == audio_is_input_device(dev->type()))) {
5047 RETURN_STATUS_IF_ERROR(pushPort(dev));
5048 }
5049 }
5050 }
5051 return OK;
5052}
5053
jiabin19cdba52020-11-24 11:28:58 -08005054status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005055{
Eric Laurent99fcae42018-05-17 16:59:18 -07005056 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5057 return BAD_VALUE;
5058 }
5059 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5060 if (dev != 0) {
5061 dev->toAudioPort(port);
5062 return NO_ERROR;
5063 }
5064 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5065 if (dev != 0) {
5066 dev->toAudioPort(port);
5067 return NO_ERROR;
5068 }
5069 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5070 if (out != 0) {
5071 out->toAudioPort(port);
5072 return NO_ERROR;
5073 }
5074 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5075 if (in != 0) {
5076 in->toAudioPort(port);
5077 return NO_ERROR;
5078 }
5079 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005080}
5081
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005082status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5083 audio_patch_handle_t *handle,
5084 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005085{
François Gaffieafd4cea2019-11-18 15:50:22 +01005086 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005087 if (handle == NULL || patch == NULL) {
5088 return BAD_VALUE;
5089 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005090 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005091 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005092 return BAD_VALUE;
5093 }
5094 // only one source per audio patch supported for now
5095 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005096 return INVALID_OPERATION;
5097 }
Eric Laurent874c42872014-08-08 15:13:39 -07005098 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005099 return INVALID_OPERATION;
5100 }
Eric Laurent874c42872014-08-08 15:13:39 -07005101 for (size_t i = 0; i < patch->num_sinks; i++) {
5102 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5103 return INVALID_OPERATION;
5104 }
5105 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005106
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005107 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5108 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5109 if (srcDevice == nullptr || sinkDevice == nullptr) {
5110 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5111 return BAD_VALUE;
5112 }
5113 ALOGV("%s between source %s and sink %s", __func__,
5114 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5115 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5116 // Default attributes, default volume priority, not to infer with non raw audio patches.
5117 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5118 const struct audio_port_config *source = &patch->sources[0];
5119 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005120 new SourceClientDescriptor(
5121 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5122 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005123 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005124 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005125
5126 status_t status =
5127 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5128
5129 if (status != NO_ERROR) {
5130 return INVALID_OPERATION;
5131 }
5132 mAudioSources.add(portId, sourceDesc);
5133 return NO_ERROR;
5134}
5135
5136status_t AudioPolicyManager::connectAudioSourceToSink(
5137 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5138 const struct audio_patch *patch,
5139 audio_patch_handle_t &handle,
5140 uid_t uid, uint32_t delayMs)
5141{
5142 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5143 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5144 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5145 return INVALID_OPERATION;
5146 }
5147 sourceDesc->connect(handle, sinkDevice);
5148 if (isMsdPatch(handle)) {
5149 return NO_ERROR;
5150 }
5151 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5152 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5153 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5154 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5155 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5156 goto FailurePatchAdded;
5157 }
5158 status = swOutput->start();
5159 if (status != NO_ERROR) {
5160 goto FailureSourceAdded;
5161 }
5162 swOutput->addClient(sourceDesc);
5163 status = startSource(swOutput, sourceDesc, &delayMs);
5164 if (status != NO_ERROR) {
5165 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5166 goto FailureSourceActive;
5167 }
5168 if (delayMs != 0) {
5169 usleep(delayMs * 1000);
5170 }
5171 return NO_ERROR;
5172
5173FailureSourceActive:
5174 swOutput->stop();
5175 releaseOutput(sourceDesc->portId());
5176FailureSourceAdded:
5177 sourceDesc->setSwOutput(nullptr);
5178FailurePatchAdded:
5179 releaseAudioPatchInternal(handle);
5180 return INVALID_OPERATION;
5181}
5182
5183status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5184 audio_patch_handle_t *handle,
5185 uid_t uid, uint32_t delayMs,
5186 const sp<SourceClientDescriptor>& sourceDesc)
5187{
5188 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 sp<AudioPatch> patchDesc;
5190 ssize_t index = mAudioPatches.indexOfKey(*handle);
5191
François Gaffieafd4cea2019-11-18 15:50:22 +01005192 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5193 patch->sources[0].role,
5194 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005195#if LOG_NDEBUG == 0
5196 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005197 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5198 patch->sinks[i].role,
5199 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005200 }
5201#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005202
5203 if (index >= 0) {
5204 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005205 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5206 __func__, mUidCached, patchDesc->getUid(), uid);
5207 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005208 return INVALID_OPERATION;
5209 }
5210 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005211 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005212 }
5213
5214 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005215 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005216 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005217 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005218 return BAD_VALUE;
5219 }
Eric Laurent84c70242014-06-23 08:46:27 -07005220 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5221 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005222 if (patchDesc != 0) {
5223 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005224 ALOGV("%s source id differs for patch current id %d new id %d",
5225 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 return BAD_VALUE;
5227 }
5228 }
Eric Laurent874c42872014-08-08 15:13:39 -07005229 DeviceVector devices;
5230 for (size_t i = 0; i < patch->num_sinks; i++) {
5231 // Only support mix to devices connection
5232 // TODO add support for mix to mix connection
5233 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005234 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005235 return INVALID_OPERATION;
5236 }
5237 sp<DeviceDescriptor> devDesc =
5238 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5239 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005240 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005241 return BAD_VALUE;
5242 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005243
jiabin66acc432024-02-06 00:57:36 +00005244 if (outputDesc->mProfile->getCompatibilityScore(
5245 DeviceVector(devDesc),
5246 patch->sources[0].sample_rate,
5247 nullptr, // updatedSamplingRate
5248 patch->sources[0].format,
5249 nullptr, // updatedFormat
5250 patch->sources[0].channel_mask,
5251 nullptr, // updatedChannelMask
5252 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005253 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005254 return INVALID_OPERATION;
5255 }
5256 devices.add(devDesc);
5257 }
5258 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 return INVALID_OPERATION;
5260 }
Eric Laurent874c42872014-08-08 15:13:39 -07005261
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005263 ALOGV("%s setting device %s on output %d",
5264 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305265 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005266 index = mAudioPatches.indexOfKey(*handle);
5267 if (index >= 0) {
5268 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005269 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 }
5271 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005272 patchDesc->setUid(uid);
5273 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005274 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005275 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005276 return INVALID_OPERATION;
5277 }
5278 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5279 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5280 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005281 // only one sink supported when connecting an input device to a mix
5282 if (patch->num_sinks > 1) {
5283 return INVALID_OPERATION;
5284 }
François Gaffie53615e22015-03-19 09:24:12 +01005285 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 if (inputDesc == NULL) {
5287 return BAD_VALUE;
5288 }
5289 if (patchDesc != 0) {
5290 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5291 return BAD_VALUE;
5292 }
5293 }
François Gaffie11d30102018-11-02 16:09:09 +01005294 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005295 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005296 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 return BAD_VALUE;
5298 }
5299
jiabin66acc432024-02-06 00:57:36 +00005300 if (inputDesc->mProfile->getCompatibilityScore(
5301 DeviceVector(device),
5302 patch->sinks[0].sample_rate,
5303 nullptr, /*updatedSampleRate*/
5304 patch->sinks[0].format,
5305 nullptr, /*updatedFormat*/
5306 patch->sinks[0].channel_mask,
5307 nullptr, /*updatedChannelMask*/
5308 // FIXME for the parameter type,
5309 // and the NONE
5310 (audio_output_flags_t)
5311 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005312 return INVALID_OPERATION;
5313 }
5314 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005315 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005316 device->toString().c_str(), inputDesc->mIoHandle);
5317 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 index = mAudioPatches.indexOfKey(*handle);
5319 if (index >= 0) {
5320 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005321 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 }
5323 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005324 patchDesc->setUid(uid);
5325 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005326 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005327 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005328 return INVALID_OPERATION;
5329 }
5330 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5331 // device to device connection
5332 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005333 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005334 return BAD_VALUE;
5335 }
5336 }
François Gaffie11d30102018-11-02 16:09:09 +01005337 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005338 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005339 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005340 return BAD_VALUE;
5341 }
Eric Laurent874c42872014-08-08 15:13:39 -07005342
Eric Laurent6a94d692014-05-20 11:18:06 -07005343 //update source and sink with our own data as the data passed in the patch may
5344 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005345 PatchBuilder patchBuilder;
5346 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005347
5348 // if first sink is to MSD, establish single MSD patch
5349 if (getMsdAudioOutDevices().contains(
5350 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5351 ALOGV("%s patching to MSD", __FUNCTION__);
5352 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5353 goto installPatch;
5354 }
5355
François Gaffieafd4cea2019-11-18 15:50:22 +01005356 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5357 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005358
Eric Laurent874c42872014-08-08 15:13:39 -07005359 for (size_t i = 0; i < patch->num_sinks; i++) {
5360 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005361 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005362 return INVALID_OPERATION;
5363 }
François Gaffie11d30102018-11-02 16:09:09 +01005364 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005365 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005366 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005367 return BAD_VALUE;
5368 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005369 audio_port_config sinkPortConfig = {};
5370 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5371 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005372
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005373 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5374 // volume management purpose (tracking activity)
5375 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5376 // in config XML to reach the sink so that is can be declared as available.
5377 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005378 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005379 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005380 // take care of dynamic routing for SwOutput selection,
5381 audio_attributes_t attributes = sourceDesc->attributes();
5382 audio_stream_type_t stream = sourceDesc->stream();
5383 audio_attributes_t resultAttr;
5384 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5385 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005386 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5387 config.channel_mask =
5388 (audio_channel_mask_get_representation(sourceMask)
5389 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5390 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005391 config.format = sourceDesc->config().format;
5392 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5393 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5394 bool isRequestedDeviceForExclusiveUse = false;
5395 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005396 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005397 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005398 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5399 &stream, sourceDesc->uid(), &config, &flags,
5400 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005401 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005402 if (output == AUDIO_IO_HANDLE_NONE) {
5403 ALOGV("%s no output for device %s",
5404 __FUNCTION__, sinkDevice->toString().c_str());
5405 return INVALID_OPERATION;
5406 }
5407 outputDesc = mOutputs.valueFor(output);
5408 if (outputDesc->isDuplicated()) {
5409 ALOGE("%s output is duplicated", __func__);
5410 return INVALID_OPERATION;
5411 }
François Gaffie7e39df22022-04-26 12:48:49 +02005412 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5413 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005414 } else {
5415 // Same for "raw patches" aka created from createAudioPatch API
5416 SortedVector<audio_io_handle_t> outputs =
5417 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5418 // if the sink device is reachable via an opened output stream, request to
5419 // go via this output stream by adding a second source to the patch
5420 // description
5421 output = selectOutput(outputs);
5422 if (output == AUDIO_IO_HANDLE_NONE) {
5423 ALOGE("%s no output available for internal patch sink", __func__);
5424 return INVALID_OPERATION;
5425 }
5426 outputDesc = mOutputs.valueFor(output);
5427 if (outputDesc->isDuplicated()) {
5428 ALOGV("%s output for device %s is duplicated",
5429 __func__, sinkDevice->toString().c_str());
5430 return INVALID_OPERATION;
5431 }
François Gaffie7e39df22022-04-26 12:48:49 +02005432 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005433 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005434 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005435 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005436 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005437 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005438 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5439 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005440 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5441 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005442 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005443 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005444 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005445 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005446 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005447 return INVALID_OPERATION;
5448 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005449 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005450 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005451 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005452 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005453 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005454 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005455 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005456 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5457 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005458 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005459 }
Eric Laurent83b88082014-06-20 18:31:16 -07005460 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005461 }
5462 // TODO: check from routing capabilities in config file and other conflicting patches
5463
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005464installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005465 status_t status = installPatch(
5466 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005467 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005468 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005469 return INVALID_OPERATION;
5470 }
5471 } else {
5472 return BAD_VALUE;
5473 }
5474 } else {
5475 return BAD_VALUE;
5476 }
5477 return NO_ERROR;
5478}
5479
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005480status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005481{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005482 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005483 ssize_t index = mAudioPatches.indexOfKey(handle);
5484
5485 if (index < 0) {
5486 return BAD_VALUE;
5487 }
5488 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005489 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5490 __func__, mUidCached, patchDesc->getUid(), uid);
5491 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005492 return INVALID_OPERATION;
5493 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005494 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5495 for (size_t i = 0; i < mAudioSources.size(); i++) {
5496 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5497 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5498 portId = sourceDesc->portId();
5499 break;
5500 }
5501 }
5502 return portId != AUDIO_PORT_HANDLE_NONE ?
5503 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005504}
Eric Laurent6a94d692014-05-20 11:18:06 -07005505
François Gaffieafd4cea2019-11-18 15:50:22 +01005506status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005507 uint32_t delayMs,
5508 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005509{
5510 ALOGV("%s patch %d", __func__, handle);
5511 if (mAudioPatches.indexOfKey(handle) < 0) {
5512 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5513 return BAD_VALUE;
5514 }
5515 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005516 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005517 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005518 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005519 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005520 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005521 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005522 return BAD_VALUE;
5523 }
5524
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305525 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005526 getNewOutputDevices(outputDesc, true /*fromCache*/),
5527 true,
5528 0,
5529 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005530 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5531 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005532 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005533 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005534 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005535 return BAD_VALUE;
5536 }
5537 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005538 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005539 true,
5540 NULL);
5541 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005542 status_t status =
5543 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5544 ALOGV("%s patch panel returned %d patchHandle %d",
5545 __func__, status, patchDesc->getAfHandle());
5546 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005547 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005548 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005549 // SW or HW Bridge
5550 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5551 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005552 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005553 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5554 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5555 outputDesc = sourceDesc->swOutput().promote();
5556 }
5557 if (outputDesc == nullptr) {
5558 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5559 // releaseOutput has already called closeOutput in case of direct output
5560 return NO_ERROR;
5561 }
François Gaffie7e39df22022-04-26 12:48:49 +02005562 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005563 // While using a HwBridge, force reconsidering device only if not reusing an existing
5564 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005565 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005566 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5567 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5568 // Reconsider device only for cases:
5569 // 1 / Active Output
5570 // 2 / Inactive Output previously hosting HwBridge
5571 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5572 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5573 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305574 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005575 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5576 outputDesc->devices(),
5577 force,
5578 0,
5579 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005580 } else {
5581 return BAD_VALUE;
5582 }
5583 } else {
5584 return BAD_VALUE;
5585 }
5586 return NO_ERROR;
5587}
5588
5589status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5590 struct audio_patch *patches,
5591 unsigned int *generation)
5592{
François Gaffie53615e22015-03-19 09:24:12 +01005593 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005594 return BAD_VALUE;
5595 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005596 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005597 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005598}
5599
Eric Laurente1715a42014-05-20 11:30:42 -07005600status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005601{
Eric Laurente1715a42014-05-20 11:30:42 -07005602 ALOGV("setAudioPortConfig()");
5603
5604 if (config == NULL) {
5605 return BAD_VALUE;
5606 }
5607 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5608 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005609 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5610 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005611 }
5612
Eric Laurenta121f902014-06-03 13:32:54 -07005613 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005614 if (config->type == AUDIO_PORT_TYPE_MIX) {
5615 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005616 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005617 if (outputDesc == NULL) {
5618 return BAD_VALUE;
5619 }
Eric Laurent84c70242014-06-23 08:46:27 -07005620 ALOG_ASSERT(!outputDesc->isDuplicated(),
5621 "setAudioPortConfig() called on duplicated output %d",
5622 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005623 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005624 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005625 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005626 if (inputDesc == NULL) {
5627 return BAD_VALUE;
5628 }
Eric Laurenta121f902014-06-03 13:32:54 -07005629 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005630 } else {
5631 return BAD_VALUE;
5632 }
5633 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5634 sp<DeviceDescriptor> deviceDesc;
5635 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5636 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5637 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5638 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5639 } else {
5640 return BAD_VALUE;
5641 }
5642 if (deviceDesc == NULL) {
5643 return BAD_VALUE;
5644 }
Eric Laurenta121f902014-06-03 13:32:54 -07005645 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005646 } else {
5647 return BAD_VALUE;
5648 }
5649
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005650 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005651 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5652 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005653 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005654 audioPortConfig->toAudioPortConfig(&newConfig, config);
5655 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005656 }
Eric Laurenta121f902014-06-03 13:32:54 -07005657 if (status != NO_ERROR) {
5658 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005659 }
Eric Laurente1715a42014-05-20 11:30:42 -07005660
5661 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005662}
5663
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005664void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5665{
Eric Laurentd60560a2015-04-10 11:31:20 -07005666 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005667 clearAudioPatches(uid);
5668 clearSessionRoutes(uid);
5669}
5670
Eric Laurent6a94d692014-05-20 11:18:06 -07005671void AudioPolicyManager::clearAudioPatches(uid_t uid)
5672{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005673 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005674 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005675 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005676 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005677 }
5678 }
5679}
5680
François Gaffiec005e562018-11-06 15:04:49 +01005681void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005682{
François Gaffiec005e562018-11-06 15:04:49 +01005683 // Take the first attributes following the product strategy as it is used to retrieve the routed
5684 // device. All attributes wihin a strategy follows the same "routing strategy"
5685 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5686 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005687 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005688 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005689 for (size_t j = 0; j < mOutputs.size(); j++) {
5690 if (mOutputs.keyAt(j) == ouptutToSkip) {
5691 continue;
5692 }
5693 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005694 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005695 continue;
5696 }
5697 // If the default device for this strategy is on another output mix,
5698 // invalidate all tracks in this strategy to force re connection.
5699 // Otherwise select new device on the output mix.
5700 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005701 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005702 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005703 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005704 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005705 // If the device is using preferred mixer attributes, the output need to reopen
5706 // with default configuration when the new selected devices are different from
5707 // current routing devices.
5708 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5709 continue;
5710 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305711 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005712 }
5713 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005714 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005715}
5716
5717void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5718{
5719 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005720 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005721 for (size_t i = 0; i < mOutputs.size(); i++) {
5722 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005723 for (const auto& client : outputDesc->getClientIterable()) {
5724 if (client->hasPreferredDevice() && client->uid() == uid) {
5725 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005726 auto clientStrategy = client->strategy();
5727 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5728 end(affectedStrategies)) {
5729 continue;
5730 }
5731 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005732 }
5733 }
5734 }
5735 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005736 for (const auto& strategy : affectedStrategies) {
5737 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005738 }
5739
5740 // remove input routes associated with this uid
5741 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005742 for (size_t i = 0; i < mInputs.size(); i++) {
5743 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005744 for (const auto& client : inputDesc->getClientIterable()) {
5745 if (client->hasPreferredDevice() && client->uid() == uid) {
5746 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5747 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005748 }
5749 }
5750 }
5751 // reroute inputs if necessary
5752 SortedVector<audio_io_handle_t> inputsToClose;
5753 for (size_t i = 0; i < mInputs.size(); i++) {
5754 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005755 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005756 inputsToClose.add(inputDesc->mIoHandle);
5757 }
5758 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005759 for (const auto& input : inputsToClose) {
5760 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005761 }
5762}
5763
Eric Laurentd60560a2015-04-10 11:31:20 -07005764void AudioPolicyManager::clearAudioSources(uid_t uid)
5765{
5766 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005767 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5768 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005769 stopAudioSource(mAudioSources.keyAt(i));
5770 }
5771 }
5772}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005773
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005774status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5775 audio_io_handle_t *ioHandle,
5776 audio_devices_t *device)
5777{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005778 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5779 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005780 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005781 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5782 if (deviceDesc == nullptr) {
5783 return INVALID_OPERATION;
5784 }
5785 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005786
François Gaffiedf372692015-03-19 10:43:27 +01005787 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005788}
5789
Eric Laurentd60560a2015-04-10 11:31:20 -07005790status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005791 const audio_attributes_t *attributes,
5792 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005793 uid_t uid) {
5794 return startAudioSourceInternal(source, attributes, portId, uid,
David Li48b6a832024-07-01 13:14:10 +00005795 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurent963dbcc2024-06-20 12:34:15 +00005796}
5797
5798status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5799 const audio_attributes_t *attributes,
5800 audio_port_handle_t *portId,
David Li48b6a832024-07-01 13:14:10 +00005801 uid_t uid, bool internal, bool isCallRx,
5802 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005803{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005804 ALOGV("%s", __FUNCTION__);
5805 *portId = AUDIO_PORT_HANDLE_NONE;
5806
5807 if (source == NULL || attributes == NULL || portId == NULL) {
5808 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5809 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005810 return BAD_VALUE;
5811 }
5812
Eric Laurentd60560a2015-04-10 11:31:20 -07005813 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5814 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005815 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5816 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005817 return INVALID_OPERATION;
5818 }
5819
François Gaffie11d30102018-11-02 16:09:09 +01005820 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005821 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005822 String8(source->ext.device.address),
5823 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005824 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005825 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005826 return BAD_VALUE;
5827 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005828
jiabin4ef93452019-09-10 14:29:54 -07005829 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005830
François Gaffieaaac0fd2018-11-22 17:56:39 +01005831 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005832 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005833 mEngine->getStreamTypeForAttributes(*attributes),
5834 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005835 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005836
David Li48b6a832024-07-01 13:14:10 +00005837 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005838 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005839 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005840 }
5841 return status;
5842}
5843
David Li48b6a832024-07-01 13:14:10 +00005844status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5845 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005846{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005847 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005848
5849 // make sure we only have one patch per source.
5850 disconnectAudioSource(sourceDesc);
5851
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005852 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005853 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5854 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5855 sourceDesc->srcDevice()->type(),
5856 String8(sourceDesc->srcDevice()->address().c_str()),
5857 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005858 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005859 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005860 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005861 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005862 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5863 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5864 return INVALID_OPERATION;
5865 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005866 PatchBuilder patchBuilder;
5867 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5868 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005869
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005870 return connectAudioSourceToSink(
David Li48b6a832024-07-01 13:14:10 +00005871 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005872}
5873
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005874status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005875{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005876 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5877 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005878 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005879 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005880 return BAD_VALUE;
5881 }
5882 status_t status = disconnectAudioSource(sourceDesc);
5883
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005884 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005885 return status;
5886}
5887
Andy Hung2ddee192015-12-18 17:34:44 -08005888status_t AudioPolicyManager::setMasterMono(bool mono)
5889{
5890 if (mMasterMono == mono) {
5891 return NO_ERROR;
5892 }
5893 mMasterMono = mono;
5894 // if enabling mono we close all offloaded devices, which will invalidate the
5895 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5896 // for recreating the new AudioTrack as non-offloaded PCM.
5897 //
5898 // If disabling mono, we leave all tracks as is: we don't know which clients
5899 // and tracks are able to be recreated as offloaded. The next "song" should
5900 // play back offloaded.
5901 if (mMasterMono) {
5902 Vector<audio_io_handle_t> offloaded;
5903 for (size_t i = 0; i < mOutputs.size(); ++i) {
5904 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5905 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5906 offloaded.push(desc->mIoHandle);
5907 }
5908 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005909 for (const auto& handle : offloaded) {
5910 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005911 }
5912 }
5913 // update master mono for all remaining outputs
5914 for (size_t i = 0; i < mOutputs.size(); ++i) {
5915 updateMono(mOutputs.keyAt(i));
5916 }
5917 return NO_ERROR;
5918}
5919
5920status_t AudioPolicyManager::getMasterMono(bool *mono)
5921{
5922 *mono = mMasterMono;
5923 return NO_ERROR;
5924}
5925
Eric Laurentac9cef52017-06-09 15:46:26 -07005926float AudioPolicyManager::getStreamVolumeDB(
5927 audio_stream_type_t stream, int index, audio_devices_t device)
5928{
jiabin9a3361e2019-10-01 09:38:30 -07005929 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005930}
5931
jiabin81772902018-04-02 17:52:27 -07005932status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5933 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005934 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005935{
Kriti Dang6537def2021-03-02 13:46:59 +01005936 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5937 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005938 return BAD_VALUE;
5939 }
Kriti Dang6537def2021-03-02 13:46:59 +01005940 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5941 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005942
5943 size_t formatsWritten = 0;
5944 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005945
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005946 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005947 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5948 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005949 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005950 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005951 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005952 bool formatEnabled = true;
5953 switch (forceUse) {
5954 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005955 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005956 break;
5957 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5958 formatEnabled = false;
5959 break;
5960 default: // AUTO or ALWAYS => true
5961 break;
jiabin81772902018-04-02 17:52:27 -07005962 }
5963 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5964 }
jiabin81772902018-04-02 17:52:27 -07005965 }
5966 return NO_ERROR;
5967}
5968
Kriti Dang6537def2021-03-02 13:46:59 +01005969status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5970 audio_format_t *surroundFormats) {
5971 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5972 return BAD_VALUE;
5973 }
5974 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5975 __func__, *numSurroundFormats, surroundFormats);
5976
5977 size_t formatsWritten = 0;
5978 size_t formatsMax = *numSurroundFormats;
5979 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5980
5981 // Return formats from all device profiles that have already been resolved by
5982 // checkOutputsForDevice().
5983 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5984 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5985 audio_devices_t deviceType = device->type();
5986 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5987 // returns formats reported by HDMI devices.
5988 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5989 continue;
5990 }
5991 // Formats reported by sink devices
5992 std::unordered_set<audio_format_t> formatset;
5993 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5994 formatset.insert(it->second.begin(), it->second.end());
5995 }
5996
5997 // Formats hard-coded in the in policy configuration file (if any).
5998 FormatVector encodedFormats = device->encodedFormats();
5999 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6000 // Filter the formats which are supported by the vendor hardware.
6001 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006002 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006003 formats.insert(*it);
6004 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006005 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006006 if (pair.second.count(*it) != 0) {
6007 formats.insert(pair.first);
6008 break;
6009 }
6010 }
6011 }
6012 }
6013 }
6014 *numSurroundFormats = formats.size();
6015 for (const auto& format: formats) {
6016 if (formatsWritten < formatsMax) {
6017 surroundFormats[formatsWritten++] = format;
6018 }
6019 }
6020 return NO_ERROR;
6021}
6022
jiabin81772902018-04-02 17:52:27 -07006023status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6024{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006025 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006026 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6027 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006028 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006029 return BAD_VALUE;
6030 }
6031
Mikhail Naganov100f0122018-11-29 11:22:16 -08006032 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6033 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006034 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006035 return INVALID_OPERATION;
6036 }
6037
Mikhail Naganov100f0122018-11-29 11:22:16 -08006038 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006039 return NO_ERROR;
6040 }
6041
Mikhail Naganov100f0122018-11-29 11:22:16 -08006042 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006043 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006044 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006045 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006046 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006047 }
6048 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006049 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006050 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006051 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006052 }
6053 }
6054
6055 sp<SwAudioOutputDescriptor> outputDesc;
6056 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006057 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6058 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006059 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6060 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006061 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006062 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006063 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6064 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6065 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006066 name.c_str(),
6067 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006068 if (status != NO_ERROR) {
6069 continue;
6070 }
6071 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6072 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6073 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006074 name.c_str(),
6075 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006076 profileUpdated |= (status == NO_ERROR);
6077 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006078 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006079 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006080 AUDIO_DEVICE_IN_HDMI);
6081 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6082 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006083 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006084 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006085 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6086 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6087 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006088 name.c_str(),
6089 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006090 if (status != NO_ERROR) {
6091 continue;
6092 }
6093 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6094 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6095 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006096 name.c_str(),
6097 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006098 profileUpdated |= (status == NO_ERROR);
6099 }
6100
jiabin81772902018-04-02 17:52:27 -07006101 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006102 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006103 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006104 }
6105
6106 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6107}
6108
Eric Laurent5ada82e2019-08-29 17:53:54 -07006109void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006110{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006111 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006112 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006113 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006114 }
6115}
6116
jiabin6012f912018-11-02 17:06:30 -07006117bool AudioPolicyManager::isHapticPlaybackSupported()
6118{
6119 for (const auto& hwModule : mHwModules) {
6120 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6121 for (const auto &outProfile : outputProfiles) {
6122 struct audio_port audioPort;
6123 outProfile->toAudioPort(&audioPort);
6124 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6125 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6126 return true;
6127 }
6128 }
6129 }
6130 }
6131 return false;
6132}
6133
Carter Hsu325a8eb2022-01-19 19:56:51 +08006134bool AudioPolicyManager::isUltrasoundSupported()
6135{
6136 bool hasUltrasoundOutput = false;
6137 bool hasUltrasoundInput = false;
6138 for (const auto& hwModule : mHwModules) {
6139 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6140 if (!hasUltrasoundOutput) {
6141 for (const auto &outProfile : outputProfiles) {
6142 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6143 hasUltrasoundOutput = true;
6144 break;
6145 }
6146 }
6147 }
6148
6149 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6150 if (!hasUltrasoundInput) {
6151 for (const auto &inputProfile : inputProfiles) {
6152 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6153 hasUltrasoundInput = true;
6154 break;
6155 }
6156 }
6157 }
6158
6159 if (hasUltrasoundOutput && hasUltrasoundInput)
6160 return true;
6161 }
6162 return false;
6163}
6164
Atneya Nair698f5ef2022-12-15 16:15:09 -08006165bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6166{
6167 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6168 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6169 for (const auto& hwModule : mHwModules) {
6170 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6171 for (const auto &inputProfile : inputProfiles) {
6172 if ((inputProfile->getFlags() & mask) == mask) {
6173 return true;
6174 }
6175 }
6176 }
6177 return false;
6178}
6179
Eric Laurent8340e672019-11-06 11:01:08 -08006180bool AudioPolicyManager::isCallScreenModeSupported()
6181{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006182 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006183}
6184
6185
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006186status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006187{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006188 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006189 if (!sourceDesc->isConnected()) {
6190 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6191 return NO_ERROR;
6192 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006193 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6194 if (swOutput != 0) {
6195 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006196 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006197 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006198 }
jiabinbce0c1d2020-10-05 11:20:18 -07006199 if (releaseOutput(sourceDesc->portId())) {
6200 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6201 // no need to release audio patch here but just return NO_ERROR.
6202 return NO_ERROR;
6203 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006204 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006205 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006206 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006207 // close Hwoutput and remove from mHwOutputs
6208 } else {
6209 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6210 }
6211 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006212 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006213 sourceDesc->disconnect();
6214 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006215}
6216
François Gaffiec005e562018-11-06 15:04:49 +01006217sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6218 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006219{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006220 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006221 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006222 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006223 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006224 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6225 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006226 source = sourceDesc;
6227 break;
6228 }
6229 }
6230 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006231}
6232
Eric Laurentb4f42a92022-01-17 17:37:31 +01006233bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006234 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006235 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006236{
6237 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6238 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006239 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006240 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006241 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6242 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6243 return false;
6244 }
6245 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6246 return false;
6247 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006248 }
6249
Eric Laurentd332bc82023-08-04 11:45:23 +02006250 // The caller can have the audio config criteria ignored by either passing a null ptr or
6251 // the AUDIO_CONFIG_INITIALIZER value.
6252 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006253 // some positional channel masks and PCM format and for stereo if low latency performance
6254 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006255
6256 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006257 static const bool stereo_spatialization_enabled =
6258 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006259 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006260 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006261 ? audio_channel_mask_contains_stereo(config->channel_mask)
6262 : audio_is_channel_mask_spatialized(config->channel_mask);
6263 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006264 return false;
6265 }
6266 if (!audio_is_linear_pcm(config->format)) {
6267 return false;
6268 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006269 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6270 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6271 return false;
6272 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006273 }
6274
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006275 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006276 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006277 if (profile == nullptr) {
6278 return false;
6279 }
6280
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006281 return true;
6282}
6283
Shunkai Yao57b93392024-04-26 04:12:21 +00006284// The Spatializer output is compatible with Haptic use cases if:
6285// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6286// with client if client haptic channel bits were set, or
6287// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6288// including the haptic bits or creating the HapticGenerator effect for same session.
6289bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6290 const audio_config_t* config, audio_session_t sessionId) const {
6291 const auto clientHapticChannel =
6292 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6293 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6294 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6295
6296 if (threadOutputHapticChannel) {
6297 // check format and sampleRate match if client haptic channel mask exist
6298 if (clientHapticChannel) {
6299 return mSpatializerOutput->getFormat() == config->format &&
6300 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6301 }
6302 return true;
6303 } else {
6304 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6305 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6306 // HapticGenerator effect for this session) are not supported.
6307 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006308 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006309 }
6310}
6311
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006312void AudioPolicyManager::checkVirtualizerClientRoutes() {
6313 std::set<audio_stream_type_t> streamsToInvalidate;
6314 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006315 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6316 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006317 audio_attributes_t attr = client->attributes();
6318 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6319 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6320 audio_config_base_t clientConfig = client->config();
6321 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006322 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006323 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006324 streamsToInvalidate.insert(client->stream());
6325 }
6326 }
6327 }
6328
jiabinc44b3462022-12-08 12:52:31 -08006329 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006330}
6331
Eric Laurente191d1b2022-04-15 11:59:25 +02006332
6333bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6334 const sp<SwAudioOutputDescriptor>& outputDesc) {
6335 if (outputDesc->isDuplicated()) {
6336 return false;
6337 }
6338 DeviceVector devices = outputDesc->supportedDevices();
6339 for (size_t i = 0; i < mOutputs.size(); i++) {
6340 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6341 if (desc == outputDesc || desc->isDuplicated()) {
6342 continue;
6343 }
6344 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6345 if (!sharedDevices.isEmpty()
6346 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6347 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6348 return false;
6349 }
6350 }
6351 return true;
6352}
6353
6354
Eric Laurentfa0f6742021-08-17 18:39:44 +02006355status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006356 const audio_attributes_t *attr,
6357 audio_io_handle_t *output) {
6358 *output = AUDIO_IO_HANDLE_NONE;
6359
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006360 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6361 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6362 audio_config_t *configPtr = nullptr;
6363 audio_config_t config;
6364 if (mixerConfig != nullptr) {
6365 config = audio_config_initializer(mixerConfig);
6366 configPtr = &config;
6367 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006368 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006369 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006370 return BAD_VALUE;
6371 }
6372
6373 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006374 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006375 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006376 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006377 return BAD_VALUE;
6378 }
6379
Eric Laurente191d1b2022-04-15 11:59:25 +02006380 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006381 for (size_t i = 0; i < mOutputs.size(); i++) {
6382 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006383 if (!desc->isDuplicated()
6384 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6385 spatializerOutputs.push_back(desc);
6386 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006387 }
6388 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006389 mSpatializerOutput.clear();
6390 bool outputsChanged = false;
6391 for (const auto& desc : spatializerOutputs) {
6392 if (desc->mProfile == profile
6393 && (configPtr == nullptr
6394 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6395 mSpatializerOutput = desc;
6396 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6397 } else {
6398 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6399 " and devices %s", __func__, desc->mIoHandle,
6400 configPtr != nullptr ? configPtr->channel_mask : 0,
6401 devices.toString().c_str());
6402 closeOutput(desc->mIoHandle);
6403 outputsChanged = true;
6404 }
Eric Laurent39095982021-08-24 18:29:27 +02006405 }
6406
Eric Laurente191d1b2022-04-15 11:59:25 +02006407 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006408 sp<SwAudioOutputDescriptor> desc =
6409 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006410 if (desc != nullptr) {
6411 mSpatializerOutput = desc;
6412 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006413 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006414 }
6415
6416 checkVirtualizerClientRoutes();
6417
Eric Laurente191d1b2022-04-15 11:59:25 +02006418 if (outputsChanged) {
6419 mPreviousOutputs = mOutputs;
6420 mpClientInterface->onAudioPortListUpdate();
6421 }
6422
6423 if (mSpatializerOutput == nullptr) {
6424 ALOGV("%s could not open spatializer output with requested config", __func__);
6425 return BAD_VALUE;
6426 }
Eric Laurent39095982021-08-24 18:29:27 +02006427 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006428 ALOGV("%s returning new spatializer output %d", __func__, *output);
6429 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006430}
6431
Eric Laurentfa0f6742021-08-17 18:39:44 +02006432status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6433 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006434 return INVALID_OPERATION;
6435 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006436 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006437 return BAD_VALUE;
6438 }
Eric Laurent39095982021-08-24 18:29:27 +02006439
Eric Laurente191d1b2022-04-15 11:59:25 +02006440 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6441 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6442 closeOutput(mSpatializerOutput->mIoHandle);
6443 //from now on mSpatializerOutput is null
6444 checkVirtualizerClientRoutes();
6445 }
Eric Laurent39095982021-08-24 18:29:27 +02006446
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006447 return NO_ERROR;
6448}
6449
Eric Laurente552edb2014-03-10 17:42:56 -07006450// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006451// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006452// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006453uint32_t AudioPolicyManager::nextAudioPortGeneration()
6454{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006455 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006456}
6457
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006458AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006459 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006460 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006461 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006462 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006463 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006464 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006465 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006466 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006467 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006468 mAudioPortGeneration(1),
6469 mBeaconMuteRefCount(0),
6470 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006471 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006472 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006473 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006474 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006475{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006476}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006477
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006478status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006479 if (mEngine == nullptr) {
6480 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006481 }
6482 mEngine->setObserver(this);
6483 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006484 if (status != NO_ERROR) {
6485 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6486 return status;
6487 }
François Gaffie2110e042015-03-24 08:41:51 +01006488
jiabin29230182023-04-04 21:02:36 +00006489 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6490 // at the end of this function.
6491 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006492 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6493 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6494
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006495 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006496 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006497 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006498
Eric Laurent3a4311c2014-03-17 12:00:47 -07006499 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006500 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6501 defaultOutputDevice == nullptr ||
6502 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6503 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6504 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006505 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006506 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006507 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006508
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006509 // Silence ALOGV statements
6510 property_set("log.tag." LOG_TAG, "D");
6511
Eric Laurente552edb2014-03-10 17:42:56 -07006512 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006513 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006514}
6515
Eric Laurente0720872014-03-11 09:30:41 -07006516AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006517{
Eric Laurente552edb2014-03-10 17:42:56 -07006518 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006519 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006520 }
6521 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006522 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006523 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006524 mAvailableOutputDevices.clear();
6525 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006526 mOutputs.clear();
6527 mInputs.clear();
6528 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006529 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006530 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006531}
6532
Eric Laurente0720872014-03-11 09:30:41 -07006533status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006534{
Eric Laurent87ffa392015-05-22 10:32:38 -07006535 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006536}
6537
Eric Laurente552edb2014-03-10 17:42:56 -07006538// ---
6539
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006540void AudioPolicyManager::onNewAudioModulesAvailable()
6541{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006542 DeviceVector newDevices;
6543 onNewAudioModulesAvailableInt(&newDevices);
6544 if (!newDevices.empty()) {
6545 nextAudioPortGeneration();
6546 mpClientInterface->onAudioPortListUpdate();
6547 }
6548}
6549
6550void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6551{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006552 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006553 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6554 continue;
6555 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006556 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006557 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6558 handle != AUDIO_MODULE_HANDLE_NONE) {
6559 hwModule->setHandle(handle);
6560 } else {
6561 ALOGW("could not load HW module %s", hwModule->getName());
6562 continue;
6563 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006564 }
6565 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006566 // open all output streams needed to access attached devices.
6567 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006568 // This also validates mAvailableOutputDevices list
6569 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6570 if (!outProfile->canOpenNewIo()) {
6571 ALOGE("Invalid Output profile max open count %u for profile %s",
6572 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6573 continue;
6574 }
6575 if (!outProfile->hasSupportedDevices()) {
6576 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6577 continue;
6578 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006579 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6580 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006581 mTtsOutputAvailable = true;
6582 }
6583
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006584 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006585 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006586 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006587 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6588 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006589 } else {
6590 // choose first device present in profile's SupportedDevices also part of
6591 // mAvailableOutputDevices.
6592 if (availProfileDevices.isEmpty()) {
6593 continue;
6594 }
6595 supportedDevice = availProfileDevices.itemAt(0);
6596 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006597 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006598 continue;
6599 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306600
6601 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6602 && availProfileDevices.areAllDevicesAttached()) {
6603 ALOGV("%s skip opening output for mmap profile %s", __func__,
6604 outProfile->getTagName().c_str());
6605 continue;
6606 }
6607
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006608 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6609 mpClientInterface);
6610 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006611 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006612 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6613 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006614 AUDIO_STREAM_DEFAULT,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006615 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006616 if (status != NO_ERROR) {
6617 ALOGW("Cannot open output stream for devices %s on hw module %s",
6618 supportedDevice->toString().c_str(), hwModule->getName());
6619 continue;
6620 }
6621 for (const auto &device : availProfileDevices) {
6622 // give a valid ID to an attached device once confirmed it is reachable
6623 if (!device->isAttached()) {
6624 device->attach(hwModule);
6625 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006626 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006627 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006628 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6629 }
6630 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006631 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006632 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6633 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006634 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006635 }
Eric Laurent39095982021-08-24 18:29:27 +02006636 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006637 outputDesc->close();
6638 } else {
6639 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306640 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006641 DeviceVector(supportedDevice),
6642 true,
6643 0,
6644 NULL);
6645 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006646 }
6647 // open input streams needed to access attached devices to validate
6648 // mAvailableInputDevices list
6649 for (const auto& inProfile : hwModule->getInputProfiles()) {
6650 if (!inProfile->canOpenNewIo()) {
6651 ALOGE("Invalid Input profile max open count %u for profile %s",
6652 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6653 continue;
6654 }
6655 if (!inProfile->hasSupportedDevices()) {
6656 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6657 continue;
6658 }
6659 // chose first device present in profile's SupportedDevices also part of
6660 // available input devices
6661 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006662 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006663 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006664 ALOGV("%s: Input device list is empty! for profile %s",
6665 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006666 continue;
6667 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306668
6669 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6670 && availProfileDevices.areAllDevicesAttached()) {
6671 ALOGV("%s skip opening input for mmap profile %s", __func__,
6672 inProfile->getTagName().c_str());
6673 continue;
6674 }
6675
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006676 sp<AudioInputDescriptor> inputDesc =
6677 new AudioInputDescriptor(inProfile, mpClientInterface);
6678
6679 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6680 status_t status = inputDesc->open(nullptr,
6681 availProfileDevices.itemAt(0),
6682 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006683 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006684 &input);
6685 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306686 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6687 __func__, availProfileDevices.toString().c_str(),
6688 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006689 continue;
6690 }
6691 for (const auto &device : availProfileDevices) {
6692 // give a valid ID to an attached device once confirmed it is reachable
6693 if (!device->isAttached()) {
6694 device->attach(hwModule);
6695 device->importAudioPortAndPickAudioProfile(inProfile, true);
6696 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006697 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006698 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6699 }
6700 }
6701 inputDesc->close();
6702 }
6703 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006704
6705 // Check if spatializer outputs can be closed until used.
6706 // mOutputs vector never contains duplicated outputs at this point.
6707 std::vector<audio_io_handle_t> outputsClosed;
6708 for (size_t i = 0; i < mOutputs.size(); i++) {
6709 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6710 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6711 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6712 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006713 nextAudioPortGeneration();
6714 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6715 if (index >= 0) {
6716 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6717 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6718 patchDesc->getAfHandle(), 0);
6719 mAudioPatches.removeItemsAt(index);
6720 mpClientInterface->onAudioPatchListUpdate();
6721 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006722 desc->close();
6723 }
6724 }
6725 for (auto output : outputsClosed) {
6726 removeOutput(output);
6727 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006728}
6729
Eric Laurent98e38192018-02-15 18:31:53 -08006730void AudioPolicyManager::addOutput(audio_io_handle_t output,
6731 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006732{
Eric Laurent1c333e22014-05-20 10:48:17 -07006733 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006734 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006735 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006736 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006737 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006738}
6739
François Gaffie53615e22015-03-19 09:24:12 +01006740void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6741{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006742 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6743 ALOGV("%s: removing primary output", __func__);
6744 mPrimaryOutput = nullptr;
6745 }
François Gaffie53615e22015-03-19 09:24:12 +01006746 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006747 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006748}
6749
Eric Laurent98e38192018-02-15 18:31:53 -08006750void AudioPolicyManager::addInput(audio_io_handle_t input,
6751 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006752{
Eric Laurent1c333e22014-05-20 10:48:17 -07006753 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006754 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006755}
Eric Laurente552edb2014-03-10 17:42:56 -07006756
François Gaffie11d30102018-11-02 16:09:09 +01006757status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006758 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006759 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006760{
François Gaffie11d30102018-11-02 16:09:09 +01006761 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006762 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006763 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006764
François Gaffie11d30102018-11-02 16:09:09 +01006765 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006766 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006767 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006768 }
Eric Laurente552edb2014-03-10 17:42:56 -07006769
Eric Laurent3b73df72014-03-11 09:06:29 -07006770 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006771 // first call getAudioPort to get the supported attributes from the HAL
6772 struct audio_port_v7 port = {};
6773 device->toAudioPort(&port);
6774 status_t status = mpClientInterface->getAudioPort(&port);
6775 if (status == NO_ERROR) {
6776 device->importAudioPort(port);
6777 }
6778
6779 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006780 for (size_t i = 0; i < mOutputs.size(); i++) {
6781 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006782 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006783 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006784 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6785 mOutputs.keyAt(i), device->toString().c_str());
6786 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006787 }
6788 }
6789 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006790 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006791 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006792 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6793 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006794 if (profile->supportsDevice(device)) {
6795 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306796 ALOGV("%s(): adding profile %s from module %s",
6797 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006798 }
6799 }
6800 }
6801
Eric Laurent7b279bb2015-12-14 10:18:23 -08006802 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006803
Eric Laurente552edb2014-03-10 17:42:56 -07006804 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006805 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006806 return BAD_VALUE;
6807 }
6808
6809 // open outputs for matching profiles if needed. Direct outputs are also opened to
6810 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6811 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006812 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006813
6814 // nothing to do if one output is already opened for this profile
6815 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006816 for (j = 0; j < outputs.size(); j++) {
6817 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006818 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006819 // matching profile: save the sample rates, format and channel masks supported
6820 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006821 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006822 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006823 }
Eric Laurente552edb2014-03-10 17:42:56 -07006824 break;
6825 }
6826 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006827 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006828 continue;
6829 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306830 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6831 ALOGV("%s skip opening output for mmap profile %s",
6832 __func__, profile->getTagName().c_str());
6833 continue;
6834 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006835 if (!profile->canOpenNewIo()) {
6836 ALOGW("Max Output number %u already opened for this profile %s",
6837 profile->maxOpenCount, profile->getTagName().c_str());
6838 continue;
6839 }
6840
Eric Laurent83efe1c2017-07-09 16:51:08 -07006841 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006842 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006843 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6844 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006845 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006846 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006847 profiles.removeAt(profile_index);
6848 profile_index--;
6849 } else {
6850 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006851 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006852 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006853 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6854 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006855 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006856 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006857
François Gaffie11d30102018-11-02 16:09:09 +01006858 if (device_distinguishes_on_address(deviceType)) {
6859 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6860 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306861 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6862 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006863 }
Eric Laurente552edb2014-03-10 17:42:56 -07006864 ALOGV("checkOutputsForDevice(): adding output %d", output);
6865 }
6866 }
6867
6868 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006869 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006870 return BAD_VALUE;
6871 }
Eric Laurentd4692962014-05-05 18:13:44 -07006872 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006873 // check if one opened output is not needed any more after disconnecting one device
6874 for (size_t i = 0; i < mOutputs.size(); i++) {
6875 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006876 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006877 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006878 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006879 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006880 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006881 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006882 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6883 mOutputs.keyAt(i));
6884 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006885 }
Eric Laurente552edb2014-03-10 17:42:56 -07006886 }
6887 }
Eric Laurentd4692962014-05-05 18:13:44 -07006888 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006889 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006890 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6891 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006892 if (!profile->supportsDevice(device)) {
6893 continue;
6894 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306895 ALOGV("%s(): clearing direct output profile %s on module %s",
6896 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006897 profile->clearAudioProfiles();
6898 if (!profile->hasDynamicAudioProfile()) {
6899 continue;
6900 }
6901 // When a device is disconnected, if there is an IOProfile that contains dynamic
6902 // profiles and supports the disconnected device, call getAudioPort to repopulate
6903 // the capabilities of the devices that is supported by the IOProfile.
6904 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6905 if (supportedDevice == device ||
6906 !mAvailableOutputDevices.contains(supportedDevice)) {
6907 continue;
6908 }
6909 struct audio_port_v7 port;
6910 supportedDevice->toAudioPort(&port);
6911 status_t status = mpClientInterface->getAudioPort(&port);
6912 if (status == NO_ERROR) {
6913 supportedDevice->importAudioPort(port);
6914 }
Eric Laurente552edb2014-03-10 17:42:56 -07006915 }
6916 }
6917 }
6918 }
6919 return NO_ERROR;
6920}
6921
François Gaffie11d30102018-11-02 16:09:09 +01006922status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006923 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006924{
François Gaffie11d30102018-11-02 16:09:09 +01006925 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006926 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006927 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006928 }
6929
Eric Laurentd4692962014-05-05 18:13:44 -07006930 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006931 sp<AudioInputDescriptor> desc;
6932
jiabinbf5f4262023-04-12 21:48:34 +00006933 // first call getAudioPort to get the supported attributes from the HAL
6934 struct audio_port_v7 port = {};
6935 device->toAudioPort(&port);
6936 status_t status = mpClientInterface->getAudioPort(&port);
6937 if (status == NO_ERROR) {
6938 device->importAudioPort(port);
6939 }
6940
Eric Laurent0dd51852019-04-19 18:18:58 -07006941 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006942 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006943 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006944 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006945 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006946 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006947 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006948
François Gaffie11d30102018-11-02 16:09:09 +01006949 if (profile->supportsDevice(device)) {
6950 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306951 ALOGV("%s : adding profile %s from module %s", __func__,
6952 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006953 }
6954 }
6955 }
6956
Eric Laurent0dd51852019-04-19 18:18:58 -07006957 if (profiles.isEmpty()) {
6958 ALOGW("%s: No input profile available for device %s",
6959 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006960 return BAD_VALUE;
6961 }
6962
6963 // open inputs for matching profiles if needed. Direct inputs are also opened to
6964 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6965 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6966
Eric Laurent1c333e22014-05-20 10:48:17 -07006967 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006968
Eric Laurentd4692962014-05-05 18:13:44 -07006969 // nothing to do if one input is already opened for this profile
6970 size_t input_index;
6971 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6972 desc = mInputs.valueAt(input_index);
6973 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006974 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006975 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006976 }
Eric Laurentd4692962014-05-05 18:13:44 -07006977 break;
6978 }
6979 }
6980 if (input_index != mInputs.size()) {
6981 continue;
6982 }
6983
Jaideep Sharma44824a22024-06-18 16:32:34 +05306984 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6985 ALOGV("%s skip opening input for mmap profile %s",
6986 __func__, profile->getTagName().c_str());
6987 continue;
6988 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006989 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306990 ALOGW("%s Max Input number %u already opened for this profile %s",
6991 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08006992 continue;
6993 }
6994
Eric Laurentfe231122017-11-17 17:48:06 -08006995 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006996 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306997 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00006998 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
6999 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007000
Eric Laurentcf2c0212014-07-25 16:20:43 -07007001 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007002 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007003 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007004 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007005 mpClientInterface->setParameters(input, String8(param));
7006 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007007 }
jiabin12537fc2023-10-12 17:56:08 +00007008 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007009 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307010 ALOGW("%s direct input missing param for profile %s", __func__,
7011 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007012 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007013 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007014 }
7015
Eric Laurent0dd51852019-04-19 18:18:58 -07007016 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007017 addInput(input, desc);
7018 }
7019 } // endif input != 0
7020
Eric Laurentcf2c0212014-07-25 16:20:43 -07007021 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307022 ALOGW("%s could not open input for device %s on profile %s", __func__,
7023 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007024 profiles.removeAt(profile_index);
7025 profile_index--;
7026 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007027 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007028 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007029 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307030 ALOGV("%s: adding input %d for profile %s", __func__,
7031 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007032
7033 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307034 ALOGV("%s: closing input %d for profile %s", __func__,
7035 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007036 closeInput(input);
7037 }
Eric Laurentd4692962014-05-05 18:13:44 -07007038 }
7039 } // end scan profiles
7040
7041 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007042 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007043 return BAD_VALUE;
7044 }
7045 } else {
7046 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007047 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007048 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007049 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007050 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007051 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007052 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007053 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307054 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7055 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007056 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007057 }
7058 }
7059 }
7060 } // end disconnect
7061
7062 return NO_ERROR;
7063}
7064
7065
Eric Laurente0720872014-03-11 09:30:41 -07007066void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007067{
7068 ALOGV("closeOutput(%d)", output);
7069
François Gaffie1c878552018-11-22 16:53:21 +01007070 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7071 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007072 ALOGW("closeOutput() unknown output %d", output);
7073 return;
7074 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007075 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007076 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007077
Eric Laurente552edb2014-03-10 17:42:56 -07007078 // look for duplicated outputs connected to the output being removed.
7079 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007080 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7081 if (dupOutput->isDuplicated() &&
7082 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7083 sp<SwAudioOutputDescriptor> remainingOutput =
7084 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007085 // As all active tracks on duplicated output will be deleted,
7086 // and as they were also referenced on the other output, the reference
7087 // count for their stream type must be adjusted accordingly on
7088 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007089 const bool wasActive = remainingOutput->isActive();
7090 // Note: no-op on the closing output where all clients has already been set inactive
7091 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007092 // stop() will be a no op if the output is still active but is needed in case all
7093 // active streams refcounts where cleared above
7094 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007095 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007096 }
Eric Laurente552edb2014-03-10 17:42:56 -07007097 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7098 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7099
7100 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007101 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007102 }
7103 }
7104
Eric Laurent05b90f82014-08-27 15:32:29 -07007105 nextAudioPortGeneration();
7106
François Gaffie1c878552018-11-22 16:53:21 +01007107 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007108 if (index >= 0) {
7109 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007110 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7111 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007112 mAudioPatches.removeItemsAt(index);
7113 mpClientInterface->onAudioPatchListUpdate();
7114 }
7115
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007116 if (closingOutputWasActive) {
7117 closingOutput->stop();
7118 }
François Gaffie1c878552018-11-22 16:53:21 +01007119 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007120 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007121 for (const auto device : closingOutput->devices()) {
7122 device->setPreferredConfig(nullptr);
7123 }
7124 }
Eric Laurente552edb2014-03-10 17:42:56 -07007125
François Gaffie53615e22015-03-19 09:24:12 +01007126 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007127 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007128 if (closingOutput == mSpatializerOutput) {
7129 mSpatializerOutput.clear();
7130 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007131
7132 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7133 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007134 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007135 bool directOutputOpen = false;
7136 for (size_t i = 0; i < mOutputs.size(); i++) {
7137 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7138 directOutputOpen = true;
7139 break;
7140 }
7141 }
7142 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007143 ALOGV("no direct outputs open, reset MSD patches");
7144 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7145 // how output devices for patching are resolved. Avoid by caching and reusing the
7146 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7147 // devices to patch to. This may be complicated by the fact that devices may become
7148 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007149 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007150 }
7151 }
jiabin220eea12024-05-17 17:55:20 +00007152
7153 if (closingOutput->mPreferredAttrInfo != nullptr) {
7154 closingOutput->mPreferredAttrInfo->resetActiveClient();
7155 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007156}
7157
7158void AudioPolicyManager::closeInput(audio_io_handle_t input)
7159{
7160 ALOGV("closeInput(%d)", input);
7161
7162 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7163 if (inputDesc == NULL) {
7164 ALOGW("closeInput() unknown input %d", input);
7165 return;
7166 }
7167
Eric Laurent6a94d692014-05-20 11:18:06 -07007168 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007169
François Gaffie11d30102018-11-02 16:09:09 +01007170 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007171 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007172 if (index >= 0) {
7173 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007174 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7175 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007176 mAudioPatches.removeItemsAt(index);
7177 mpClientInterface->onAudioPatchListUpdate();
7178 }
7179
François Gaffie6ebbce02023-07-19 13:27:53 +02007180 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007181 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007182 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007183
François Gaffie11d30102018-11-02 16:09:09 +01007184 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7185 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007186 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007187 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007188 }
Eric Laurente552edb2014-03-10 17:42:56 -07007189}
7190
François Gaffie11d30102018-11-02 16:09:09 +01007191SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7192 const DeviceVector &devices,
7193 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007194{
7195 SortedVector<audio_io_handle_t> outputs;
7196
François Gaffie11d30102018-11-02 16:09:09 +01007197 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007198 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007199 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007200 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007201 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007202 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007203 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007204 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007205 outputs.add(openOutputs.keyAt(i));
7206 }
7207 }
7208 return outputs;
7209}
7210
Mikhail Naganov37977152018-07-11 15:54:44 -07007211void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7212{
7213 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7214 // output is suspended before any tracks are moved to it
7215 checkA2dpSuspend();
7216 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007217 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007218 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007219 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007220 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007221 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7222 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7223 // configuration changes will ultimately be rerouted correctly. We can still avoid
7224 // unnecessary rerouting by caching and reusing the arguments to
7225 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7226 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007227 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007228 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007229 // an event that changed routing likely occurred, inform upper layers
7230 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007231}
7232
François Gaffiec005e562018-11-06 15:04:49 +01007233bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7234 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007235{
François Gaffiec005e562018-11-06 15:04:49 +01007236 return mEngine->getProductStrategyForAttributes(lAttr) ==
7237 mEngine->getProductStrategyForAttributes(rAttr);
7238}
7239
Francois Gaffieff1eb522020-05-06 18:37:04 +02007240void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7241{
7242 for (size_t i = 0; i < mAudioSources.size(); i++) {
7243 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7244 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007245 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007246 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007247 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007248 }
7249 }
7250}
7251
7252void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7253{
7254 for (size_t i = 0; i < mAudioSources.size(); i++) {
7255 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7256 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7257 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7258 disconnectAudioSource(sourceDesc);
7259 }
7260 }
7261}
7262
François Gaffiec005e562018-11-06 15:04:49 +01007263void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7264{
7265 auto psId = mEngine->getProductStrategyForAttributes(attr);
7266
7267 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7268 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007269
François Gaffie11d30102018-11-02 16:09:09 +01007270 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7271 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007272
Eric Laurentc209fe42020-06-05 18:11:23 -07007273 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007274 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007275 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007276 // take into account dynamic audio policies related changes: if a client is now associated
7277 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007278 // invalidate clients on outputs that do not support all the newly selected devices for the
7279 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007280 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007281 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007282 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007283 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007284 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007285
Eric Laurentc209fe42020-06-05 18:11:23 -07007286 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7287 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7288 continue;
7289 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007290 if (!desc->supportsAllDevices(newDevices)) {
7291 invalidatedOutputs.push_back(desc);
7292 break;
7293 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007294 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007295 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007296 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7297 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7298 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007299 if (status == OK) {
7300 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7301 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7302 maxLatency = desc->latency();
7303 }
7304 invalidatedOutputs.push_back(desc);
7305 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007306 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007307 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007308 }
7309 }
7310
Eric Laurent56ed8842022-11-15 16:04:41 +01007311 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007312 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7313 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007314 for (audio_io_handle_t srcOut : srcOutputs) {
7315 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007316 if (desc == nullptr) continue;
7317
7318 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007319 maxLatency = desc->latency();
7320 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007321
Eric Laurent56ed8842022-11-15 16:04:41 +01007322 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007323 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007324 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007325 // a client on a non direct outputs has necessarily a linear PCM format
7326 // so we can call selectOutput() safely
7327 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7328 client->flags(),
7329 client->config().format,
7330 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007331 client->config().sample_rate,
7332 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007333 if (newOutput != srcOut) {
7334 invalidate = true;
7335 break;
7336 }
7337 } else {
7338 sp<IOProfile> profile = getProfileForOutput(newDevices,
7339 client->config().sample_rate,
7340 client->config().format,
7341 client->config().channel_mask,
7342 client->flags(),
7343 true /* directOnly */);
7344 if (profile != desc->mProfile) {
7345 invalidate = true;
7346 break;
7347 }
7348 }
7349 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007350 // mute strategy while moving tracks from one output to another
7351 if (invalidate) {
7352 invalidatedOutputs.push_back(desc);
7353 if (desc->isStrategyActive(psId)) {
7354 setStrategyMute(psId, true, desc);
7355 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7356 newDevices.types());
7357 }
Eric Laurente552edb2014-03-10 17:42:56 -07007358 }
François Gaffiec005e562018-11-06 15:04:49 +01007359 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007360 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007361 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007362 }
Eric Laurente552edb2014-03-10 17:42:56 -07007363 }
7364
Eric Laurent56ed8842022-11-15 16:04:41 +01007365 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7366 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7367 std::to_string(srcOutputs[0]).c_str(),
7368 std::to_string(dstOutputs[0]).c_str());
7369
François Gaffiec005e562018-11-06 15:04:49 +01007370 // Move effects associated to this stream from previous output to new output
7371 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007372 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007373 }
François Gaffiec005e562018-11-06 15:04:49 +01007374 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007375 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007376 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007377 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007378 desc->setTracksInvalidatedStatusByStrategy(psId);
7379 }
Eric Laurente552edb2014-03-10 17:42:56 -07007380 }
7381 }
7382}
7383
Eric Laurente0720872014-03-11 09:30:41 -07007384void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007385{
François Gaffiec005e562018-11-06 15:04:49 +01007386 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7387 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7388 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007389 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007390 }
Eric Laurente552edb2014-03-10 17:42:56 -07007391}
7392
Kevin Rocard153f92d2018-12-18 18:33:28 -08007393void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007394 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007395 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007396 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007397 for (size_t i = 0; i < mOutputs.size(); i++) {
7398 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7399 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007400 sp<AudioPolicyMix> primaryMix;
7401 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007402 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007403 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7404 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7405 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007406 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7407 for (auto &secondaryMix : secondaryMixes) {
7408 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7409 if (outputDesc != nullptr &&
7410 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7411 secondaryDescs.push_back(outputDesc);
7412 }
7413 }
7414
jiabinc44b3462022-12-08 12:52:31 -08007415 if (status != OK &&
7416 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7417 // When it failed to query secondary output, only invalidate the client that is not
7418 // MMAP. The reason is that MMAP stream will not support secondary output.
7419 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007420 } else if (!std::equal(
7421 client->getSecondaryOutputs().begin(),
7422 client->getSecondaryOutputs().end(),
7423 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungced57302024-08-14 11:37:57 -07007424 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7425 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007426 // If the format is not PCM, the tracks should be invalidated to get correct
7427 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007428 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007429 } else {
7430 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7431 std::vector<audio_io_handle_t> secondaryOutputIds;
7432 for (const auto &secondaryDesc: secondaryDescs) {
7433 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7434 weakSecondaryDescs.push_back(secondaryDesc);
7435 }
7436 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7437 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007438 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007439 }
7440 }
7441 }
jiabin10a03f12021-05-07 23:46:28 +00007442 if (!trackSecondaryOutputs.empty()) {
7443 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7444 }
jiabinc44b3462022-12-08 12:52:31 -08007445 if (!clientsToInvalidate.empty()) {
7446 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7447 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007448 }
7449}
7450
Eric Laurent2517af32020-11-25 15:31:27 +01007451bool AudioPolicyManager::isScoRequestedForComm() const {
7452 AudioDeviceTypeAddrVector devices;
7453 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7454 for (const auto &device : devices) {
7455 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7456 return true;
7457 }
7458 }
7459 return false;
7460}
7461
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007462bool AudioPolicyManager::isHearingAidUsedForComm() const {
7463 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7464 true /*fromCache*/);
7465 for (const auto &device : devices) {
7466 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7467 return true;
7468 }
7469 }
7470 return false;
7471}
7472
7473
Eric Laurente0720872014-03-11 09:30:41 -07007474void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007475{
François Gaffie53615e22015-03-19 09:24:12 +01007476 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007477 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007478 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007479 return;
7480 }
7481
Eric Laurent3a4311c2014-03-17 12:00:47 -07007482 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007483 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7484 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007485 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007486
7487 // if suspended, restore A2DP output if:
7488 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007489 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007490 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007491 //
Eric Laurentf732e072016-08-03 19:30:28 -07007492 // if not suspended, suspend A2DP output if:
7493 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007494 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007495 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007496 //
7497 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007498 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007499 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007500 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007501 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007502
7503 mpClientInterface->restoreOutput(a2dpOutput);
7504 mA2dpSuspended = false;
7505 }
7506 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007507 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007508 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007509 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007510 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007511
7512 mpClientInterface->suspendOutput(a2dpOutput);
7513 mA2dpSuspended = true;
7514 }
7515 }
7516}
7517
François Gaffie11d30102018-11-02 16:09:09 +01007518DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7519 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007520{
François Gaffiedb1755b2023-09-01 11:50:35 +02007521 if (outputDesc == nullptr) {
7522 return DeviceVector{};
7523 }
François Gaffie11d30102018-11-02 16:09:09 +01007524
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007525 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007526 if (index >= 0) {
7527 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007528 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007529 ALOGV("%s device %s forced by patch %d", __func__,
7530 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7531 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007532 }
7533 }
7534
Dean Wheatley514b4312020-06-17 21:45:00 +10007535 // Do not retrieve engine device for outputs through MSD
7536 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7537 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7538 return outputDesc->devices();
7539 }
7540
Eric Laurent97ac8712018-07-27 18:59:02 -07007541 // Honor explicit routing requests only if no client using default routing is active on this
7542 // input: a specific app can not force routing for other apps by setting a preferred device.
7543 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007544 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007545 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007546 if (device != nullptr) {
7547 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007548 }
7549
François Gaffiea807ef92018-11-05 10:44:33 +01007550 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7551 // of setForceUse / Default Bus device here
7552 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7553 if (device != nullptr) {
7554 return DeviceVector(device);
7555 }
7556
François Gaffiedb1755b2023-09-01 11:50:35 +02007557 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007558 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7559 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307560 auto hasStreamActive = [&](auto stream) {
7561 return hasStream(streams, stream) && isStreamActive(stream, 0);
7562 };
Eric Laurent484e9272018-06-07 17:29:23 -07007563
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307564 auto doGetOutputDevicesForVoice = [&]() {
7565 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007566 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307567 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007568 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7569 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307570 };
7571
7572 // With low-latency playing on speaker, music on WFD, when the first low-latency
7573 // output is stopped, getNewOutputDevices checks for a product strategy
7574 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007575 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307576 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7577 // stream is associated to the output descriptor.
7578 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7579 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7580 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7581 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007582 // Retrieval of devices for voice DL is done on primary output profile, cannot
7583 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007584 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007585 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7586 break;
7587 }
Eric Laurente552edb2014-03-10 17:42:56 -07007588 }
François Gaffiec005e562018-11-06 15:04:49 +01007589 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007590 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007591}
7592
François Gaffie11d30102018-11-02 16:09:09 +01007593sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7594 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007595{
François Gaffie11d30102018-11-02 16:09:09 +01007596 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007597
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007598 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007599 if (index >= 0) {
7600 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007601 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007602 ALOGV("getNewInputDevice() device %s forced by patch %d",
7603 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7604 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007605 }
7606 }
7607
Eric Laurent97ac8712018-07-27 18:59:02 -07007608 // Honor explicit routing requests only if no client using default routing is active on this
7609 // input: a specific app can not force routing for other apps by setting a preferred device.
7610 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007611 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7612 if (device != nullptr) {
7613 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007614 }
7615
Eric Laurentdc95a252018-04-12 12:46:56 -07007616 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007617 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007618 audio_attributes_t attributes;
7619 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007620 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007621 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7622 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007623 attributes = topClient->attributes();
7624 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007625 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007626 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007627 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7628 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007629 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007630 }
7631
Francois Gaffie716e1432019-01-14 16:58:59 +01007632 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7633 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007634 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007635 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007636 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007637 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007638
Eric Laurente552edb2014-03-10 17:42:56 -07007639 return device;
7640}
7641
Eric Laurent794fde22016-03-11 09:50:45 -08007642bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7643 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007644 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007645}
7646
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007647status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007648 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007649 if (devices == nullptr) {
7650 return BAD_VALUE;
7651 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007652
Andy Hung6d23c0f2022-02-16 09:37:15 -08007653 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007654 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7655 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007656 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007657 for (const auto& device : curDevices) {
7658 devices->push_back(device->getDeviceTypeAddr());
7659 }
7660 return NO_ERROR;
7661}
7662
Eric Laurente0720872014-03-11 09:30:41 -07007663void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007664 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007665 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007666 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007667 updateDevicesAndOutputs();
7668 break;
7669 default:
7670 break;
7671 }
7672}
7673
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007674uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007675
7676 // skip beacon mute management if a dedicated TTS output is available
7677 if (mTtsOutputAvailable) {
7678 return 0;
7679 }
7680
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007681 switch(event) {
7682 case STARTING_OUTPUT:
7683 mBeaconMuteRefCount++;
7684 break;
7685 case STOPPING_OUTPUT:
7686 if (mBeaconMuteRefCount > 0) {
7687 mBeaconMuteRefCount--;
7688 }
7689 break;
7690 case STARTING_BEACON:
7691 mBeaconPlayingRefCount++;
7692 break;
7693 case STOPPING_BEACON:
7694 if (mBeaconPlayingRefCount > 0) {
7695 mBeaconPlayingRefCount--;
7696 }
7697 break;
7698 }
7699
7700 if (mBeaconMuteRefCount > 0) {
7701 // any playback causes beacon to be muted
7702 return setBeaconMute(true);
7703 } else {
7704 // no other playback: unmute when beacon starts playing, mute when it stops
7705 return setBeaconMute(mBeaconPlayingRefCount == 0);
7706 }
7707}
7708
7709uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7710 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7711 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7712 // keep track of muted state to avoid repeating mute/unmute operations
7713 if (mBeaconMuted != mute) {
7714 // mute/unmute AUDIO_STREAM_TTS on all outputs
7715 ALOGV("\t muting %d", mute);
7716 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007717 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7718 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7719 ALOGV("\t no tts volume source available");
7720 return 0;
7721 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007722 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007723 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007724 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007725 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007726 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007727 maxLatency = latency;
7728 }
7729 }
7730 mBeaconMuted = mute;
7731 return maxLatency;
7732 }
7733 return 0;
7734}
7735
Eric Laurente0720872014-03-11 09:30:41 -07007736void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007737{
François Gaffiec005e562018-11-06 15:04:49 +01007738 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007739 mPreviousOutputs = mOutputs;
7740}
7741
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007742uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007743 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007744 uint32_t delayMs)
7745{
7746 // mute/unmute strategies using an incompatible device combination
7747 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7748 // if unmuting, unmute only after the specified delay
7749 if (outputDesc->isDuplicated()) {
7750 return 0;
7751 }
7752
7753 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007754 DeviceVector devices = outputDesc->devices();
7755 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007756
François Gaffiec005e562018-11-06 15:04:49 +01007757 auto productStrategies = mEngine->getOrderedProductStrategies();
7758 for (const auto &productStrategy : productStrategies) {
7759 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7760 DeviceVector curDevices =
7761 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7762 curDevices = curDevices.filter(outputDesc->supportedDevices());
7763 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007764 bool doMute = false;
7765
François Gaffiec005e562018-11-06 15:04:49 +01007766 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007767 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007768 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7769 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007770 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007771 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007772 }
Eric Laurent99401132014-05-07 19:48:15 -07007773 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007774 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007775 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007776 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007777 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007778 continue;
7779 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307780 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007781 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7782 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7783 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007784 if (mute) {
7785 // FIXME: should not need to double latency if volume could be applied
7786 // immediately by the audioflinger mixer. We must account for the delay
7787 // between now and the next time the audioflinger thread for this output
7788 // will process a buffer (which corresponds to one buffer size,
7789 // usually 1/2 or 1/4 of the latency).
7790 if (muteWaitMs < desc->latency() * 2) {
7791 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007792 }
7793 }
7794 }
7795 }
7796 }
7797 }
7798
Eric Laurent99401132014-05-07 19:48:15 -07007799 // temporary mute output if device selection changes to avoid volume bursts due to
7800 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007801 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007802 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007803
Eric Laurentdc462862016-07-19 12:29:53 -07007804 if (muteWaitMs < tempMuteWaitMs) {
7805 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007806 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007807
7808 // If recommended duration is defined, replace temporary mute duration to avoid
7809 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7810 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7811 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7812 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7813 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7814
François Gaffieaaac0fd2018-11-22 17:56:39 +01007815 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7816 // make sure that we do not start the temporary mute period too early in case of
7817 // delayed device change
7818 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7819 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007820 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007821 }
7822 }
7823
Eric Laurente552edb2014-03-10 17:42:56 -07007824 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7825 if (muteWaitMs > delayMs) {
7826 muteWaitMs -= delayMs;
7827 usleep(muteWaitMs * 1000);
7828 return muteWaitMs;
7829 }
7830 return 0;
7831}
7832
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307833uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7834 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007835 const DeviceVector &devices,
7836 bool force,
7837 int delayMs,
7838 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007839 bool requiresMuteCheck, bool requiresVolumeCheck,
7840 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007841{
jiabin3ff8d7d2022-12-13 06:27:44 +00007842 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307843 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7844 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7845 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007846 uint32_t muteWaitMs;
7847
7848 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307849 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007850 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307851 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007852 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007853 return muteWaitMs;
7854 }
Eric Laurente552edb2014-03-10 17:42:56 -07007855
7856 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007857 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007858 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007859 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007860
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307861 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7862 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007863
7864 if (!filteredDevices.isEmpty()) {
7865 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007866 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007867
7868 // if the outputs are not materially active, there is no need to mute.
7869 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007870 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007871 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307872 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7873 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007874 muteWaitMs = 0;
7875 }
Eric Laurente552edb2014-03-10 17:42:56 -07007876
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007877 bool outputRouted = outputDesc->isRouted();
7878
Eric Laurent79ea9582020-06-11 18:49:24 -07007879 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7880 // output profile or if new device is not supported AND previous device(s) is(are) still
7881 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007882 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307883 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7884 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007885 // restore previous device after evaluating strategy mute state
7886 outputDesc->setDevices(prevDevices);
7887 return muteWaitMs;
7888 }
7889
Eric Laurente552edb2014-03-10 17:42:56 -07007890 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007891 // the requested device is AUDIO_DEVICE_NONE
7892 // OR the requested device is the same as current device
7893 // AND force is not specified
7894 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007895 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007896 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307897 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7898 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7899 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007900 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307901 ALOGV("%s %s setting same device on routed output, force apply volumes",
7902 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007903 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7904 }
Eric Laurente552edb2014-03-10 17:42:56 -07007905 return muteWaitMs;
7906 }
7907
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307908 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7909 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007910
Eric Laurente552edb2014-03-10 17:42:56 -07007911 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007912 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007913 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007914 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007915 PatchBuilder patchBuilder;
7916 patchBuilder.addSource(outputDesc);
7917 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7918 for (const auto &filteredDevice : filteredDevices) {
7919 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007920 }
7921
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007922 // Add half reported latency to delayMs when muteWaitMs is null in order
7923 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007924 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7925 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7926 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007927 }
Eric Laurente552edb2014-03-10 17:42:56 -07007928
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007929 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7930 if (!skipMuteDelay) {
7931 // update stream volumes according to new device
7932 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7933 }
Eric Laurente552edb2014-03-10 17:42:56 -07007934
7935 return muteWaitMs;
7936}
7937
Eric Laurentc75307b2015-03-17 15:29:32 -07007938status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007939 int delayMs,
7940 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007941{
Eric Laurent6a94d692014-05-20 11:18:06 -07007942 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007943 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7944 return INVALID_OPERATION;
7945 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007946 if (patchHandle) {
7947 index = mAudioPatches.indexOfKey(*patchHandle);
7948 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007949 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007950 }
7951 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007952 return INVALID_OPERATION;
7953 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007954 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007955 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007956 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007957 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007958 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007959 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007960 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007961 return status;
7962}
7963
7964status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007965 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007966 bool force,
7967 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007968{
7969 status_t status = NO_ERROR;
7970
Eric Laurent1f2f2232014-06-02 12:01:23 -07007971 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007972 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7973 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007974
François Gaffie11d30102018-11-02 16:09:09 +01007975 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007976 PatchBuilder patchBuilder;
7977 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007978 // AUDIO_SOURCE_HOTWORD is for internal use only:
7979 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007980 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7981 auto result = usecase;
7982 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7983 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7984 }
7985 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007986 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007987 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007988 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007989 }
7990 }
7991 return status;
7992}
7993
Eric Laurent6a94d692014-05-20 11:18:06 -07007994status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7995 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007996{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007997 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007998 ssize_t index;
7999 if (patchHandle) {
8000 index = mAudioPatches.indexOfKey(*patchHandle);
8001 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008002 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008003 }
8004 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008005 return INVALID_OPERATION;
8006 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008007 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008008 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008009 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008010 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008011 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008012 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008013 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008014 return status;
8015}
8016
François Gaffie11d30102018-11-02 16:09:09 +01008017sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008018 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008019 audio_format_t& format,
8020 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008021 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008022{
8023 // Choose an input profile based on the requested capture parameters: select the first available
8024 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008025 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008026
Atneya Nair0f0a8032022-12-12 16:20:12 -08008027 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8028 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8029 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8030
8031 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008032
jiabin2fd710d2022-05-02 23:20:22 +00008033 for (;;) {
8034 sp<IOProfile> firstInexact = nullptr;
8035 uint32_t updatedSamplingRate = 0;
8036 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8037 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8038 for (const auto& hwModule : mHwModules) {
8039 for (const auto& profile : hwModule->getInputProfiles()) {
8040 // profile->log();
8041 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008042 if (profile->getCompatibilityScore(
8043 DeviceVector(device),
8044 samplingRate,
8045 &updatedSamplingRate,
8046 format,
8047 &updatedFormat,
8048 channelMask,
8049 &updatedChannelMask,
8050 // FIXME ugly cast
8051 (audio_output_flags_t) flags,
8052 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8053 samplingRate = updatedSamplingRate;
8054 format = updatedFormat;
8055 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008056 return profile;
8057 }
jiabin66acc432024-02-06 00:57:36 +00008058 if (firstInexact == nullptr
8059 && profile->getCompatibilityScore(
8060 DeviceVector(device),
8061 samplingRate,
8062 &updatedSamplingRate,
8063 format,
8064 &updatedFormat,
8065 channelMask,
8066 &updatedChannelMask,
8067 // FIXME ugly cast
8068 (audio_output_flags_t) flags,
8069 false /*exactMatchRequiredForInputFlags*/)
8070 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008071 firstInexact = profile;
8072 }
8073 }
8074 }
8075
8076 if (firstInexact != nullptr) {
8077 samplingRate = updatedSamplingRate;
8078 format = updatedFormat;
8079 channelMask = updatedChannelMask;
8080 return firstInexact;
8081 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8082 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8083 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8084 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8085 flags = AUDIO_INPUT_FLAG_NONE;
8086 } else { // fail
8087 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8088 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8089 samplingRate, format, channelMask, oriFlags);
8090 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008091 }
8092 }
jiabin2fd710d2022-05-02 23:20:22 +00008093
8094 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008095}
8096
Vlad Popa87e0e582024-05-20 18:49:20 -07008097float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8098 VolumeSource volumeSource,
8099 int index,
8100 const DeviceTypeSet &deviceTypes)
8101{
8102 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8103 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8104 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8105
8106 if (com_android_media_audio_abs_volume_index_fix()) {
8107 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8108 mAbsoluteVolumeDrivingStreams.end()) {
8109 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8110 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8111 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8112 ALOGD("%s: no group matching with %s", __FUNCTION__,
8113 toString(attributesToDriveAbs).c_str());
8114 return volumeDb;
8115 }
8116
8117 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8118 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8119 if (vsToDriveAbs == volumeSource) {
8120 // attenuation is applied by the abs volume controller
8121 return volumeDbMax;
8122 } else {
8123 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8124 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8125 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8126 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8127 curvesAbs.getVolumeIndexMax());
8128 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8129 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8130 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8131 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8132 return newVolumeDb;
8133 }
8134 }
8135 return volumeDb;
8136 } else {
8137 return volumeDb;
8138 }
8139}
8140
François Gaffieaaac0fd2018-11-22 17:56:39 +01008141float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8142 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008143 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008144 const DeviceTypeSet& deviceTypes,
8145 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008146{
Vlad Popa87e0e582024-05-20 18:49:20 -07008147 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008148 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8149 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8150
8151 if (!computeInternalInteraction) {
8152 return volumeDb;
8153 }
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008154
8155 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8156 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8157 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8158 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008159 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8160 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8161 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8162 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8163 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008164 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008165 mOutputs.isActive(ringVolumeSrc, 0)) {
8166 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008167 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8168 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008169 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008170 }
8171
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008172 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008173 if ((volumeSource != callVolumeSrc && (isInCall() ||
8174 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008175 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008176 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8177 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008178 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8179 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8180 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008181 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008182 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008183 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008184 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008185 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8186 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008187 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008188 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8189 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8190 // programmatically muted.
8191 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8192 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8193 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008194 bool exemptFromCapping =
8195 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8196 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008197 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8198 volumeSource, volumeDb);
8199 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008200 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8201 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8202 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008203 }
8204 }
Eric Laurente552edb2014-03-10 17:42:56 -07008205 // if a headset is connected, apply the following rules to ring tones and notifications
8206 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008207 // - always attenuate notifications volume by 6dB
8208 // - attenuate ring tones volume by 6dB unless music is not playing and
8209 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008210 // - if music is playing, always limit the volume to current music volume,
8211 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008212 if (!Intersection(deviceTypes,
8213 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8214 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008215 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8216 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008217 ((volumeSource == alarmVolumeSrc ||
8218 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008219 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8220 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8221 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008222 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8223 curves.canBeMuted()) {
8224
Eric Laurente552edb2014-03-10 17:42:56 -07008225 // when the phone is ringing we must consider that music could have been paused just before
8226 // by the music application and behave as if music was active if the last music track was
8227 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008228 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8229 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008230 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008231 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008232 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8233 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008234 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008235 float musicVolDb = computeVolume(musicCurves,
8236 musicVolumeSrc,
8237 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008238 musicDevice,
8239 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008240 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8241 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8242 if (volumeDb > minVolDb) {
8243 volumeDb = minVolDb;
8244 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008245 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008246 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8247 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008248 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8249 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8250 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8251 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008252 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008253 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008254 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8255 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008256 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8257 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008258 }
8259 }
jiabin9a3361e2019-10-01 09:38:30 -07008260 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008261 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008262 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008263 }
8264 }
8265
François Gaffie43c73442018-11-08 08:21:55 +01008266 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008267}
8268
Eric Laurent3839bc02018-07-10 18:33:34 -07008269int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008270 VolumeSource fromVolumeSource,
8271 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008272{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008273 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008274 return srcIndex;
8275 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008276 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8277 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008278 float minSrc = (float)srcCurves.getVolumeIndexMin();
8279 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8280 float minDst = (float)dstCurves.getVolumeIndexMin();
8281 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008282
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008283 // preserve mute request or correct range
8284 if (srcIndex < minSrc) {
8285 if (srcIndex == 0) {
8286 return 0;
8287 }
8288 srcIndex = minSrc;
8289 } else if (srcIndex > maxSrc) {
8290 srcIndex = maxSrc;
8291 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008292 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8293}
8294
François Gaffieaaac0fd2018-11-22 17:56:39 +01008295status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8296 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008297 int index,
8298 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008299 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008300 int delayMs,
8301 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008302{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008303 // APM is single threaded, and single instance.
8304 static std::set<IVolumeCurves*> invalidCurvesReported;
8305
François Gaffieaaac0fd2018-11-22 17:56:39 +01008306 // do not change actual attributes volume if the attributes is muted
8307 if (outputDesc->isMuted(volumeSource)) {
8308 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8309 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008310 return NO_ERROR;
8311 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008312
Eric Laurent5baf07c2024-01-11 16:57:27 +00008313 bool isVoiceVolSrc;
8314 bool isBtScoVolSrc;
8315 if (!isVolumeConsistentForCalls(
8316 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008317 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008318 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008319 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008320 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008321
jiabin9a3361e2019-10-01 09:38:30 -07008322 if (deviceTypes.empty()) {
8323 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008324 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008325 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008326 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008327 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008328
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008329 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008330 if (!invalidCurvesReported.count(&curves)) {
8331 invalidCurvesReported.insert(&curves);
8332 String8 dump;
8333 curves.dump(&dump);
8334 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8335 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008336 return BAD_VALUE;
8337 }
8338
jiabin9a3361e2019-10-01 09:38:30 -07008339 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8340 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008341 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008342 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008343 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8344 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008345 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008346 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008347 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008348 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8349 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008350
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008351 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008352 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8353 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8354 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008355 }
Eric Laurente552edb2014-03-10 17:42:56 -07008356 return NO_ERROR;
8357}
8358
Eric Laurent5baf07c2024-01-11 16:57:27 +00008359void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008360 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008361 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008362 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008363 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008364 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008365 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8366 } else {
8367 voiceVolume = index == 0 ? 0.0 : 1.0;
8368 }
8369 if (voiceVolume != mLastVoiceVolume) {
8370 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8371 mLastVoiceVolume = voiceVolume;
8372 }
8373}
8374
8375bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8376 const DeviceTypeSet& deviceTypes,
8377 bool& isVoiceVolSrc,
8378 bool& isBtScoVolSrc,
8379 const char* caller) {
8380 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8381 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8382 const bool isScoRequested = isScoRequestedForComm();
8383 const bool isHAUsed = isHearingAidUsedForComm();
8384
8385 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8386 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8387
8388 if ((callVolSrc != btScoVolSrc) &&
8389 ((isVoiceVolSrc && isScoRequested) ||
8390 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8391 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8392 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8393 volumeSource, isScoRequested ? " " : " not ");
8394 return false;
8395 }
8396 return true;
8397}
8398
Eric Laurentc75307b2015-03-17 15:29:32 -07008399void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008400 const DeviceTypeSet& deviceTypes,
8401 int delayMs,
8402 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008403{
jiabincd510522020-01-22 09:40:55 -08008404 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008405 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8406 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8407 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008408 curves.getVolumeIndex(deviceTypes),
8409 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008410 }
8411}
8412
François Gaffiec005e562018-11-06 15:04:49 +01008413void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8414 bool on,
8415 const sp<AudioOutputDescriptor>& outputDesc,
8416 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008417 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008418{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008419 std::vector<VolumeSource> sourcesToMute;
8420 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8421 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8422 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008423 VolumeSource source = toVolumeSource(attributes, false);
8424 if ((source != VOLUME_SOURCE_NONE) &&
8425 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8426 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008427 sourcesToMute.push_back(source);
8428 }
Eric Laurente552edb2014-03-10 17:42:56 -07008429 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008430 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008431 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008432 }
8433
Eric Laurente552edb2014-03-10 17:42:56 -07008434}
8435
François Gaffieaaac0fd2018-11-22 17:56:39 +01008436void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8437 bool on,
8438 const sp<AudioOutputDescriptor>& outputDesc,
8439 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008440 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008441{
jiabin9a3361e2019-10-01 09:38:30 -07008442 if (deviceTypes.empty()) {
8443 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008444 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008445 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008446 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008447 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008448 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008449 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008450 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8451 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008452 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008453 }
8454 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008455 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8456 // ignored
8457 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008458 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008459 if (!outputDesc->isMuted(volumeSource)) {
8460 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008461 return;
8462 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008463 if (outputDesc->decMuteCount(volumeSource) == 0) {
8464 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008465 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008466 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008467 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008468 delayMs);
8469 }
8470 }
8471}
8472
François Gaffie53615e22015-03-19 09:24:12 +01008473bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8474{
François Gaffiec005e562018-11-06 15:04:49 +01008475 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008476 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8477 return true;
8478 }
8479
8480 // has known usage?
8481 switch (paa->usage) {
8482 case AUDIO_USAGE_UNKNOWN:
8483 case AUDIO_USAGE_MEDIA:
8484 case AUDIO_USAGE_VOICE_COMMUNICATION:
8485 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8486 case AUDIO_USAGE_ALARM:
8487 case AUDIO_USAGE_NOTIFICATION:
8488 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8489 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8490 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8491 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8492 case AUDIO_USAGE_NOTIFICATION_EVENT:
8493 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8494 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8495 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8496 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008497 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008498 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008499 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008500 case AUDIO_USAGE_EMERGENCY:
8501 case AUDIO_USAGE_SAFETY:
8502 case AUDIO_USAGE_VEHICLE_STATUS:
8503 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008504 break;
8505 default:
8506 return false;
8507 }
8508 return true;
8509}
8510
François Gaffie2110e042015-03-24 08:41:51 +01008511audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8512{
8513 return mEngine->getForceUse(usage);
8514}
8515
Eric Laurent96d1dda2022-03-14 17:14:19 +01008516bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008517 return isStateInCall(mEngine->getPhoneState());
8518}
8519
Eric Laurent96d1dda2022-03-14 17:14:19 +01008520bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008521 return is_state_in_call(state);
8522}
8523
Eric Laurentf9cccec2022-11-16 19:12:00 +01008524bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008525 audio_mode_t mode = mEngine->getPhoneState();
8526 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008527 || (mode == AUDIO_MODE_CALL_SCREEN)
8528 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008529}
8530
Eric Laurentf9cccec2022-11-16 19:12:00 +01008531bool AudioPolicyManager::isInCallOrScreening() const {
8532 audio_mode_t mode = mEngine->getPhoneState();
8533 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8534}
8535
Eric Laurentd60560a2015-04-10 11:31:20 -07008536void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8537{
8538 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008539 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008540 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008541 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008542 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008543 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008544 }
8545 }
8546
8547 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8548 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8549 bool release = false;
8550 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8551 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8552 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8553 source->ext.device.type == deviceDesc->type()) {
8554 release = true;
8555 }
8556 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008557 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008558 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8559 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8560 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008561 sink->ext.device.type == deviceDesc->type() &&
8562 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8563 || strncmp(sink->ext.device.address, address,
8564 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008565 release = true;
8566 }
8567 }
8568 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008569 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8570 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008571 }
8572 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008573
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008574 mInputs.clearSessionRoutesForDevice(deviceDesc);
8575
Francois Gaffie716e1432019-01-14 16:58:59 +01008576 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008577}
8578
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008579void AudioPolicyManager::modifySurroundFormats(
8580 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008581 std::unordered_set<audio_format_t> enforcedSurround(
8582 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008583 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008584 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008585 allSurround.insert(pair.first);
8586 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8587 }
Phil Burk09bc4612016-02-24 15:58:15 -08008588
8589 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8590 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008591 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008592 // This is the resulting set of formats depending on the surround mode:
8593 // 'all surround' = allSurround
8594 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8595 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8596 // 'manual surround' = mManualSurroundFormats
8597 // AUTO: formats v 'enforced surround'
8598 // ALWAYS: formats v 'all surround' v 'enforced surround'
8599 // NEVER: formats ^ 'non-surround'
8600 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008601
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008602 std::unordered_set<audio_format_t> formatSet;
8603 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8604 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008605 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008606 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008607 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008608 formatSet.insert(*formatIter);
8609 }
8610 }
8611 } else {
8612 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8613 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008614 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008615
jiabin81772902018-04-02 17:52:27 -07008616 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008617 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008618 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8619 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8620 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008621 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008622 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8623 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8624 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008625 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008626 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008627 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008628 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008629 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008630 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008631}
8632
jiabin06e4bab2019-07-29 10:13:34 -07008633void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8634 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008635 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8636 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8637
8638 // If NEVER, then remove support for channelMasks > stereo.
8639 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008640 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8641 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008642 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008643 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008644 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008645 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008646 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008647 }
8648 }
jiabin81772902018-04-02 17:52:27 -07008649 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8650 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8651 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008652 bool supports5dot1 = false;
8653 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008654 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008655 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8656 supports5dot1 = true;
8657 break;
8658 }
8659 }
8660 // If not then add 5.1 support.
8661 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008662 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008663 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008664 }
Phil Burk09bc4612016-02-24 15:58:15 -08008665 }
8666}
8667
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008668void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008669 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008670 const sp<IOProfile>& profile) {
8671 if (!profile->hasDynamicAudioProfile()) {
8672 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008673 }
François Gaffie112b0af2015-11-19 16:13:25 +01008674
jiabin12537fc2023-10-12 17:56:08 +00008675 audio_port_v7 devicePort;
8676 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008677
jiabin12537fc2023-10-12 17:56:08 +00008678 audio_port_v7 mixPort;
8679 profile->toAudioPort(&mixPort);
8680 mixPort.ext.mix.handle = ioHandle;
8681
8682 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8683 if (status != NO_ERROR) {
8684 ALOGE("%s failed to query the attributes of the mix port", __func__);
8685 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008686 }
jiabin12537fc2023-10-12 17:56:08 +00008687
8688 std::set<audio_format_t> supportedFormats;
8689 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8690 supportedFormats.insert(mixPort.audio_profiles[i].format);
8691 }
8692 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8693 mReportedFormatsMap[devDesc] = formats;
8694
8695 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8696 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8697 modifySurroundFormats(devDesc, &formats);
8698 size_t modifiedNumProfiles = 0;
8699 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8700 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8701 formats.end()) {
8702 // Skip the format that is not present after modifying surround formats.
8703 continue;
8704 }
8705 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8706 sizeof(struct audio_profile));
8707 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8708 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8709 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8710 modifySurroundChannelMasks(&channels);
8711 std::copy(channels.begin(), channels.end(),
8712 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8713 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8714 }
8715 mixPort.num_audio_profiles = modifiedNumProfiles;
8716 }
8717 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008718}
Eric Laurentd60560a2015-04-10 11:31:20 -07008719
Mikhail Naganovdc769682018-05-04 15:34:08 -07008720status_t AudioPolicyManager::installPatch(const char *caller,
8721 audio_patch_handle_t *patchHandle,
8722 AudioIODescriptorInterface *ioDescriptor,
8723 const struct audio_patch *patch,
8724 int delayMs)
8725{
8726 ssize_t index = mAudioPatches.indexOfKey(
8727 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8728 *patchHandle : ioDescriptor->getPatchHandle());
8729 sp<AudioPatch> patchDesc;
8730 status_t status = installPatch(
8731 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8732 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008733 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008734 }
8735 return status;
8736}
8737
8738status_t AudioPolicyManager::installPatch(const char *caller,
8739 ssize_t index,
8740 audio_patch_handle_t *patchHandle,
8741 const struct audio_patch *patch,
8742 int delayMs,
8743 uid_t uid,
8744 sp<AudioPatch> *patchDescPtr)
8745{
8746 sp<AudioPatch> patchDesc;
8747 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8748 if (index >= 0) {
8749 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008750 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008751 }
8752
8753 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8754 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8755 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8756 if (status == NO_ERROR) {
8757 if (index < 0) {
8758 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008759 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008760 } else {
8761 patchDesc->mPatch = *patch;
8762 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008763 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008764 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008765 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008766 }
8767 nextAudioPortGeneration();
8768 mpClientInterface->onAudioPatchListUpdate();
8769 }
8770 if (patchDescPtr) *patchDescPtr = patchDesc;
8771 return status;
8772}
8773
jiabinbce0c1d2020-10-05 11:20:18 -07008774bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8775{
8776 const TrackClientVector activeClients = output->getActiveClients();
8777 if (activeClients.empty()) {
8778 return true;
8779 }
8780 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8781 if (index < 0) {
8782 ALOGE("%s, no audio patch found while there are active clients on output %d",
8783 __func__, output->getId());
8784 return false;
8785 }
8786 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8787 DeviceVector routedDevices;
8788 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8789 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8790 patchDesc->mPatch.sinks[i].id);
8791 if (device == nullptr) {
8792 ALOGE("%s, no audio device found with id(%d)",
8793 __func__, patchDesc->mPatch.sinks[i].id);
8794 return false;
8795 }
8796 routedDevices.add(device);
8797 }
8798 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008799 if (client->isInvalid()) {
8800 // No need to take care about invalidated clients.
8801 continue;
8802 }
jiabinbce0c1d2020-10-05 11:20:18 -07008803 sp<DeviceDescriptor> preferredDevice =
8804 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8805 if (mEngine->getOutputDevicesForAttributes(
8806 client->attributes(), preferredDevice, false) == routedDevices) {
8807 return false;
8808 }
8809 }
8810 return true;
8811}
8812
8813sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008814 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008815 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8816 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008817{
8818 for (const auto& device : devices) {
8819 // TODO: This should be checking if the profile supports the device combo.
8820 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008821 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8822 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008823 return nullptr;
8824 }
8825 }
8826 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8827 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008828 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008829 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008830 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008831 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008832 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008833 return nullptr;
8834 }
jiabin14b50cc2023-12-13 19:01:52 +00008835 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8836 auto portConfig = desc->getConfig();
8837 for (const auto& device : devices) {
8838 device->setPreferredConfig(&portConfig);
8839 }
8840 }
jiabinbce0c1d2020-10-05 11:20:18 -07008841
8842 // Here is where the out_set_parameters() for card & device gets called
8843 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8844 const audio_devices_t deviceType = device->type();
8845 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008846 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008847 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8848 mpClientInterface->setParameters(output, String8(param));
8849 free(param);
8850 }
jiabin12537fc2023-10-12 17:56:08 +00008851 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008852 if (!profile->hasValidAudioProfile()) {
8853 ALOGW("%s() missing param", __func__);
8854 desc->close();
8855 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008856 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8857 // Reopen the output with the best audio profile picked by APM when the profile supports
8858 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008859 desc->close();
8860 output = AUDIO_IO_HANDLE_NONE;
8861 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8862 profile->pickAudioProfile(
8863 config.sample_rate, config.channel_mask, config.format);
8864 config.offload_info.sample_rate = config.sample_rate;
8865 config.offload_info.channel_mask = config.channel_mask;
8866 config.offload_info.format = config.format;
8867
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008868 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
8869 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008870 if (status != NO_ERROR) {
8871 return nullptr;
8872 }
8873 }
8874
8875 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008876 setOutputDevices(__func__, desc,
8877 devices,
8878 true,
8879 0,
8880 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008881 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8882 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8883
jiabinbce0c1d2020-10-05 11:20:18 -07008884 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8885 sp<AudioPolicyMix> policyMix;
8886 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8887 policyMix->setOutput(desc);
8888 desc->mPolicyMix = policyMix;
8889 } else {
8890 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008891 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008892 }
8893
baek.kim -61c20122022-07-27 10:05:32 +00008894 } else if (hasPrimaryOutput() && speaker != nullptr
8895 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008896 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8897 // no duplicated output for:
8898 // - direct outputs
8899 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008900 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008901 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8902
8903 //TODO: configure audio effect output stage here
8904
8905 // open a duplicating output thread for the new output and the primary output
8906 sp<SwAudioOutputDescriptor> dupOutputDesc =
8907 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8908 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8909 if (status == NO_ERROR) {
8910 // add duplicated output descriptor
8911 addOutput(duplicatedOutput, dupOutputDesc);
8912 } else {
8913 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8914 mPrimaryOutput->mIoHandle, output);
8915 desc->close();
8916 removeOutput(output);
8917 nextAudioPortGeneration();
8918 return nullptr;
8919 }
8920 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008921 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8922 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8923 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008924 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008925 }
jiabinbce0c1d2020-10-05 11:20:18 -07008926 return desc;
8927}
8928
jiabinf1c73972022-04-14 16:28:52 -07008929status_t AudioPolicyManager::getDevicesForAttributes(
8930 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8931 // Devices are determined in the following precedence:
8932 //
8933 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8934 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8935 //
8936 // If no such dynamic policy then
8937 // 2) Devices containing an active client using setPreferredDevice
8938 // with same strategy as the attributes.
8939 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8940 //
8941 // If no corresponding active client with setPreferredDevice then
8942 // 3) Devices associated with the strategy determined by the attributes
8943 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8944 //
8945 // See related getOutputForAttrInt().
8946
8947 // check dynamic policies but only for primary descriptors (secondary not used for audible
8948 // audio routing, only used for duplication for playback capture)
8949 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008950 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008951 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008952 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8953 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8954 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008955 if (status != OK) {
8956 return status;
8957 }
8958
8959 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8960 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8961 // as they are unaffected by device/stream volume
8962 // (per SwAudioOutputDescriptor::isFixedVolume()).
8963 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8964 ) {
8965 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8966 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8967 devices.add(deviceDesc);
8968 } else {
8969 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8970 // which selects setPreferredDevice if active. This means forVolume call
8971 // will take an active setPreferredDevice, if such exists.
8972
8973 devices = mEngine->getOutputDevicesForAttributes(
8974 attr, nullptr /* preferredDevice */, false /* fromCache */);
8975 }
8976
8977 if (forVolume) {
8978 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8979 // for single volume control in AudioService (such relationship should exist if
8980 // SPEAKER_SAFE is present).
8981 //
8982 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8983 DeviceVector speakerSafeDevices =
8984 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8985 if (!speakerSafeDevices.isEmpty()) {
8986 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8987 devices.remove(speakerSafeDevices);
8988 }
8989 }
8990
8991 return NO_ERROR;
8992}
8993
8994status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8995 AudioProfileVector& audioProfiles,
8996 uint32_t flags,
8997 bool isInput) {
8998 for (const auto& hwModule : mHwModules) {
8999 // the MSD module checks for different conditions
9000 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9001 continue;
9002 }
9003 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9004 : hwModule->getOutputProfiles();
9005 for (const auto& profile : ioProfiles) {
9006 if (!profile->areAllDevicesSupported(devices) ||
9007 !profile->isCompatibleProfileForFlags(
9008 flags, false /*exactMatchRequiredForInputFlags*/)) {
9009 continue;
9010 }
9011 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9012 }
9013 }
9014
9015 if (!isInput) {
9016 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9017 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9018 if (msdModule != nullptr) {
9019 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9020 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9021 for (const auto &profile: msdModule->getOutputProfiles()) {
9022 if (!profile->asAudioPort()->isDirectOutput()) {
9023 continue;
9024 }
9025 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9026 }
9027 } else {
9028 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9029 }
9030 }
9031 }
9032
9033 return NO_ERROR;
9034}
9035
jiabin3ff8d7d2022-12-13 06:27:44 +00009036sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9037 const audio_config_t *config,
9038 audio_output_flags_t flags,
9039 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009040 closeOutput(outputDesc->mIoHandle);
9041 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9042 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9043 if (preferredOutput == nullptr) {
9044 ALOGE("%s failed to reopen output device=%d, caller=%s",
9045 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009046 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009047 return preferredOutput;
9048}
9049
9050void AudioPolicyManager::reopenOutputsWithDevices(
9051 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9052 for (const auto& [output, devices] : outputsToReopen) {
9053 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9054 closeOutput(output);
9055 openOutputWithProfileAndDevice(desc->mProfile, devices);
9056 }
jiabina84c3d32022-12-02 18:59:55 +00009057}
9058
jiabinc44b3462022-12-08 12:52:31 -08009059PortHandleVector AudioPolicyManager::getClientsForStream(
9060 audio_stream_type_t streamType) const {
9061 PortHandleVector clients;
9062 for (size_t i = 0; i < mOutputs.size(); ++i) {
9063 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9064 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9065 }
9066 return clients;
9067}
9068
9069void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9070 PortHandleVector clients;
9071 for (auto stream : streams) {
9072 PortHandleVector clientsForStream = getClientsForStream(stream);
9073 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9074 }
9075 mpClientInterface->invalidateTracks(clients);
9076}
9077
jiabin220eea12024-05-17 17:55:20 +00009078void AudioPolicyManager::updateClientsInternalMute(
9079 const sp<android::SwAudioOutputDescriptor> &desc) {
9080 if (!desc->isBitPerfect() ||
9081 !com::android::media::audioserver::
9082 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9083 // This is only used for bit perfect output now.
9084 return;
9085 }
9086 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9087 bool bitPerfectClientInternalMute = false;
9088 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9089 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9090 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9091 bitPerfectClient = client;
9092 continue;
9093 }
9094 bool muted = false;
9095 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9096 // System sound is muted.
9097 muted = true;
9098 } else {
9099 bitPerfectClientInternalMute = true;
9100 }
9101 if (client->setInternalMute(muted)) {
9102 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9103 if (!result.ok()) {
9104 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9105 continue;
9106 }
9107 media::TrackInternalMuteInfo info;
9108 info.portId = result.value();
9109 info.muted = client->getInternalMute();
9110 clientsInternalMute.push_back(std::move(info));
9111 }
9112 }
9113 if (bitPerfectClient != nullptr &&
9114 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9115 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9116 if (result.ok()) {
9117 media::TrackInternalMuteInfo info;
9118 info.portId = result.value();
9119 info.muted = bitPerfectClient->getInternalMute();
9120 clientsInternalMute.push_back(std::move(info));
9121 } else {
9122 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9123 __func__, bitPerfectClient->portId());
9124 }
9125 }
9126 if (!clientsInternalMute.empty()) {
9127 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9128 status != NO_ERROR) {
9129 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9130 }
9131 }
9132}
9133
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009134} // namespace android