blob: 6cb8c31df34bd13b60dd14505d1a2375db3dab58 [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
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// 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>
Atneya Nairb16666a2023-12-11 20:18:33 -080045#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070046#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070047#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070048#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070049#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070050#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070051#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070052#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070053#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070054#include <utils/Log.h>
55
Eric Laurentd4692962014-05-05 18:13:44 -070056#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010057#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurent3b73df72014-03-11 09:06:29 -070059namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070060
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010061using android::media::audio::common::AudioDevice;
62using android::media::audio::common::AudioDeviceAddress;
63using android::media::audio::common::AudioPortDeviceExt;
64using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000065using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070066
Eric Laurentdc462862016-07-19 12:29:53 -070067//FIXME: workaround for truncated touch sounds
68// to be removed when the problem is handled by system UI
69#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070070
71// Largest difference in dB on earpiece in call between the voice volume and another
72// media / notification / system volume.
73constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
74
jiabin06e4bab2019-07-29 10:13:34 -070075template <typename T>
76bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
77{
78 if (left.size() != right.size()) {
79 return false;
80 }
81 for (size_t index = 0; index < right.size(); index++) {
82 if (left[index] != right[index]) {
83 return false;
84 }
85 }
86 return true;
87}
88
89template <typename T>
90bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
91{
92 return !(left == right);
93}
94
Eric Laurente552edb2014-03-10 17:42:56 -070095// ----------------------------------------------------------------------------
96// AudioPolicyInterface implementation
97// ----------------------------------------------------------------------------
98
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010099status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
100 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
101 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800102 nextAudioPortGeneration();
103 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800104}
105
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100106status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
107 audio_policy_dev_state_t state,
108 const char* device_address,
109 const char* device_name,
110 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800111 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
113 status == OK) {
114 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
115 } else {
116 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
117 return status;
118 }
119}
120
François Gaffie11d30102018-11-02 16:09:09 +0100121void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000122 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200123{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000124 audio_port_v7 devicePort;
125 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000126 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000127 status != OK) {
Andy Hungf7786a42024-02-08 21:19:47 -0800128 ALOGE("Error %d while setting connected state for device %s",
129 static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000130 device->getDeviceTypeAddr().toString(false).c_str());
131 }
François Gaffie44481e72016-04-20 07:49:57 +0200132}
133
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100134status_t AudioPolicyManager::setDeviceConnectionStateInt(
135 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
136 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100137 if (port.ext.getTag() != AudioPortExt::device) {
138 return BAD_VALUE;
139 }
140 audio_devices_t device_type;
141 std::string device_address;
142 if (status_t status = aidl2legacy_AudioDevice_audio_device(
143 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
144 status != OK) {
145 return status;
146 };
147 const char* device_name = port.name.c_str();
148 // connect/disconnect only 1 device at a time
149 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
150 return BAD_VALUE;
151
152 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
153 device_type, device_address.c_str(), device_name, encodedFormat,
154 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000155 if (device == nullptr) {
156 return INVALID_OPERATION;
157 }
158 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
159 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
160 }
161 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100162}
163
François Gaffie11d30102018-11-02 16:09:09 +0100164status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800165 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166 const char* device_address,
167 const char* device_name,
168 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800169 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
171 status == OK) {
172 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
173 } else {
174 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
175 return status;
176 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700177}
Paul McLeane743a472015-01-28 11:07:31 -0800178
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
180 audio_policy_dev_state_t state)
181{
Eric Laurente552edb2014-03-10 17:42:56 -0700182 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700184 SortedVector <audio_io_handle_t> outputs;
185
François Gaffie11d30102018-11-02 16:09:09 +0100186 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700187
Eric Laurente552edb2014-03-10 17:42:56 -0700188 // save a copy of the opened output descriptors before any output is opened or closed
189 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
190 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100191
192 bool wasLeUnicastActive = isLeUnicastActive();
193
Eric Laurente552edb2014-03-10 17:42:56 -0700194 switch (state)
195 {
196 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800197 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700198 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100199 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700200 return INVALID_OPERATION;
201 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800202 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700203 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700204
Eric Laurente552edb2014-03-10 17:42:56 -0700205 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200206 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700207 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700208 }
209
François Gaffie44481e72016-04-20 07:49:57 +0200210 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
211 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000212 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200213
François Gaffie11d30102018-11-02 16:09:09 +0100214 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
215 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200216
Francois Gaffie716e1432019-01-14 16:58:59 +0100217 mHwModules.cleanUpForDevice(device);
218
jiabinc0048632023-04-27 22:04:31 +0000219 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700220 return INVALID_OPERATION;
221 }
François Gaffie2110e042015-03-24 08:41:51 +0100222
jiabin1c4794b2020-05-05 10:08:05 -0700223 // Populate encapsulation information when a output device is connected.
224 device->setEncapsulationInfoFromHal(mpClientInterface);
225
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700226 // outputs should never be empty here
227 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
228 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100229 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800230
Eric Laurent3ae5f312015-02-03 17:12:08 -0800231 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700232 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700233 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700234 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700236 return INVALID_OPERATION;
237 }
238
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700240
jiabinc0048632023-04-27 22:04:31 +0000241 // Notify the HAL to prepare to disconnect device
242 broadcastDeviceConnectionState(
243 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
Eric Laurente552edb2014-03-10 17:42:56 -0700245 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100246 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700247
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100248 mOutputs.clearSessionRoutesForDevice(device);
249
François Gaffie11d30102018-11-02 16:09:09 +0100250 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100251
jiabinc0048632023-04-27 22:04:31 +0000252 // Send Disconnect to HALs
253 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
254
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800255 // Reset active device codec
256 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
257
Kriti Dangef6be8f2020-11-05 11:58:19 +0100258 // remove device from mReportedFormatsMap cache
259 mReportedFormatsMap.erase(device);
260
jiabina84c3d32022-12-02 18:59:55 +0000261 // remove preferred mixer configurations
262 mPreferredMixerAttrInfos.erase(device->getId());
263
Eric Laurente552edb2014-03-10 17:42:56 -0700264 } break;
265
266 default:
François Gaffie11d30102018-11-02 16:09:09 +0100267 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700268 return BAD_VALUE;
269 }
270
Eric Laurent736a1022019-03-27 18:28:46 -0700271 // Propagate device availability to Engine
272 setEngineDeviceConnectionState(device, state);
273
Eric Laurentae970022019-01-29 14:25:04 -0800274 // No need to evaluate playback routing when connecting a remote submix
275 // output device used by a dynamic policy of type recorder as no
276 // playback use case is affected.
277 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700278 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800279 for (audio_io_handle_t output : outputs) {
280 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800281 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
282 if (policyMix != nullptr
283 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000284 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800285 doCheckForDeviceAndOutputChanges = false;
286 break;
287 }
288 }
289 }
290
291 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700292 // outputs must be closed after checkOutputForAllStrategies() is executed
293 if (!outputs.isEmpty()) {
294 for (audio_io_handle_t output : outputs) {
295 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100296 // close unused outputs after device disconnection or direct outputs that have
297 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200298 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200299 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
300 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200301 (desc->mDirectOpenCount == 0))
302 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
303 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200304 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700305 closeOutput(output);
306 }
Eric Laurente552edb2014-03-10 17:42:56 -0700307 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
309 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700310 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700311 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800312 };
313
314 if (doCheckForDeviceAndOutputChanges) {
315 checkForDeviceAndOutputChanges(checkCloseOutputs);
316 } else {
317 checkCloseOutputs();
318 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100319 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100320 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700321 const DeviceVector activeMediaDevices =
322 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000323 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700324 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700325 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530326 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
327 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100328 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700329 // do not force device change on duplicated output because if device is 0, it will
330 // also force a device 0 for the two outputs it is duplicated to which may override
331 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100332 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100333 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700334 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700335 // always force when disconnecting (a non-duplicated device)
336 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000337 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
338 // If the device is using preferred mixer attributes, the output need to reopen
339 // with default configuration when the new selected devices are different from
340 // current routing devices
341 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
342 continue;
343 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530344 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700345 }
jiabinbce0c1d2020-10-05 11:20:18 -0700346 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000347 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700348 desc->supportsDevicesForPlayback(activeMediaDevices)) {
349 // Reopen the output to query the dynamic profiles when there is not active
350 // clients or all active clients will be rerouted. Otherwise, set the flag
351 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
352 // can be reopened to query dynamic profiles when all clients are inactive.
353 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000354 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700355 } else {
356 desc->mPendingReopenToQueryProfiles = true;
357 }
358 }
359 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
360 // Clear the flag that previously set for re-querying profiles.
361 desc->mPendingReopenToQueryProfiles = false;
362 }
363 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000364 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700365
Eric Laurentd60560a2015-04-10 11:31:20 -0700366 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100367 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700368 }
369
Eric Laurent96d1dda2022-03-14 17:14:19 +0100370 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
371
Eric Laurent72aa32f2014-05-30 18:51:48 -0700372 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700373 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700374 } // end if is output device
375
Eric Laurente552edb2014-03-10 17:42:56 -0700376 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700377 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100378 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700379 switch (state)
380 {
381 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700382 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700383 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100384 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700385 return INVALID_OPERATION;
386 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700387
388 if (mAvailableInputDevices.add(device) < 0) {
389 return NO_MEMORY;
390 }
391
François Gaffie44481e72016-04-20 07:49:57 +0200392 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
393 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000394 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200395
Eric Laurent0dd51852019-04-19 18:18:58 -0700396 if (checkInputsForDevice(device, state) != NO_ERROR) {
397 mAvailableInputDevices.remove(device);
398
jiabinc0048632023-04-27 22:04:31 +0000399 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100400
401 mHwModules.cleanUpForDevice(device);
402
Eric Laurentd4692962014-05-05 18:13:44 -0700403 return INVALID_OPERATION;
404 }
405
Eric Laurentd4692962014-05-05 18:13:44 -0700406 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700407
408 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700409 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700410 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100411 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700412 return INVALID_OPERATION;
413 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700414
François Gaffie11d30102018-11-02 16:09:09 +0100415 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700416
jiabinc0048632023-04-27 22:04:31 +0000417 // Notify the HAL to prepare to disconnect device
418 broadcastDeviceConnectionState(
419 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700420
François Gaffie11d30102018-11-02 16:09:09 +0100421 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700422
423 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100424
jiabinc0048632023-04-27 22:04:31 +0000425 // Set Disconnect to HALs
426 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
427
Kriti Dangef6be8f2020-11-05 11:58:19 +0100428 // remove device from mReportedFormatsMap cache
429 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700430 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700431
432 default:
François Gaffie11d30102018-11-02 16:09:09 +0100433 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700434 return BAD_VALUE;
435 }
436
Eric Laurent736a1022019-03-27 18:28:46 -0700437 // Propagate device availability to Engine
438 setEngineDeviceConnectionState(device, state);
439
Eric Laurent0dd51852019-04-19 18:18:58 -0700440 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700441 // As the input device list can impact the output device selection, update
442 // getDeviceForStrategy() cache
443 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700444
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100445 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200446 // Reconnect Audio Source
447 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
448 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
449 checkAudioSourceForAttributes(attributes);
450 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700451 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100452 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700453 }
454
Eric Laurentb52c1522014-05-20 11:27:36 -0700455 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700456 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700457 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700458
François Gaffie11d30102018-11-02 16:09:09 +0100459 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700460 return BAD_VALUE;
461}
462
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100463status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
464 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800465 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700466 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
467 devDescr->setName(device_name);
468 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100469}
470
Eric Laurent736a1022019-03-27 18:28:46 -0700471void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
472 audio_policy_dev_state_t state) {
473
474 // the Engine does not have to know about remote submix devices used by dynamic audio policies
475 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
476 return;
477 }
478 mEngine->setDeviceConnectionState(device, state);
479}
480
481
Eric Laurente0720872014-03-11 09:30:41 -0700482audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100483 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700484{
Eric Laurent634b7142016-04-20 13:48:02 -0700485 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800486 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
487 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700488 (strlen(device_address) != 0)/*matchAddress*/);
489
490 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100491 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700492 device, device_address);
493 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
494 }
François Gaffie53615e22015-03-19 09:24:12 +0100495
Eric Laurent3a4311c2014-03-17 12:00:47 -0700496 DeviceVector *deviceVector;
497
Eric Laurente552edb2014-03-10 17:42:56 -0700498 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700499 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700500 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700501 deviceVector = &mAvailableInputDevices;
502 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100503 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700504 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700505 }
Eric Laurent634b7142016-04-20 13:48:02 -0700506
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800507 return (deviceVector->getDevice(
508 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700509 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800510}
511
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
513 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 const char *device_name,
515 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
518 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800520 // connect/disconnect only 1 device at a time
521 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
522
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700524 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800526 // Nothing to do: device is not connected
527 return NO_ERROR;
528 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800530
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700531 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800532 // configure codecs.
533 // Handle two specific cases by sending a set parameter to
534 // configure A2DP codecs. No need to toggle device state.
535 // Case 1: A2DP active device switches from primary to primary
536 // module
537 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100538 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700539 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800540 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
541 if (availablePrimaryOutputDevices().contains(devDesc) &&
542 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100543 bool isA2dp = audio_is_a2dp_out_device(device);
544 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
545 : String8(AudioParameter::keyReconfigLeSupported);
546 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800547 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100548 int isReconfigSupported;
549 repliedParameters.getInt(supportKey, isReconfigSupported);
550 if (isReconfigSupported) {
551 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
552 : String8(AudioParameter::keyReconfigLe);
553 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800554 param.add(key, String8("true"));
555 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
556 devDesc->setEncodedFormat(encodedFormat);
557 return NO_ERROR;
558 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700559 }
560 }
cnx421bd2dcc42020-07-11 14:58:44 +0800561 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
562 for (size_t i = 0; i < mOutputs.size(); i++) {
563 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
564 // mute media strategies and delay device switch by the largest
565 // This avoid sending the music tail into the earpiece or headset.
566 setStrategyMute(musicStrategy, true, desc);
567 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
568 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
569 nullptr, true /*fromCache*/).types());
570 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800571 // Toggle the device state: UNAVAILABLE -> AVAILABLE
572 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100573 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800574 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800575 device_address, device_name,
576 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800577 if (status != NO_ERROR) {
578 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
579 status);
580 return status;
581 }
582
583 status = setDeviceConnectionState(device,
584 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800585 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800586 if (status != NO_ERROR) {
587 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
588 status);
589 return status;
590 }
591
592 return NO_ERROR;
593}
594
Pattydd807582021-11-04 21:01:03 +0800595status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
596 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800597{
Pattydd807582021-11-04 21:01:03 +0800598 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800599 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800600 std::unordered_set<audio_format_t> formatSet;
601 sp<HwModule> primaryModule =
602 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700603 if (primaryModule == nullptr) {
604 ALOGE("%s() unable to get primary module", __func__);
605 return NO_INIT;
606 }
Pattydd807582021-11-04 21:01:03 +0800607
608 DeviceTypeSet audioDeviceSet;
609
610 switch(device) {
611 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
612 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
613 break;
614 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800615 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
616 break;
617 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
618 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800619 break;
620 default:
621 ALOGE("%s() device type 0x%08x not supported", __func__, device);
622 return BAD_VALUE;
623 }
624
jiabin9a3361e2019-10-01 09:38:30 -0700625 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800626 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800627 for (const auto& device : declaredDevices) {
628 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800629 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800630 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800631 return status;
632}
633
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100634DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
635{
636 DeviceVector rxSinkdevices{};
637 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
638 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
639 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
640 auto rxSinkDevice = rxSinkdevices.itemAt(0);
641 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
642 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
643 // retrieve Rx Source device descriptor
644 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
645 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
646
647 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
648 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
649 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
650 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
651 return DeviceVector(rxSinkDevice);
652 }
653 }
654 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
655 // the device returned is not necessarily reachable via this output
656 // (filter later by setOutputDevices())
657 return getNewOutputDevices(mPrimaryOutput, fromCache);
658}
659
660status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
661{
François Gaffiedb1755b2023-09-01 11:50:35 +0200662 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100663 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
664 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
665 }
666 return INVALID_OPERATION;
667}
668
669status_t AudioPolicyManager::updateCallRoutingInternal(
670 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671{
672 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100673 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700674 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200675 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700676 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100677 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700678 }
François Gaffie11d30102018-11-02 16:09:09 +0100679
Francois Gaffie716e1432019-01-14 16:58:59 +0100680 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100681 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200682
683 disconnectTelephonyAudioSource(mCallRxSourceClient);
684 disconnectTelephonyAudioSource(mCallTxSourceClient);
685
686 if (rxDevices.isEmpty()) {
687 ALOGW("%s() no selected output device", __func__);
688 return INVALID_OPERATION;
689 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000690 if (txSourceDevice == nullptr) {
691 ALOGE("%s() selected input device not available", __func__);
692 return INVALID_OPERATION;
693 }
François Gaffiec005e562018-11-06 15:04:49 +0100694
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100695 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100696 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700697
François Gaffie9eb18552018-11-05 10:33:26 +0100698 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700699 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100700 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700701 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100702 // retrieve Rx Source and Tx Sink device descriptors
703 sp<DeviceDescriptor> rxSourceDevice =
704 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
705 String8(),
706 AUDIO_FORMAT_DEFAULT);
707 sp<DeviceDescriptor> txSinkDevice =
708 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
709 String8(),
710 AUDIO_FORMAT_DEFAULT);
711
712 // RX and TX Telephony device are declared by Primary Audio HAL
713 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
714 (telephonyRxModule->getHalVersionMajor() >= 3)) {
715 if (rxSourceDevice == 0 || txSinkDevice == 0) {
716 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100717 ALOGE("%s() no telephony Tx and/or RX device", __func__);
718 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100719 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100720 // createAudioPatchInternal now supports both HW / SW bridging
721 createRxPatch = true;
722 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100723 } else {
724 // If the RX device is on the primary HW module, then use legacy routing method for
725 // voice calls via setOutputDevice() on primary output.
726 // Otherwise, create two audio patches for TX and RX path.
727 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
728 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700729 // If the TX device is also on the primary HW module, setOutputDevice() will take care
730 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100731 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
732 (txSinkDevice != 0);
733 }
734 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
735 // Otherwise, create two audio patches for TX and RX path.
736 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200737 if (!hasPrimaryOutput()) {
738 ALOGW("%s() no primary output available", __func__);
739 return INVALID_OPERATION;
740 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530741 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700742 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200743 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800744 // If the TX device is on the primary HW module but RX device is
745 // on other HW module, SinkMetaData of telephony input should handle it
746 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700747 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700748 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100749 // terminate active capture if on the same HW module as the call TX source device
750 // FIXME: would be better to refine to only inputs whose profile connects to the
751 // call TX device but this information is not in the audio patch and logic here must be
752 // symmetric to the one in startInput()
753 for (const auto& activeDesc : mInputs.getActiveInputs()) {
754 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
755 closeActiveClients(activeDesc);
756 }
757 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200758 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800759 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100760 if (waitMs != nullptr) {
761 *waitMs = muteWaitMs;
762 }
763 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800764}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700765
Mikhail Naganov100f0122018-11-29 11:22:16 -0800766bool AudioPolicyManager::isDeviceOfModule(
767 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
768 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
769 if (module != 0) {
770 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
771 .indexOf(devDesc) != NAME_NOT_FOUND
772 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
773 .indexOf(devDesc) != NAME_NOT_FOUND;
774 }
775 return false;
776}
777
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200778void AudioPolicyManager::connectTelephonyRxAudioSource()
779{
Francois Gaffie601801d2021-06-22 13:27:39 +0200780 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200781 const struct audio_port_config source = {
782 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
783 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
784 };
785 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100786
787 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
788 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
789 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
790 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200791 ALOGE_IF(mCallRxSourceClient == nullptr,
792 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200793}
794
Francois Gaffie601801d2021-06-22 13:27:39 +0200795void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200796{
Francois Gaffie601801d2021-06-22 13:27:39 +0200797 if (clientDesc == nullptr) {
798 return;
799 }
800 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
801 "%s error stopping audio source", __func__);
802 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200803}
804
805void AudioPolicyManager::connectTelephonyTxAudioSource(
806 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
807 uint32_t delayMs)
808{
Francois Gaffie601801d2021-06-22 13:27:39 +0200809 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200810 if (srcDevice == nullptr || sinkDevice == nullptr) {
811 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
812 return;
813 }
814 PatchBuilder patchBuilder;
815 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
816 ALOGV("%s between source %s and sink %s", __func__,
817 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200818 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200819 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
820
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200821 struct audio_port_config source = {};
822 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100823 mCallTxSourceClient = new SourceClientDescriptor(
824 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
825 mCommunnicationStrategy, toVolumeSource(aa), true);
826 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
827
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200828 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
829 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200830 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
831 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200832 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
833 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200834 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200835 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200836}
837
Eric Laurente0720872014-03-11 09:30:41 -0700838void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700839{
840 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100841 // store previous phone state for management of sonification strategy below
842 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100843 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100844
845 if (mEngine->setPhoneState(state) != NO_ERROR) {
846 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700847 return;
848 }
François Gaffie2110e042015-03-24 08:41:51 +0100849 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700850 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700851 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700852 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800853 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700854 }
855
François Gaffie2110e042015-03-24 08:41:51 +0100856 /**
857 * Switching to or from incall state or switching between telephony and VoIP lead to force
858 * routing command.
859 */
Eric Laurent74b71512019-11-06 17:21:57 -0800860 bool force = ((isStateInCall(oldState) != isStateInCall(state))
861 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700862
863 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700864 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700865
Eric Laurente552edb2014-03-10 17:42:56 -0700866 int delayMs = 0;
867 if (isStateInCall(state)) {
868 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100869 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
870 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700871 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700872 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700873 // mute media and sonification strategies and delay device switch by the largest
874 // latency of any output where either strategy is active.
875 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100876 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
877 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
878 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700879 (delayMs < (int)desc->latency()*2)) {
880 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700881 }
François Gaffiec005e562018-11-06 15:04:49 +0100882 setStrategyMute(musicStrategy, true, desc);
883 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
884 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
885 nullptr, true /*fromCache*/).types());
886 setStrategyMute(sonificationStrategy, true, desc);
887 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
888 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
889 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700890 }
891 }
892
François Gaffiedb1755b2023-09-01 11:50:35 +0200893 if (state == AUDIO_MODE_IN_CALL) {
894 (void)updateCallRouting(false /*fromCache*/, delayMs);
895 } else {
896 if (oldState == AUDIO_MODE_IN_CALL) {
897 disconnectTelephonyAudioSource(mCallRxSourceClient);
898 disconnectTelephonyAudioSource(mCallTxSourceClient);
899 }
900 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100901 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
902 // force routing command to audio hardware when ending call
903 // even if no device change is needed
904 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
905 rxDevices = mPrimaryOutput->devices();
906 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530907 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700908 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700909 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700910
jiabin3ff8d7d2022-12-13 06:27:44 +0000911 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700912 // reevaluate routing on all outputs in case tracks have been started during the call
913 for (size_t i = 0; i < mOutputs.size(); i++) {
914 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100915 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200916 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
917 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000918 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
919 // If the device is using preferred mixer attributes, the output need to reopen
920 // with default configuration when the new selected devices are different from
921 // current routing devices.
922 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
923 continue;
924 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530925 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200926 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700927 }
928 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000929 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700930
Eric Laurent96d1dda2022-03-14 17:14:19 +0100931 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
932
Eric Laurente552edb2014-03-10 17:42:56 -0700933 if (isStateInCall(state)) {
934 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700935 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800936 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700937 }
938
939 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100940 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
941 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700942}
943
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700944audio_mode_t AudioPolicyManager::getPhoneState() {
945 return mEngine->getPhoneState();
946}
947
Eric Laurente0720872014-03-11 09:30:41 -0700948void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100949 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700950{
François Gaffie2110e042015-03-24 08:41:51 +0100951 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700952 if (config == mEngine->getForceUse(usage)) {
953 return;
954 }
Eric Laurente552edb2014-03-10 17:42:56 -0700955
François Gaffie2110e042015-03-24 08:41:51 +0100956 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
957 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
958 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700959 }
François Gaffie2110e042015-03-24 08:41:51 +0100960 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
961 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
962 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700963
964 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700965 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800966
Eric Laurent22fcda22019-05-17 16:28:47 -0700967 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
968 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800969 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700970 }
971
Eric Laurentdc462862016-07-19 12:29:53 -0700972 //FIXME: workaround for truncated touch sounds
973 // to be removed when the problem is handled by system UI
974 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700975 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
976 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
977 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700978
979 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100980 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700981}
982
Eric Laurente0720872014-03-11 09:30:41 -0700983void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700984{
985 ALOGV("setSystemProperty() property %s, value %s", property, value);
986}
987
Dorin Drimusecc9f422022-03-09 17:57:40 +0100988// Find an MSD output profile compatible with the parameters passed.
989// When "directOnly" is set, restrict search to profiles for direct outputs.
990sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
991 const DeviceVector& devices,
992 uint32_t samplingRate,
993 audio_format_t format,
994 audio_channel_mask_t channelMask,
995 audio_output_flags_t flags,
996 bool directOnly)
997{
998 flags = getRelevantFlags(flags, directOnly);
999
1000 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1001 if (msdModule != nullptr) {
1002 // for the msd module check if there are patches to the output devices
1003 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1004 HwModuleCollection modules;
1005 modules.add(msdModule);
1006 return searchCompatibleProfileHwModules(
1007 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1008 flags, directOnly);
1009 }
1010 }
1011 return nullptr;
1012}
1013
Michael Chana94fbb22018-04-24 14:31:19 +10001014// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1015// search to profiles for direct outputs.
1016sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001017 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001018 uint32_t samplingRate,
1019 audio_format_t format,
1020 audio_channel_mask_t channelMask,
1021 audio_output_flags_t flags,
1022 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001023{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001024 flags = getRelevantFlags(flags, directOnly);
1025
1026 return searchCompatibleProfileHwModules(
1027 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1028}
1029
1030audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1031 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001032 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001033 // only retain flags that will drive the direct output profile selection
1034 // if explicitly requested
1035 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001036 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001037 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1038 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001039 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001040 return flags;
1041}
Eric Laurent861a6282015-05-18 15:40:16 -07001042
Dorin Drimusecc9f422022-03-09 17:57:40 +01001043sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1044 const HwModuleCollection& hwModules,
1045 const DeviceVector& devices,
1046 uint32_t samplingRate,
1047 audio_format_t format,
1048 audio_channel_mask_t channelMask,
1049 audio_output_flags_t flags,
1050 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001051 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001052 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001053 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001054 if (!curProfile->isCompatibleProfile(devices,
1055 samplingRate, NULL /*updatedSamplingRate*/,
1056 format, NULL /*updatedFormat*/,
1057 channelMask, NULL /*updatedChannelMask*/,
1058 flags)) {
1059 continue;
1060 }
1061 // reject profiles not corresponding to a device currently available
1062 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1063 continue;
1064 }
1065 // reject profiles if connected device does not support codec
1066 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1067 continue;
1068 }
1069 if (!directOnly) {
1070 return curProfile;
1071 }
1072
1073 // when searching for direct outputs, if several profiles are compatible, give priority
1074 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001075 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001076 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001077 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001078 }
1079 profile = curProfile;
1080 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1081 break;
1082 }
Eric Laurente552edb2014-03-10 17:42:56 -07001083 }
1084 }
Eric Laurent861a6282015-05-18 15:40:16 -07001085 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001086}
1087
Eric Laurentfa0f6742021-08-17 18:39:44 +02001088sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001089 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001090{
1091 for (const auto& hwModule : mHwModules) {
1092 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001093 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001094 continue;
1095 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001096 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001097 // reject profiles not corresponding to a device currently available
1098 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1099 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1100 continue;
1101 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001102 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1103 != devices.size()) {
1104 continue;
1105 }
1106 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001107 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1108 return curProfile;
1109 }
1110 }
1111 return nullptr;
1112}
1113
Eric Laurentf4e63452017-11-06 19:31:46 +00001114audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001115{
François Gaffiec005e562018-11-06 15:04:49 +01001116 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001117
1118 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1119 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1120 // format, flags, etc. This may result in some discrepancy for functions that utilize
1121 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1122 // and AudioSystem::getOutputSamplingRate().
1123
François Gaffie11d30102018-11-02 16:09:09 +01001124 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001125 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1126 if (stream == AUDIO_STREAM_MUSIC &&
1127 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1128 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1129 }
1130 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001131
François Gaffie11d30102018-11-02 16:09:09 +01001132 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1133 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001134 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001135}
1136
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001137status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1138 const audio_attributes_t *srcAttr,
1139 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001140{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001141 if (srcAttr != NULL) {
1142 if (!isValidAttributes(srcAttr)) {
1143 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1144 __func__,
1145 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1146 srcAttr->tags);
1147 return BAD_VALUE;
1148 }
1149 *dstAttr = *srcAttr;
1150 } else {
1151 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1152 ALOGE("%s: invalid stream type", __func__);
1153 return BAD_VALUE;
1154 }
François Gaffiec005e562018-11-06 15:04:49 +01001155 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001156 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001157
1158 // Only honor audibility enforced when required. The client will be
1159 // forced to reconnect if the forced usage changes.
1160 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001161 dstAttr->flags = static_cast<audio_flags_mask_t>(
1162 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001163 }
1164
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001165 return NO_ERROR;
1166}
1167
Kevin Rocard153f92d2018-12-18 18:33:28 -08001168status_t AudioPolicyManager::getOutputForAttrInt(
1169 audio_attributes_t *resultAttr,
1170 audio_io_handle_t *output,
1171 audio_session_t session,
1172 const audio_attributes_t *attr,
1173 audio_stream_type_t *stream,
1174 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001175 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001176 audio_output_flags_t *flags,
1177 audio_port_handle_t *selectedDeviceId,
1178 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001179 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001180 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001181 bool *isSpatialized,
1182 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001183{
François Gaffiec005e562018-11-06 15:04:49 +01001184 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001185 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001186 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001187 const sp<DeviceDescriptor> requestedDevice =
1188 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1189
Eric Laurent8a1095a2019-11-08 14:44:16 -08001190 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001191 *isSpatialized = false;
1192
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001193 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1194 if (status != NO_ERROR) {
1195 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001196 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001197 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001198 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001199 }
François Gaffiec005e562018-11-06 15:04:49 +01001200 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001201
François Gaffiec005e562018-11-06 15:04:49 +01001202 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1203 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001204
Oscar Azucena873d10f2023-01-12 18:34:42 -08001205 bool usePrimaryOutputFromPolicyMixes = false;
1206
Kevin Rocard153f92d2018-12-18 18:33:28 -08001207 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1208 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1209 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001210 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001211 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1212 .channel_mask = config->channel_mask,
1213 .format = config->format,
1214 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001215 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001216 mAvailableOutputDevices, requestedDevice, primaryMix,
1217 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001218 if (status != OK) {
1219 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001220 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001221
Kevin Rocard153f92d2018-12-18 18:33:28 -08001222 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001223 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1224 && !audio_is_linear_pcm(config->format)) {
1225 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001226 return BAD_VALUE;
1227 }
1228 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001229 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001230 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1231 primaryMix->mDeviceAddress,
1232 AUDIO_FORMAT_DEFAULT);
1233 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001234 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001235 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1236 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001237 // if a direct output can be opened to deliver the track's multi-channel content to the
1238 // output rather than being downmixed by the primary output, then use this direct
1239 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1240 // mix.
1241 bool tryDirectForChannelMask = policyDesc != nullptr
1242 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1243 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001244 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001245 audio_io_handle_t newOutput;
1246 status = openDirectOutput(
1247 *stream, session, config,
1248 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001249 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001250 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001251 policyDesc = mOutputs.valueFor(newOutput);
1252 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001253 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001254 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001255 policyDesc = nullptr;
1256 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001257 }
1258 if (policyDesc != nullptr) {
1259 policyDesc->mPolicyMix = primaryMix;
1260 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001261 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1262 : AUDIO_PORT_HANDLE_NONE;
1263 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1264 // Remove direct flag as it is not on a direct output.
1265 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1266 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001267
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001268 ALOGV("getOutputForAttr() returns output %d", *output);
1269 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1270 *outputType = API_OUT_MIX_PLAYBACK;
1271 } else {
1272 *outputType = API_OUTPUT_LEGACY;
1273 }
1274 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001275 } else {
1276 if (policyMixDevice != nullptr) {
1277 ALOGE("%s, try to use primary mix but no output found", __func__);
1278 return INVALID_OPERATION;
1279 }
1280 // Fallback to default engine selection as the selected primary mix device is not
1281 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001282 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001283 }
François Gaffiec005e562018-11-06 15:04:49 +01001284 // Virtual sources must always be dynamicaly or explicitly routed
1285 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1286 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1287 return BAD_VALUE;
1288 }
1289 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1290 // in order to let the choice of the order to future vendor engine
1291 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001292
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001293 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001294 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001295 }
1296
Nadav Barb2f18162018-07-18 13:01:53 +03001297 // Set incall music only if device was explicitly set, and fallback to the device which is
1298 // chosen by the engine if not.
1299 // FIXME: provide a more generic approach which is not device specific and move this back
1300 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001301 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001302 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001303 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001304 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001305 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001306 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001307 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001308 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001309 }
1310 }
1311
François Gaffiec005e562018-11-06 15:04:49 +01001312 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1313 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1314 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001315
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001316 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001317 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001318 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001319 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001320 ALOGV("%s() Using MSD devices %s instead of devices %s",
1321 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001322 } else {
1323 *output = AUDIO_IO_HANDLE_NONE;
1324 }
1325 }
1326 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001327 sp<PreferredMixerAttributesInfo> info = nullptr;
1328 if (outputDevices.size() == 1) {
1329 info = getPreferredMixerAttributesInfo(
1330 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001331 mEngine->getProductStrategyForAttributes(*resultAttr),
1332 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001333 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1334 // and it is currently active.
1335 if (info != nullptr && info->getUid() != uid &&
1336 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1337 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001338 info = nullptr;
1339 }
1340 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001341 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001342 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001343 // The client will be active if the client is currently preferred mixer owner and the
1344 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001345 *isBitPerfect = (info != nullptr
1346 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001347 && info->getUid() == uid
1348 && *output != AUDIO_IO_HANDLE_NONE
1349 // When bit-perfect output is selected for the preferred mixer attributes owner,
1350 // only need to consider the config matches.
1351 && mOutputs.valueFor(*output)->isConfigurationMatched(
1352 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001353 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001354 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001355 AudioProfileVector profiles;
1356 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1357 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001358 const auto channels = profiles[0]->getChannels();
1359 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1360 config->channel_mask = *channels.begin();
1361 }
1362 const auto sampleRates = profiles[0]->getSampleRates();
1363 if (!sampleRates.empty() &&
1364 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1365 config->sample_rate = *sampleRates.begin();
1366 }
jiabinf1c73972022-04-14 16:28:52 -07001367 config->format = profiles[0]->getFormat();
1368 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001369 return INVALID_OPERATION;
1370 }
Paul McLeanaa981192015-03-21 09:55:15 -07001371
François Gaffiec005e562018-11-06 15:04:49 +01001372 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001373 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001374 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001375 *selectedDeviceId = outputDevice->getId();
1376 break;
1377 }
1378 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001379
Eric Laurent8a1095a2019-11-08 14:44:16 -08001380 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1381 *outputType = API_OUTPUT_TELEPHONY_TX;
1382 } else {
1383 *outputType = API_OUTPUT_LEGACY;
1384 }
1385
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001386 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1387
1388 return NO_ERROR;
1389}
1390
1391status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1392 audio_io_handle_t *output,
1393 audio_session_t session,
1394 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001395 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001396 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001397 audio_output_flags_t *flags,
1398 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001399 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001400 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001401 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001402 bool *isSpatialized,
1403 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001404{
1405 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1406 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1407 return INVALID_OPERATION;
1408 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001409 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001410 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001411 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001412 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001413 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001414 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001415 const sp<DeviceDescriptor> requestedDevice =
1416 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1417
1418 // Prevent from storing invalid requested device id in clients
1419 const audio_port_handle_t sanitizedRequestedPortId =
1420 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1421 *selectedDeviceId = sanitizedRequestedPortId;
1422
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001423 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001424 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001425 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1426 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001427 if (status != NO_ERROR) {
1428 return status;
1429 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001430 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001431 if (secondaryOutputs != nullptr) {
1432 for (auto &secondaryMix : secondaryMixes) {
1433 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1434 if (outputDesc != nullptr &&
1435 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1436 secondaryOutputs->push_back(outputDesc->mIoHandle);
1437 weakSecondaryOutputDescs.push_back(outputDesc);
1438 }
1439 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001440 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001441
Eric Laurent8fc147b2018-07-22 19:13:55 -07001442 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001443 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001444 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001445 };
jiabin4ef93452019-09-10 14:29:54 -07001446 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001447
Eric Laurentc209fe42020-06-05 18:11:23 -07001448 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001449 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001450 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001451 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001452 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001453 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001454 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001455 std::move(weakSecondaryOutputDescs),
1456 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001457 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001458
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001459 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1460 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001461
Eric Laurente83b55d2014-11-14 10:06:21 -08001462 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001463}
1464
Eric Laurentc529cf62020-04-17 18:19:10 -07001465status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1466 audio_session_t session,
1467 const audio_config_t *config,
1468 audio_output_flags_t flags,
1469 const DeviceVector &devices,
1470 audio_io_handle_t *output) {
1471
1472 *output = AUDIO_IO_HANDLE_NONE;
1473
1474 // skip direct output selection if the request can obviously be attached to a mixed output
1475 // and not explicitly requested
1476 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1477 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1478 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1479 return NAME_NOT_FOUND;
1480 }
1481
1482 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1483 // This prevents creating an offloaded track and tearing it down immediately after start
1484 // when audioflinger detects there is an active non offloadable effect.
1485 // FIXME: We should check the audio session here but we do not have it in this context.
1486 // This may prevent offloading in rare situations where effects are left active by apps
1487 // in the background.
1488 sp<IOProfile> profile;
1489 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1490 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1491 profile = getProfileForOutput(
1492 devices, config->sample_rate, config->format, config->channel_mask,
1493 flags, true /* directOnly */);
1494 }
1495
1496 if (profile == nullptr) {
1497 return NAME_NOT_FOUND;
1498 }
1499
1500 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1501 for (size_t i = 0; i < mOutputs.size(); i++) {
1502 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1503 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1504 // reuse direct output if currently open by the same client
1505 // and configured with same parameters
1506 if ((config->sample_rate == desc->getSamplingRate()) &&
1507 (config->format == desc->getFormat()) &&
1508 (config->channel_mask == desc->getChannelMask()) &&
1509 (session == desc->mDirectClientSession)) {
1510 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001511 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001512 mOutputs.keyAt(i), session);
1513 *output = mOutputs.keyAt(i);
1514 return NO_ERROR;
1515 }
1516 }
1517 }
1518
1519 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001520 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1521 return NAME_NOT_FOUND;
1522 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1523 // MMAP gracefully handles lack of an exclusive track resource by mixing
1524 // above the audio framework. For AAudio to know that the limit is reached,
1525 // return an error.
1526 return NAME_NOT_FOUND;
1527 } else {
1528 // Close outputs on this profile, if available, to free resources for this request
1529 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1530 const auto desc = mOutputs.valueAt(i);
1531 if (desc->mProfile == profile) {
1532 closeOutput(desc->mIoHandle);
1533 }
1534 }
1535 }
1536 }
1537
1538 // Unable to close streams to find free resources for this request
1539 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001540 return NAME_NOT_FOUND;
1541 }
1542
Atneya Nairb16666a2023-12-11 20:18:33 -08001543 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001544
Michael Chan6fb34492020-12-08 15:44:49 +11001545 // An MSD patch may be using the only output stream that can service this request. Release
1546 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001547 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001548
Eric Laurentf1f22e72021-07-13 14:04:14 +02001549 status_t status =
1550 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001551
1552 // only accept an output with the requested parameters
1553 if (status != NO_ERROR ||
1554 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1555 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1556 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1557 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1558 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1559 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1560 config->channel_mask, outputDesc->getChannelMask());
1561 if (*output != AUDIO_IO_HANDLE_NONE) {
1562 outputDesc->close();
1563 }
1564 // fall back to mixer output if possible when the direct output could not be open
1565 if (audio_is_linear_pcm(config->format) &&
1566 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1567 return NAME_NOT_FOUND;
1568 }
1569 *output = AUDIO_IO_HANDLE_NONE;
1570 return BAD_VALUE;
1571 }
1572 outputDesc->mDirectOpenCount = 1;
1573 outputDesc->mDirectClientSession = session;
1574
1575 addOutput(*output, outputDesc);
1576 mPreviousOutputs = mOutputs;
1577 ALOGV("%s returns new direct output %d", __func__, *output);
1578 mpClientInterface->onAudioPortListUpdate();
1579 return NO_ERROR;
1580}
1581
François Gaffie11d30102018-11-02 16:09:09 +01001582audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1583 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001584 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001585 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001586 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001587 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001588 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001589 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001590 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001591{
Andy Hungc88b0642018-04-27 15:42:35 -07001592 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001593
jiabine375d412019-02-26 12:54:53 -08001594 // Discard haptic channel mask when forcing muting haptic channels.
1595 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001596 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1597 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001598
Eric Laurente552edb2014-03-10 17:42:56 -07001599 // open a direct output if required by specified parameters
1600 //force direct flag if offload flag is set: offloading implies a direct output stream
1601 // and all common behaviors are driven by checking only the direct flag
1602 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001603 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1604 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001605 }
Nadav Bar766fb022018-01-07 12:18:03 +02001606 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1607 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001608 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001609
1610 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1611
Eric Laurente83b55d2014-11-14 10:06:21 -08001612 // only allow deep buffering for music stream type
1613 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001614 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001615 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001616 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001617 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1618 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001619 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001620 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001621 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001622 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001623 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001624 audio_is_linear_pcm(config->format) &&
1625 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001626 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001627 AUDIO_OUTPUT_FLAG_DIRECT);
1628 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001629 }
Eric Laurente552edb2014-03-10 17:42:56 -07001630
Carter Hsua3abb402021-10-26 11:11:20 +08001631 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1632 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1633 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1634 }
1635
Eric Laurentf9230d52024-01-26 18:49:09 +01001636 // Use the spatializer output if the content can be spatialized, no preferred mixer
1637 // was specified and offload or direct playback is not explicitly requested.
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001638 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001639 if (mSpatializerOutput != nullptr
jiabin2462ce82024-01-12 20:37:59 +00001640 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
Eric Laurentf9230d52024-01-26 18:49:09 +01001641 && prefMixerConfigInfo == nullptr
1642 && ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001643 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001644 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001645 }
1646
Eric Laurentc529cf62020-04-17 18:19:10 -07001647 audio_config_t directConfig = *config;
1648 directConfig.channel_mask = channelMask;
1649 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1650 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001651 return output;
1652 }
1653
Eric Laurent14cbfca2016-03-17 09:42:16 -07001654 // A request for HW A/V sync cannot fallback to a mixed output because time
1655 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001656 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001657 return AUDIO_IO_HANDLE_NONE;
1658 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001659 // A request for Tuner cannot fallback to a mixed output
1660 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1661 return AUDIO_IO_HANDLE_NONE;
1662 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001663
Eric Laurente552edb2014-03-10 17:42:56 -07001664 // ignoring channel mask due to downmix capability in mixer
1665
1666 // open a non direct output
1667
1668 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001669 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001670 // get which output is suitable for the specified stream. The actual
1671 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001672 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001673 if (prefMixerConfigInfo != nullptr) {
1674 for (audio_io_handle_t outputHandle : outputs) {
1675 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1676 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1677 output = outputHandle;
1678 break;
1679 }
1680 }
1681 if (output == AUDIO_IO_HANDLE_NONE) {
1682 // No output open with the preferred profile. Open a new one.
1683 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1684 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1685 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1686 config.format = prefMixerConfigInfo->getConfigBase().format;
1687 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1688 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1689 &config, prefMixerConfigInfo->getFlags());
1690 if (preferredOutput == nullptr) {
1691 ALOGE("%s failed to open output with preferred mixer config", __func__);
1692 } else {
1693 output = preferredOutput->mIoHandle;
1694 }
1695 }
1696 } else {
1697 // at this stage we should ignore the DIRECT flag as no direct output could be
1698 // found earlier
1699 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1700 output = selectOutput(
1701 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1702 }
Eric Laurente552edb2014-03-10 17:42:56 -07001703 }
François Gaffie11d30102018-11-02 16:09:09 +01001704 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001705 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001706 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001707
Eric Laurente552edb2014-03-10 17:42:56 -07001708 return output;
1709}
1710
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001711sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001712 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1713 mAvailableInputDevices);
1714 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1715}
1716
1717DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1718 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1719 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001720}
1721
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001722const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001724 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1725 if (msdModule != 0) {
1726 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1727 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1728 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1729 const struct audio_port_config *source = &patch->mPatch.sources[j];
1730 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1731 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001732 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001733 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001734 }
1735 }
1736 }
1737 return msdPatches;
1738}
1739
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001740bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1741 ssize_t index = mAudioPatches.indexOfKey(handle);
1742 if (index < 0) {
1743 return false;
1744 }
1745 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1746 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1747 if (msdModule == nullptr) {
1748 return false;
1749 }
1750 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1751 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1752 return true;
1753 }
1754 index = getMsdOutputPatches().indexOfKey(handle);
1755 if (index < 0) {
1756 return false;
1757 }
1758 return true;
1759}
1760
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001761status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1762 const InputProfileCollection &inputProfiles,
1763 const OutputProfileCollection &outputProfiles,
1764 const sp<DeviceDescriptor> &sourceDevice,
1765 const sp<DeviceDescriptor> &sinkDevice,
1766 AudioProfileVector& sourceProfiles,
1767 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001768 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001769 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001770 return NO_INIT;
1771 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001772 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001773 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001774 return NO_INIT;
1775 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001776 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001777 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1778 inProfile->supportsDevice(sourceDevice)) {
1779 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001780 }
1781 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001782 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001783 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001784 outProfile->supportsDevice(sinkDevice)) {
1785 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001786 }
1787 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001788 return NO_ERROR;
1789}
1790
1791status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1792 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1793 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1794{
Dean Wheatley16809da2022-12-09 14:55:46 +11001795 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1796 static const std::vector<audio_format_t> formatsOrder = {{
1797 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001798 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1799 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001800 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1801 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1802 // preferred).
1803 std::vector<audio_channel_mask_t> masks = {{
1804 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1805 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1806 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1807 // insert index masks (higher counts most preferred) as preferred over position masks
1808 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1809 masks.insert(
1810 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1811 }
1812 return masks;
1813 }();
1814
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001815 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001816 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1817 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001818 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001819 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1820 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001821 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001822 }
1823 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1824 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1825 sinkConfig->format = bestSinkConfig.format;
1826 // For encoded streams force direct flag to prevent downstream mixing.
1827 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1828 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001829 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1830 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001831 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001832 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1833 // raw and IEC61937 framed streams.
1834 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1835 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1836 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001837 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1838 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001839 sourceConfig->channel_mask =
1840 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1841 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1842 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001843 sourceConfig->format = bestSinkConfig.format;
1844 // Copy input stream directly without any processing (e.g. resampling).
1845 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1846 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1847 if (hwAvSync) {
1848 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1849 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1850 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1851 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1852 }
1853 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1854 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1855 sinkConfig->config_mask |= config_mask;
1856 sourceConfig->config_mask |= config_mask;
1857 return NO_ERROR;
1858}
1859
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001860PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1861 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001862{
1863 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001864 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1865 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1866 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1867 if (deviceModule == nullptr) {
1868 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1869 return patchBuilder;
1870 }
1871 const InputProfileCollection inputProfiles = msdIsSource ?
1872 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1873 const OutputProfileCollection outputProfiles = msdIsSource ?
1874 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1875
1876 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1877 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1878 device : getMsdAudioOutDevices().itemAt(0);
1879 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1880
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1882 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001883 AudioProfileVector sourceProfiles;
1884 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1886 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001887 for (auto hwAvSync : { true, false }) {
1888 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1889 sourceProfiles, sinkProfiles) != NO_ERROR) {
1890 continue;
1891 }
1892 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1893 &sinkConfig) == NO_ERROR) {
1894 // Found a matching config. Re-create PatchBuilder with this config.
1895 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1896 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001897 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001898 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 " supporting PCM format conversion.", __func__);
1900 return patchBuilder;
1901}
1902
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001903status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001904 DeviceVector devices;
1905 if (outputDevices != nullptr && outputDevices->size() > 0) {
1906 devices.add(*outputDevices);
1907 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001908 // Use media strategy for unspecified output device. This should only
1909 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1910 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001911 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001912 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001913 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001914 }
Michael Chan6fb34492020-12-08 15:44:49 +11001915 std::vector<PatchBuilder> patchesToCreate;
1916 for (auto i = 0u; i < devices.size(); ++i) {
1917 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001918 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001919 }
1920 // Retain only the MSD patches associated with outputDevices request.
1921 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001922 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001923 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1924 auto retainedPatch = false;
1925 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1926 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1927 patchesToRemove.removeItemsAt(i);
1928 retainedPatch = true;
1929 break;
1930 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001931 }
Michael Chan6fb34492020-12-08 15:44:49 +11001932 if (retainedPatch) {
1933 it = patchesToCreate.erase(it);
1934 continue;
1935 }
1936 ++it;
1937 }
1938 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1939 return NO_ERROR;
1940 }
1941 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1942 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001943 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001944 }
Michael Chan6fb34492020-12-08 15:44:49 +11001945 status_t status = NO_ERROR;
1946 for (const auto &p : patchesToCreate) {
1947 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1948 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1949 char message[256];
1950 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1951 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1952 currStatus == NO_ERROR ? "Success" : "Error",
1953 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1954 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1955 if (currStatus == NO_ERROR) {
1956 ALOGD("%s", message);
1957 } else {
1958 ALOGE("%s", message);
1959 if (status == NO_ERROR) {
1960 status = currStatus;
1961 }
1962 }
1963 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001964 return status;
1965}
1966
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001967void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1968 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001969 for (size_t i = 0; i < msdPatches.size(); i++) {
1970 const auto& patch = msdPatches[i];
1971 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1972 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1973 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1974 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1975 releaseAudioPatch(patch->getHandle(), mUidCached);
1976 break;
1977 }
1978 }
1979 }
1980}
1981
Dorin Drimus94d94412022-02-02 09:05:02 +01001982bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001983 DeviceVector devicesToCheck =
1984 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001985 AudioPatchCollection msdPatches = getMsdOutputPatches();
1986 for (size_t i = 0; i < msdPatches.size(); i++) {
1987 const auto& patch = msdPatches[i];
1988 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1989 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1990 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1991 const auto& foundDevice = devicesToCheck.getDevice(
1992 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1993 if (foundDevice != nullptr) {
1994 devicesToCheck.remove(foundDevice);
1995 if (devicesToCheck.isEmpty()) {
1996 return true;
1997 }
1998 }
1999 }
2000 }
2001 }
2002 return false;
2003}
2004
Eric Laurente0720872014-03-11 09:30:41 -07002005audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002006 audio_output_flags_t flags,
2007 audio_format_t format,
2008 audio_channel_mask_t channelMask,
2009 uint32_t samplingRate,
2010 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002011{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002012 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2013 "%s called with format %#x", __func__, format);
2014
jiabinebb6af42020-06-09 17:31:17 -07002015 // Return the output that haptic-generating attached to when 1) session id is specified,
2016 // 2) haptic-generating effect exists for given session id and 3) the output that
2017 // haptic-generating effect attached to is in given outputs.
2018 if (sessionId != AUDIO_SESSION_NONE) {
2019 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2020 sessionId, FX_IID_HAPTICGENERATOR);
2021 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2022 return hapticGeneratingOutput;
2023 }
2024 }
2025
Eric Laurent16c66dd2019-05-01 17:54:10 -07002026 // Flags disqualifying an output: the match must happen before calling selectOutput()
2027 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2028 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2029
2030 // Flags expressing a functional request: must be honored in priority over
2031 // other criteria
2032 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2033 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002034 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2035 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002036 // Flags expressing a performance request: have lower priority than serving
2037 // requested sampling rate or channel mask
2038 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2039 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2040 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2041
2042 const audio_output_flags_t functionalFlags =
2043 (audio_output_flags_t)(flags & kFunctionalFlags);
2044 const audio_output_flags_t performanceFlags =
2045 (audio_output_flags_t)(flags & kPerformanceFlags);
2046
2047 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2048
Eric Laurente552edb2014-03-10 17:42:56 -07002049 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002050 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002051 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002052 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002053 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002054 // with tiebreak preferring the minimum number of extra functional flags
2055 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002056 // 3: the output supporting the exact channel mask
2057 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002058 // 5: the output with the highest sampling rate if the requested sample rate is
2059 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002060 // 6: the output with the highest number of requested performance flags
2061 // 7: the output with the bit depth the closest to the requested one
2062 // 8: the primary output
2063 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002064
Eric Laurent16c66dd2019-05-01 17:54:10 -07002065 // matching criteria values in priority order for best matching output so far
2066 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002067
Eric Laurent16c66dd2019-05-01 17:54:10 -07002068 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2069 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2070 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002071
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002072 for (audio_io_handle_t output : outputs) {
2073 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002074 // matching criteria values in priority order for current output
2075 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002076
Eric Laurent16c66dd2019-05-01 17:54:10 -07002077 if (outputDesc->isDuplicated()) {
2078 continue;
2079 }
2080 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2081 continue;
2082 }
Eric Laurent8838a382014-09-08 16:44:28 -07002083
Eric Laurent16c66dd2019-05-01 17:54:10 -07002084 // If haptic channel is specified, use the haptic output if present.
2085 // When using haptic output, same audio format and sample rate are required.
2086 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002087 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002088 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2089 continue;
2090 }
2091 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002092 && format == outputDesc->getFormat()
2093 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002094 currentMatchCriteria[0] = outputHapticChannelCount;
2095 }
2096
2097 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002098 const int matchingFunctionalFlags =
2099 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2100 const int totalFunctionalFlags =
2101 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2102 // Prefer matching functional flags, but subtract unnecessary functional flags.
2103 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002104
2105 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002106 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2107 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002108 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2109 channelCount <= outputChannelCount) {
2110 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002111 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2112 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002113 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002114 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002115 currentMatchCriteria[3] = outputChannelCount;
2116 }
2117
2118 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002119 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002120 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002121 }
2122
2123 // performance flags match
2124 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2125
2126 // format match
2127 if (format != AUDIO_FORMAT_INVALID) {
2128 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002129 PolicyAudioPort::kFormatDistanceMax -
2130 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002131 }
2132
2133 // primary output match
2134 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2135
2136 // compare match criteria by priority then value
2137 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2138 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2139 bestMatchCriteria = currentMatchCriteria;
2140 bestOutput = output;
2141
2142 std::stringstream result;
2143 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2144 std::ostream_iterator<int>(result, " "));
2145 ALOGV("%s new bestOutput %d criteria %s",
2146 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002147 }
2148 }
2149
Eric Laurent16c66dd2019-05-01 17:54:10 -07002150 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002151}
2152
Eric Laurent8fc147b2018-07-22 19:13:55 -07002153status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002154{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002155 ALOGV("%s portId %d", __FUNCTION__, portId);
2156
2157 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2158 if (outputDesc == 0) {
2159 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002160 return BAD_VALUE;
2161 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002162 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002163
Eric Laurent8fc147b2018-07-22 19:13:55 -07002164 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002165 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002166
Eric Laurent733ce942017-12-07 12:18:25 -08002167 status_t status = outputDesc->start();
2168 if (status != NO_ERROR) {
2169 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002170 }
2171
Eric Laurent97ac8712018-07-27 18:59:02 -07002172 uint32_t delayMs;
2173 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002174
2175 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002176 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002177 if (status == DEAD_OBJECT) {
2178 sp<SwAudioOutputDescriptor> desc =
2179 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2180 if (desc == nullptr) {
2181 // This is not common, it may indicate something wrong with the HAL.
2182 ALOGE("%s unable to open output with default config", __func__);
2183 return status;
2184 }
2185 desc->mUsePreferredMixerAttributes = true;
2186 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002187 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002188 }
jiabina84c3d32022-12-02 18:59:55 +00002189
2190 // If the client is the first one active on preferred mixer parameters, reopen the output
2191 // if the current mixer parameters doesn't match the preferred one.
2192 if (outputDesc->devices().size() == 1) {
2193 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2194 outputDesc->devices()[0]->getId(), client->strategy());
2195 if (info != nullptr && info->getUid() == client->uid()) {
2196 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2197 info->getConfigBase(), info->getFlags())) {
2198 stopSource(outputDesc, client);
2199 outputDesc->stop();
2200 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2201 config.channel_mask = info->getConfigBase().channel_mask;
2202 config.sample_rate = info->getConfigBase().sample_rate;
2203 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002204 sp<SwAudioOutputDescriptor> desc =
2205 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2206 if (desc == nullptr) {
2207 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002208 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002209 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002210 // Intentionally return error to let the client side resending request for
2211 // creating and starting.
2212 return DEAD_OBJECT;
2213 }
2214 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002215 if (info->getActiveClientCount() == 1 &&
2216 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2217 // If it is first bit-perfect client, reroute all clients that will be routed to
2218 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2219 PortHandleVector clientsToInvalidate;
2220 for (size_t i = 0; i < mOutputs.size(); i++) {
2221 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002222 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002223 continue;
2224 }
2225 for (const auto& c : mOutputs[i]->getClientIterable()) {
2226 clientsToInvalidate.push_back(c->portId());
2227 }
2228 }
2229 if (!clientsToInvalidate.empty()) {
2230 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2231 __func__);
2232 mpClientInterface->invalidateTracks(clientsToInvalidate);
2233 }
2234 }
jiabina84c3d32022-12-02 18:59:55 +00002235 }
2236 }
2237
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002238 if (client->hasPreferredDevice()) {
2239 // playback activity with preferred device impacts routing occurred, inform upper layers
2240 mpClientInterface->onRoutingUpdated();
2241 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002242 if (delayMs != 0) {
2243 usleep(delayMs * 1000);
2244 }
2245
2246 return status;
2247}
2248
Eric Laurent96d1dda2022-03-14 17:14:19 +01002249bool AudioPolicyManager::isLeUnicastActive() const {
2250 if (isInCall()) {
2251 return true;
2252 }
2253 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2254}
2255
2256bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2257 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2258 return false;
2259 }
2260 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2261 ALOGV("%s active %d", __func__, active);
2262 return active;
2263}
2264
Eric Laurent97ac8712018-07-27 18:59:02 -07002265status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2266 const sp<TrackClientDescriptor>& client,
2267 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002268{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002269 // cannot start playback of STREAM_TTS if any other output is being used
2270 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002271
2272 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002273 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002274 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002275 auto clientStrategy = client->strategy();
2276 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002277 if (stream == AUDIO_STREAM_TTS) {
2278 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002279 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002280 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002281 return INVALID_OPERATION;
2282 } else {
2283 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2284 }
2285 } else {
2286 // some playback other than beacon starts
2287 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2288 }
2289
Eric Laurent77305a62016-07-25 16:39:22 -07002290 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002291 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002292 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002293
François Gaffie11d30102018-11-02 16:09:09 +01002294 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002295 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002296 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002297 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002298 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002299 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002300 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002301 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002302 } else {
2303 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002304 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002305 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2306 AUDIO_FORMAT_DEFAULT);
2307 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2308 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002309 }
2310
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002311 // requiresMuteCheck is false when we can bypass mute strategy.
2312 // It covers a common case when there is no materially active audio
2313 // and muting would result in unnecessary delay and dropped audio.
2314 const uint32_t outputLatencyMs = outputDesc->latency();
2315 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002316 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002317
Eric Laurente552edb2014-03-10 17:42:56 -07002318 // increment usage count for this stream on the requested output:
2319 // NOTE that the usage count is the same for duplicated output and hardware output which is
2320 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002321 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002322
2323 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002324 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002325 // Preferred device may be exclusive, use only if no other active clients on this output
2326 devices = DeviceVector(
2327 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2328 } else {
2329 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2330 }
François Gaffie11d30102018-11-02 16:09:09 +01002331 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002332 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002333 }
2334 }
Eric Laurente552edb2014-03-10 17:42:56 -07002335
François Gaffiec005e562018-11-06 15:04:49 +01002336 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002337 selectOutputForMusicEffects();
2338 }
2339
François Gaffie1c878552018-11-22 16:53:21 +01002340 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002341 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002342 if (devices.isEmpty()) {
2343 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002344 }
François Gaffiec005e562018-11-06 15:04:49 +01002345 bool shouldWait =
2346 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2347 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2348 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002349 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002350 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002351 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002352 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002353 // An output has a shared device if
2354 // - managed by the same hw module
2355 // - supports the currently selected device
2356 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002357 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002358
Eric Laurent77305a62016-07-25 16:39:22 -07002359 // force a device change if any other output is:
2360 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002361 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002362 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002363 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002364 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002365 // change the device currently selected by the other output.
2366 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002367 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002368 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002369 force = true;
2370 }
2371 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002372 // a notification so that audio focus effect can propagate, or that a mute/unmute
2373 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002374 const uint32_t latencyMs = desc->latency();
2375 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2376
2377 if (shouldWait && isActive && (waitMs < latencyMs)) {
2378 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002379 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002380
2381 // Require mute check if another output is on a shared device
2382 // and currently active to have proper drain and avoid pops.
2383 // Note restoring AudioTracks onto this output needs to invoke
2384 // a volume ramp if there is no mute.
2385 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002386 }
2387 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002388
jiabin3ff8d7d2022-12-13 06:27:44 +00002389 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2390 // If the output is open with preferred mixer attributes, but the routed device is
2391 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2392 // changed.
2393 return DEAD_OBJECT;
2394 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002395 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302396 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2397 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002398
Eric Laurente552edb2014-03-10 17:42:56 -07002399 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002400 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002401 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002402 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002403 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002404 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002405 outputDesc->useHwGain() /*force*/)) {
2406 // request AudioService to reinitialize the volume curves asynchronously
2407 ALOGE("checkAndSetVolume failed, requesting volume range init");
2408 mpClientInterface->onVolumeRangeInitRequest();
2409 };
Eric Laurente552edb2014-03-10 17:42:56 -07002410
2411 // update the outputs if starting an output with a stream that can affect notification
2412 // routing
2413 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002414
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002415 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002416 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002417 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002418 }
Eric Laurentdc462862016-07-19 12:29:53 -07002419
2420 if (waitMs > muteWaitMs) {
2421 *delayMs = waitMs - muteWaitMs;
2422 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002423
2424 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2425 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2426 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2427 // change occurs after the MixerThread starts and causes a stream volume
2428 // glitch.
2429 //
2430 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002431 }
Eric Laurentdc462862016-07-19 12:29:53 -07002432
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002433 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002434 mEngine->getForceUse(
2435 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002436 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002437 }
2438
Eric Laurent97ac8712018-07-27 18:59:02 -07002439 // Automatically enable the remote submix input when output is started on a re routing mix
2440 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002441 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2442 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002443 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2444 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2445 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002446 "remote-submix",
2447 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002448 }
2449
Eric Laurent96d1dda2022-03-14 17:14:19 +01002450 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2451
Eric Laurente552edb2014-03-10 17:42:56 -07002452 return NO_ERROR;
2453}
2454
Eric Laurent96d1dda2022-03-14 17:14:19 +01002455void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2456 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2457 bool isUnicastActive = isLeUnicastActive();
2458
2459 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002460 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002461 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2462 for (size_t i = 0; i < mOutputs.size(); i++) {
2463 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2464 if (desc != ignoredOutput && desc->isActive()
2465 && ((isUnicastActive &&
2466 !desc->devices().
2467 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2468 || (wasUnicastActive &&
2469 !desc->devices().getDevicesFromTypes(
2470 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2471 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2472 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002473 if (desc->mUsePreferredMixerAttributes && force) {
2474 // If the device is using preferred mixer attributes, the output need to reopen
2475 // with default configuration when the new selected devices are different from
2476 // current routing devices.
2477 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2478 continue;
2479 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302480 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002481 // re-apply device specific volume if not done by setOutputDevice()
2482 if (!force) {
2483 applyStreamVolumes(desc, newDevices.types(), delayMs);
2484 }
2485 }
2486 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002487 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002488 }
2489}
2490
Eric Laurent8fc147b2018-07-22 19:13:55 -07002491status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002492{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002493 ALOGV("%s portId %d", __FUNCTION__, portId);
2494
2495 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2496 if (outputDesc == 0) {
2497 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002498 return BAD_VALUE;
2499 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002500 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002501
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002502 if (client->hasPreferredDevice(true)) {
2503 // playback activity with preferred device impacts routing occurred, inform upper layers
2504 mpClientInterface->onRoutingUpdated();
2505 }
2506
Eric Laurent97ac8712018-07-27 18:59:02 -07002507 ALOGV("stopOutput() output %d, stream %d, session %d",
2508 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002509
Eric Laurent97ac8712018-07-27 18:59:02 -07002510 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002511
Eric Laurent733ce942017-12-07 12:18:25 -08002512 if (status == NO_ERROR ) {
2513 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002514 } else {
2515 return status;
2516 }
2517
2518 if (outputDesc->devices().size() == 1) {
2519 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2520 outputDesc->devices()[0]->getId(), client->strategy());
2521 if (info != nullptr && info->getUid() == client->uid()) {
2522 info->decreaseActiveClient();
2523 if (info->getActiveClientCount() == 0) {
2524 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2525 }
2526 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002527 }
2528 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002529}
2530
Eric Laurent97ac8712018-07-27 18:59:02 -07002531status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2532 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002533{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002534 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002535 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002536 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002537 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002538
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002539 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2540
François Gaffie1c878552018-11-22 16:53:21 +01002541 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2542 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002543 // Automatically disable the remote submix input when output is stopped on a
2544 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002545 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002546 if (isSingleDeviceType(
2547 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002548 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002549 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002550 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2551 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002552 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002553 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 }
2555 }
2556 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002557 if (client->hasPreferredDevice(true) &&
2558 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002559 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002560 forceDeviceUpdate = true;
2561 }
2562
Eric Laurente552edb2014-03-10 17:42:56 -07002563 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002564 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002565
Eric Laurente552edb2014-03-10 17:42:56 -07002566 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002567 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002568 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002569 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002570
2571 // If the routing does not change, if an output is routed on a device using HwGain
2572 // (aka setAudioPortConfig) and there are still active clients following different
2573 // volume group(s), force reapply volume
2574 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2575 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2576
Eric Laurente552edb2014-03-10 17:42:56 -07002577 // delay the device switch by twice the latency because stopOutput() is executed when
2578 // the track stop() command is received and at that time the audio track buffer can
2579 // still contain data that needs to be drained. The latency only covers the audio HAL
2580 // and kernel buffers. Also the latency does not always include additional delay in the
2581 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302582 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002583 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002584
2585 // force restoring the device selection on other active outputs if it differs from the
2586 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002587 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002588 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002589 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002590 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002591 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002592 desc->isActive() &&
2593 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002594 (newDevices != desc->devices())) {
2595 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2596 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002597
jiabin3ff8d7d2022-12-13 06:27:44 +00002598 if (desc->mUsePreferredMixerAttributes && force) {
2599 // If the device is using preferred mixer attributes, the output need to
2600 // reopen with default configuration when the new selected devices are
2601 // different from current routing devices.
2602 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2603 continue;
2604 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302605 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002606
Eric Laurent57de36c2016-09-28 16:59:11 -07002607 // re-apply device specific volume if not done by setOutputDevice()
2608 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002609 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002610 }
Eric Laurente552edb2014-03-10 17:42:56 -07002611 }
2612 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002613 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002614 // update the outputs if stopping one with a stream that can affect notification routing
2615 handleNotificationRoutingForStream(stream);
2616 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002617
2618 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2619 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002620 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002621 }
2622
François Gaffiec005e562018-11-06 15:04:49 +01002623 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002624 selectOutputForMusicEffects();
2625 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002626
2627 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2628
Eric Laurente552edb2014-03-10 17:42:56 -07002629 return NO_ERROR;
2630 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002631 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002632 return INVALID_OPERATION;
2633 }
2634}
2635
jiabinbce0c1d2020-10-05 11:20:18 -07002636bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002637{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002638 ALOGV("%s portId %d", __FUNCTION__, portId);
2639
2640 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2641 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002642 // If an output descriptor is closed due to a device routing change,
2643 // then there are race conditions with releaseOutput from tracks
2644 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2645 // destroyed shortly thereafter.
2646 //
2647 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002648 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002649 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002650 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002651
2652 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002653
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302654 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2655 if (outputDesc->isClientActive(client)) {
2656 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2657 stopOutput(portId);
2658 }
2659
Eric Laurent8fc147b2018-07-22 19:13:55 -07002660 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2661 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002662 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002663 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002664 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002665 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002666 if (--outputDesc->mDirectOpenCount == 0) {
2667 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002668 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002669 }
2670 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302671
Andy Hung39efb7a2018-09-26 15:39:28 -07002672 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002673 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2674 // The output is pending reopened to query dynamic profiles and
2675 // there is no active clients
2676 closeOutput(outputDesc->mIoHandle);
2677 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2678 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2679 if (newOutputDesc == nullptr) {
2680 ALOGE("%s failed to open output", __func__);
2681 }
2682 return true;
2683 }
2684 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002685}
2686
Eric Laurentcaf7f482014-11-25 17:50:47 -08002687status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2688 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002689 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002690 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002691 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002692 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002693 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002694 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002695 input_type_t *inputType,
2696 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002697{
François Gaffiec005e562018-11-06 15:04:49 +01002698 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002699 "flags %#x attributes=%s requested device ID %d",
2700 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2701 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002702
Eric Laurentad2e7b92017-09-14 20:06:42 -07002703 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002704 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002705 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002706 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002707 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002708 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002709 sp<RecordClientDescriptor> clientDesc;
2710 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002711 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002712 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002713
2714 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2715 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2716 return INVALID_OPERATION;
2717 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002718
Francois Gaffie716e1432019-01-14 16:58:59 +01002719 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2720 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002721 }
2722
Paul McLean466dc8e2015-04-17 13:15:36 -06002723 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002724 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002725 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002726
Eric Laurentad2e7b92017-09-14 20:06:42 -07002727 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2728 // possible
2729 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2730 *input != AUDIO_IO_HANDLE_NONE) {
2731 ssize_t index = mInputs.indexOfKey(*input);
2732 if (index < 0) {
2733 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2734 status = BAD_VALUE;
2735 goto error;
2736 }
2737 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002738 RecordClientVector clients = inputDesc->getClientsForSession(session);
2739 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002740 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2741 status = BAD_VALUE;
2742 goto error;
2743 }
2744 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2745 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002746 // corresponds to a new client and is only permitted from the same UID.
2747 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002748 if (clients.size() > 1) {
2749 for (const auto& client : clients) {
2750 // The client map is ordered by key values (portId) and portIds are allocated
2751 // incrementaly. So the first client in this list is the one opened by audio flinger
2752 // when the mmap stream is created and should be ignored as it does not correspond
2753 // to an actual client
2754 if (client == *clients.cbegin()) {
2755 continue;
2756 }
2757 if (uid != client->uid() && !client->isSilenced()) {
2758 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2759 uid, client->portId(), client->uid());
2760 status = INVALID_OPERATION;
2761 goto error;
2762 }
Eric Laurent331679c2018-04-16 17:03:16 -07002763 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002764 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002765 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002766 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002767
Eric Laurentfecbceb2021-02-09 14:46:43 +01002768 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002769 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002770 }
2771
2772 *input = AUDIO_IO_HANDLE_NONE;
2773 *inputType = API_INPUT_INVALID;
2774
Francois Gaffie716e1432019-01-14 16:58:59 +01002775 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002776 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002777 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002778 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002779 ALOGW("%s could not find input mix for attr %s",
2780 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002781 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002782 }
jiabinc1de2df2019-05-07 14:26:40 -07002783 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2784 String8(attr->tags + strlen("addr=")),
2785 AUDIO_FORMAT_DEFAULT);
2786 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002787 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002788 __func__, attributes.source, attributes.tags);
2789 status = BAD_VALUE;
2790 goto error;
2791 }
2792
Kevin Rocard25f9b052019-02-27 15:08:54 -08002793 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2794 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2795 } else {
2796 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2797 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002798 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002799 if (explicitRoutingDevice != nullptr) {
2800 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002801 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002802 // Prevent from storing invalid requested device id in clients
2803 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002804 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002805 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2806 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002807 }
François Gaffie11d30102018-11-02 16:09:09 +01002808 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002809 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002810 status = BAD_VALUE;
2811 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002812 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002813 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2814 *inputType = API_INPUT_MIX_CAPTURE;
2815 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002816 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2817 // there is an external policy, but this input is attached to a mix of recorders,
2818 // meaning it receives audio injected into the framework, so the recorder doesn't
2819 // know about it and is therefore considered "legacy"
2820 *inputType = API_INPUT_LEGACY;
2821 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002822 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002823 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002824 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002825 } else {
2826 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002827 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002828
Eric Laurent599c7582015-12-07 18:05:55 -08002829 }
2830
François Gaffiec005e562018-11-06 15:04:49 +01002831 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002832 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002833 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002834 AudioProfileVector profiles;
2835 status_t ret = getProfilesForDevices(
2836 DeviceVector(device), profiles, flags, true /*isInput*/);
2837 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002838 const auto channels = profiles[0]->getChannels();
2839 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2840 config->channel_mask = *channels.begin();
2841 }
2842 const auto sampleRates = profiles[0]->getSampleRates();
2843 if (!sampleRates.empty() &&
2844 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2845 config->sample_rate = *sampleRates.begin();
2846 }
jiabinf1c73972022-04-14 16:28:52 -07002847 config->format = profiles[0]->getFormat();
2848 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002849 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002850 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002851
Eric Laurent8f42ea12018-08-08 09:08:25 -07002852exit:
2853
François Gaffiec005e562018-11-06 15:04:49 +01002854 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2855 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002856
Francois Gaffie716e1432019-01-14 16:58:59 +01002857 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002858 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002859 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860
Mikhail Naganov2996f672019-04-18 12:29:59 -07002861 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002862 requestedDeviceId, attributes.source, flags,
2863 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002864 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002865 // Move (if found) effect for the client session to its input
2866 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002867 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002868
2869 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2870 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002871
Eric Laurent599c7582015-12-07 18:05:55 -08002872 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002873
2874error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002875 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002876}
2877
2878
François Gaffie11d30102018-11-02 16:09:09 +01002879audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002880 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002881 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002882 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002883 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002884 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002885{
2886 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002887 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002888 bool isSoundTrigger = false;
2889
François Gaffiec005e562018-11-06 15:04:49 +01002890 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002891 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2892 if (index >= 0) {
2893 input = mSoundTriggerSessions.valueFor(session);
2894 isSoundTrigger = true;
2895 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2896 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2897 } else {
2898 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002899 }
François Gaffiec005e562018-11-06 15:04:49 +01002900 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002901 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002902 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002903 }
2904
Carter Hsua3abb402021-10-26 11:11:20 +08002905 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2906 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2907 }
2908
Eric Laurentfe231122017-11-17 17:48:06 -08002909 // sampling rate and flags may be updated by getInputProfile
2910 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2911 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002912 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002913 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002914 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002915 // find a compatible input profile (not necessarily identical in parameters)
2916 sp<IOProfile> profile = getInputProfile(
2917 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2918 if (profile == nullptr) {
2919 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002920 }
jiabin2fd710d2022-05-02 23:20:22 +00002921
Glenn Kasten05ddca52016-02-11 08:17:12 -08002922 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002923 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002924 if (samplingRate == 0) {
2925 samplingRate = profileSamplingRate;
2926 }
Eric Laurente552edb2014-03-10 17:42:56 -07002927
Eric Laurent322b4d22015-04-03 15:57:54 -07002928 if (profile->getModuleHandle() == 0) {
2929 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002930 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002931 }
2932
Eric Laurentec376dc2021-04-08 20:41:22 +02002933 // Reuse an already opened input if a client with the same session ID already exists
2934 // on that input
2935 for (size_t i = 0; i < mInputs.size(); i++) {
2936 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2937 if (desc->mProfile != profile) {
2938 continue;
2939 }
2940 RecordClientVector clients = desc->clientsList();
2941 for (const auto &client : clients) {
2942 if (session == client->session()) {
2943 return desc->mIoHandle;
2944 }
2945 }
2946 }
2947
Eric Laurent3974e3b2017-12-07 17:58:43 -08002948 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002949 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002950 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002951 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002952 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002953 continue;
2954 }
2955 // if sound trigger, reuse input if used by other sound trigger on same session
2956 // else
2957 // reuse input if active client app is not in IDLE state
2958 //
2959 RecordClientVector clients = desc->clientsList();
2960 bool doClose = false;
2961 for (const auto& client : clients) {
2962 if (isSoundTrigger != client->isSoundTrigger()) {
2963 continue;
2964 }
2965 if (client->isSoundTrigger()) {
2966 if (session == client->session()) {
2967 return desc->mIoHandle;
2968 }
2969 continue;
2970 }
2971 if (client->active() && client->appState() != APP_STATE_IDLE) {
2972 return desc->mIoHandle;
2973 }
2974 doClose = true;
2975 }
2976 if (doClose) {
2977 closeInput(desc->mIoHandle);
2978 } else {
2979 i++;
2980 }
2981 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002982 }
2983
Eric Laurentfe231122017-11-17 17:48:06 -08002984 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002985
Eric Laurentfe231122017-11-17 17:48:06 -08002986 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2987 lConfig.sample_rate = profileSamplingRate;
2988 lConfig.channel_mask = profileChannelMask;
2989 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002990
François Gaffie11d30102018-11-02 16:09:09 +01002991 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002992
2993 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002994 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002995 (profileSamplingRate != lConfig.sample_rate) ||
2996 !audio_formats_match(profileFormat, lConfig.format) ||
2997 (profileChannelMask != lConfig.channel_mask)) {
2998 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002999 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003000 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003001 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003002 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003003 }
Eric Laurent599c7582015-12-07 18:05:55 -08003004 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003005 }
3006
Eric Laurentc722f302014-12-10 11:21:49 -08003007 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003008
Eric Laurent599c7582015-12-07 18:05:55 -08003009 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003010 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003011
Eric Laurent599c7582015-12-07 18:05:55 -08003012 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003013}
3014
Eric Laurent4eb58f12018-12-07 16:41:02 -08003015status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003016{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003017 ALOGV("%s portId %d", __FUNCTION__, portId);
3018
3019 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3020 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003021 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003022 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003023 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003024 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003025 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003026 if (client->active()) {
3027 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3028 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003029 }
3030
Eric Laurent8f42ea12018-08-08 09:08:25 -07003031 audio_session_t session = client->session();
3032
Eric Laurent4eb58f12018-12-07 16:41:02 -08003033 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003034
Eric Laurent4eb58f12018-12-07 16:41:02 -08003035 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003036
Eric Laurent4eb58f12018-12-07 16:41:02 -08003037 status_t status = inputDesc->start();
3038 if (status != NO_ERROR) {
3039 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003040 }
Eric Laurente552edb2014-03-10 17:42:56 -07003041
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003042 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003043 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003044 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003045
Eric Laurent8f42ea12018-08-08 09:08:25 -07003046 // indicate active capture to sound trigger service if starting capture from a mic on
3047 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003048 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003049 if (device != nullptr) {
3050 status = setInputDevice(input, device, true /* force */);
3051 } else {
3052 ALOGW("%s no new input device can be found for descriptor %d",
3053 __FUNCTION__, inputDesc->getId());
3054 status = BAD_VALUE;
3055 }
Eric Laurente552edb2014-03-10 17:42:56 -07003056
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003057 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003058 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003059 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003060 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003061 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3062 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003063 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003064 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003065
François Gaffie11d30102018-11-02 16:09:09 +01003066 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3067 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003068 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003069 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003070 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003071
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 // automatically enable the remote submix output when input is started if not
3073 // used by a policy mix of type MIX_TYPE_RECORDERS
3074 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003075 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003076 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003077 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003079 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3080 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003081 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082 if (address != "") {
3083 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3084 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003085 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003086 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003087 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003088 } else if (status != NO_ERROR) {
3089 // Restore client activity state.
3090 inputDesc->setClientActive(client, false);
3091 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003092 }
3093
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003094 ALOGV("%s input %d source = %d status = %d exit",
3095 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003096
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003097 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003098}
3099
Eric Laurent8fc147b2018-07-22 19:13:55 -07003100status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003101{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003102 ALOGV("%s portId %d", __FUNCTION__, portId);
3103
3104 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3105 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003106 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003107 return BAD_VALUE;
3108 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003109 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003110 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003111 if (!client->active()) {
3112 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003113 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003114 }
Carter Hsue6139d52021-07-08 10:30:20 +08003115 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003116 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003117
Eric Laurent8f42ea12018-08-08 09:08:25 -07003118 inputDesc->stop();
3119 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003120 auto current_source = inputDesc->source();
3121 setInputDevice(input, getNewInputDevice(inputDesc),
3122 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003123 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003124 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003125 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003126 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003127 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3128 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003129 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003130 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003131
3132 // automatically disable the remote submix output when input is stopped if not
3133 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003134 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003135 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003136 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003137 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003138 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3139 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003140 }
3141 if (address != "") {
3142 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3143 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003144 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003145 }
3146 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003147 resetInputDevice(input);
3148
3149 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3150 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003151 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3152 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003153 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003154 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003155 }
3156 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003157 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003158 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003159}
3160
Eric Laurent8fc147b2018-07-22 19:13:55 -07003161void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003162{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003163 ALOGV("%s portId %d", __FUNCTION__, portId);
3164
3165 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3166 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003167 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003168 return;
3169 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003170 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003171 audio_io_handle_t input = inputDesc->mIoHandle;
3172
Eric Laurent8f42ea12018-08-08 09:08:25 -07003173 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003174
Andy Hung39efb7a2018-09-26 15:39:28 -07003175 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003176 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003177 if (inputDesc->getClientCount() > 0) {
3178 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003179 return;
3180 }
3181
Eric Laurent05b90f82014-08-27 15:32:29 -07003182 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003183 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003184 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003185}
3186
Eric Laurent8f42ea12018-08-08 09:08:25 -07003187void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003188{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003189 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003190
3191 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003192 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003193 }
3194}
3195
Eric Laurent8f42ea12018-08-08 09:08:25 -07003196void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3197{
3198 stopInput(portId);
3199 releaseInput(portId);
3200}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003201
Eric Laurent0dd51852019-04-19 18:18:58 -07003202void AudioPolicyManager::checkCloseInputs() {
3203 // After connecting or disconnecting an input device, close input if:
3204 // - it has no client (was just opened to check profile) OR
3205 // - none of its supported devices are connected anymore OR
3206 // - one of its clients cannot be routed to one of its supported
3207 // devices anymore. Otherwise update device selection
3208 std::vector<audio_io_handle_t> inputsToClose;
3209 for (size_t i = 0; i < mInputs.size(); i++) {
3210 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3211 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003212 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003213 inputsToClose.push_back(mInputs.keyAt(i));
3214 } else {
3215 bool close = false;
3216 for (const auto& client : input->clientsList()) {
3217 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003218 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3219 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003220 if (!input->supportedDevices().contains(device)) {
3221 close = true;
3222 break;
3223 }
3224 }
3225 if (close) {
3226 inputsToClose.push_back(mInputs.keyAt(i));
3227 } else {
3228 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3229 }
3230 }
3231 }
3232
3233 for (const audio_io_handle_t handle : inputsToClose) {
3234 ALOGV("%s closing input %d", __func__, handle);
3235 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003236 }
Eric Laurentd4692962014-05-05 18:13:44 -07003237}
3238
François Gaffie251c7f02018-11-07 10:41:08 +01003239void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003240{
3241 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003242 if (indexMin < 0 || indexMax < 0) {
3243 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3244 return;
3245 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003246 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003247
3248 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003249 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3250 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003251 continue;
3252 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003253 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003254 }
Eric Laurente552edb2014-03-10 17:42:56 -07003255}
3256
Eric Laurente0720872014-03-11 09:30:41 -07003257status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003258 int index,
3259 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003260{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003261 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003262 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3263 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3264 return NO_ERROR;
3265 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003266 ALOGV("%s: stream %s attributes=%s", __func__,
3267 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003268 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003269}
3270
Eric Laurente0720872014-03-11 09:30:41 -07003271status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003272 int *index,
3273 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003274{
François Gaffiec005e562018-11-06 15:04:49 +01003275 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3276 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003277 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003278 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003279 deviceTypes = mEngine->getOutputDevicesForStream(
3280 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003281 }
jiabin9a3361e2019-10-01 09:38:30 -07003282 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003283}
3284
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003285status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003286 int index,
3287 audio_devices_t device)
3288{
3289 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003290 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3291 if (group == VOLUME_GROUP_NONE) {
3292 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003293 return BAD_VALUE;
3294 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003295 ALOGV("%s: group %d matching with %s index %d",
3296 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003297 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003298 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003299 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003300 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3301 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3302 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3303 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003304 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3305
3306 status = setVolumeCurveIndex(index, device, curves);
3307 if (status != NO_ERROR) {
3308 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3309 return status;
3310 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003311
jiabin9a3361e2019-10-01 09:38:30 -07003312 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003313 auto curCurvAttrs = curves.getAttributes();
3314 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3315 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003316 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003317 } else if (!curves.getStreamTypes().empty()) {
3318 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003319 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003320 } else {
3321 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3322 return BAD_VALUE;
3323 }
jiabin9a3361e2019-10-01 09:38:30 -07003324 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3325 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003326
François Gaffiecfe17322018-11-07 13:41:29 +01003327 // update volume on all outputs and streams matching the following:
3328 // - The requested stream (or a stream matching for volume control) is active on the output
3329 // - The device (or devices) selected by the engine for this stream includes
3330 // the requested device
3331 // - For non default requested device, currently selected device on the output is either the
3332 // requested device or one of the devices selected by the engine for this stream
3333 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3334 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003335 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003336 for (size_t i = 0; i < mOutputs.size(); i++) {
3337 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003338 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003339
jiabin9a3361e2019-10-01 09:38:30 -07003340 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3341 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003342 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003343
3344 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003345 continue;
3346 }
3347 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3348 curDevices.find(device) == curDevices.end()) {
3349 continue;
3350 }
3351 bool applyVolume = false;
3352 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3353 curSrcDevices.insert(device);
3354 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003355 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3356 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003357 } else {
3358 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3359 }
3360 if (!applyVolume) {
3361 continue; // next output
3362 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003363 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3364 // If a higher priority strategy is active, and the output is routed to a device with a
3365 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003366 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003367 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003368 // If the volume source is active with higher priority source, ensure at least Sw Muted
3369 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003370 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3371 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3372 false /*preferredDevice*/);
3373 if (activeClients.empty()) {
3374 continue;
3375 }
3376 bool isPreempted = false;
3377 bool isHigherPriority = productStrategy < strategy;
3378 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003379 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003380 ALOGV("%s: Strategy=%d (\nrequester:\n"
3381 " group %d, volumeGroup=%d attributes=%s)\n"
3382 " higher priority source active:\n"
3383 " volumeGroup=%d attributes=%s) \n"
3384 " on output %zu, bailing out", __func__, productStrategy,
3385 group, group, toString(attributes).c_str(),
3386 client->volumeSource(), toString(client->attributes()).c_str(), i);
3387 applyVolume = false;
3388 isPreempted = true;
3389 break;
3390 }
3391 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003392 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003393 applyVolume = true;
3394 }
3395 }
3396 if (isPreempted || applyVolume) {
3397 break;
3398 }
3399 }
3400 if (!applyVolume) {
3401 continue; // next output
3402 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003403 }
François Gaffieed91f582020-01-31 10:35:37 +01003404 //FIXME: workaround for truncated touch sounds
3405 // delayed volume change for system stream to be removed when the problem is
3406 // handled by system UI
3407 status_t volStatus = checkAndSetVolume(
3408 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003409 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003410 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3411 if (volStatus != NO_ERROR) {
3412 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003413 }
3414 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003415
3416 // update voice volume if the an active call route exists
3417 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3418 && (curSrcDevices.find(
3419 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3420 != curSrcDevices.end())) {
3421 bool isVoiceVolSrc;
3422 bool isBtScoVolSrc;
3423 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3424 isVoiceVolSrc, isBtScoVolSrc, __func__)
3425 && (isVoiceVolSrc || isBtScoVolSrc)) {
3426 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3427 }
3428 }
3429
François Gaffiecfe17322018-11-07 13:41:29 +01003430 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3431 return status;
3432}
3433
François Gaffieaaac0fd2018-11-22 17:56:39 +01003434status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003435 audio_devices_t device,
3436 IVolumeCurves &volumeCurves)
3437{
3438 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3439 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003440 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3441 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003442 (index > volumeCurves.getVolumeIndexMax())) {
3443 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3444 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3445 return BAD_VALUE;
3446 }
3447 if (!audio_is_output_device(device)) {
3448 return BAD_VALUE;
3449 }
3450
3451 // Force max volume if stream cannot be muted
3452 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3453
François Gaffieaaac0fd2018-11-22 17:56:39 +01003454 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003455 volumeCurves.addCurrentVolumeIndex(device, index);
3456 return NO_ERROR;
3457}
3458
3459status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3460 int &index,
3461 audio_devices_t device)
3462{
3463 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3464 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003465 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003466 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003467 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003468 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003469 }
jiabin9a3361e2019-10-01 09:38:30 -07003470 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003471}
3472
3473status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3474 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003475 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003476{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003477 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003478 return BAD_VALUE;
3479 }
jiabin9a3361e2019-10-01 09:38:30 -07003480 index = curves.getVolumeIndex(deviceTypes);
3481 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003482 return NO_ERROR;
3483}
3484
3485status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3486 int &index)
3487{
3488 index = getVolumeCurves(attr).getVolumeIndexMin();
3489 return NO_ERROR;
3490}
3491
3492status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3493 int &index)
3494{
3495 index = getVolumeCurves(attr).getVolumeIndexMax();
3496 return NO_ERROR;
3497}
3498
Eric Laurent36829f92017-04-07 19:04:42 -07003499audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003500{
3501 // select one output among several suitable for global effects.
3502 // The priority is as follows:
3503 // 1: An offloaded output. If the effect ends up not being offloadable,
3504 // AudioFlinger will invalidate the track and the offloaded output
3505 // will be closed causing the effect to be moved to a PCM output.
3506 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003507 // 3: The primary output
3508 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003509
François Gaffiec005e562018-11-06 15:04:49 +01003510 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3511 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003512 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003513
Eric Laurent36829f92017-04-07 19:04:42 -07003514 if (outputs.size() == 0) {
3515 return AUDIO_IO_HANDLE_NONE;
3516 }
Eric Laurente552edb2014-03-10 17:42:56 -07003517
Eric Laurent36829f92017-04-07 19:04:42 -07003518 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3519 bool activeOnly = true;
3520
3521 while (output == AUDIO_IO_HANDLE_NONE) {
3522 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3523 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3524 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3525
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003526 for (audio_io_handle_t output : outputs) {
3527 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003528 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003529 continue;
3530 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003531 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3532 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003533 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003534 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003535 }
3536 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003537 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003538 }
3539 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003540 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003541 }
3542 }
3543 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3544 output = outputOffloaded;
3545 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3546 output = outputDeepBuffer;
3547 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3548 output = outputPrimary;
3549 } else {
3550 output = outputs[0];
3551 }
3552 activeOnly = false;
3553 }
3554
3555 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003556 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3557 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003558 mMusicEffectOutput = output;
3559 }
3560
3561 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003562 return output;
3563}
3564
Eric Laurent36829f92017-04-07 19:04:42 -07003565audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3566{
3567 return selectOutputForMusicEffects();
3568}
3569
Eric Laurente0720872014-03-11 09:30:41 -07003570status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003571 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003572 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003573 int session,
3574 int id)
3575{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003576 if (session != AUDIO_SESSION_DEVICE) {
3577 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003578 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003579 index = mInputs.indexOfKey(io);
3580 if (index < 0) {
3581 ALOGW("registerEffect() unknown io %d", io);
3582 return INVALID_OPERATION;
3583 }
Eric Laurente552edb2014-03-10 17:42:56 -07003584 }
3585 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003586 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3587 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3588 || strategy == PRODUCT_STRATEGY_NONE));
3589 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003590}
3591
Eric Laurentc241b0d2018-11-28 09:08:49 -08003592status_t AudioPolicyManager::unregisterEffect(int id)
3593{
3594 if (mEffects.getEffect(id) == nullptr) {
3595 return INVALID_OPERATION;
3596 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003597 if (mEffects.isEffectEnabled(id)) {
3598 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3599 setEffectEnabled(id, false);
3600 }
3601 return mEffects.unregisterEffect(id);
3602}
3603
3604status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3605{
3606 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3607 if (effect == nullptr) {
3608 return INVALID_OPERATION;
3609 }
3610
3611 status_t status = mEffects.setEffectEnabled(id, enabled);
3612 if (status == NO_ERROR) {
3613 mInputs.trackEffectEnabled(effect, enabled);
3614 }
3615 return status;
3616}
3617
Eric Laurent6c796322019-04-09 14:13:17 -07003618
3619status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3620{
3621 mEffects.moveEffects(ids, io);
3622 return NO_ERROR;
3623}
3624
Eric Laurentc75307b2015-03-17 15:29:32 -07003625bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3626{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003627 auto vs = toVolumeSource(stream, false);
3628 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003629}
3630
3631bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3632{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003633 auto vs = toVolumeSource(stream, false);
3634 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003635}
3636
Eric Laurente0720872014-03-11 09:30:41 -07003637bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003638{
3639 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003640 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003641 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003642 return true;
3643 }
3644 }
3645 return false;
3646}
3647
Eric Laurent275e8e92014-11-30 15:14:47 -08003648// Register a list of custom mixes with their attributes and format.
3649// When a mix is registered, corresponding input and output profiles are
3650// added to the remote submix hw module. The profile contains only the
3651// parameters (sampling rate, format...) specified by the mix.
3652// The corresponding input remote submix device is also connected.
3653//
3654// When a remote submix device is connected, the address is checked to select the
3655// appropriate profile and the corresponding input or output stream is opened.
3656//
3657// When capture starts, getInputForAttr() will:
3658// - 1 look for a mix matching the address passed in attribtutes tags if any
3659// - 2 if none found, getDeviceForInputSource() will:
3660// - 2.1 look for a mix matching the attributes source
3661// - 2.2 if none found, default to device selection by policy rules
3662// At this time, the corresponding output remote submix device is also connected
3663// and active playback use cases can be transferred to this mix if needed when reconnecting
3664// after AudioTracks are invalidated
3665//
3666// When playback starts, getOutputForAttr() will:
3667// - 1 look for a mix matching the address passed in attribtutes tags if any
3668// - 2 if none found, look for a mix matching the attributes usage
3669// - 3 if none found, default to device and output selection by policy rules.
3670
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003671status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003672{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3674 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003675 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003676 sp<HwModule> rSubmixModule;
3677 // examine each mix's route type
3678 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003679 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003680 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3681 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3682 ALOGE("Unsupported Policy Mix %zu of %zu: "
3683 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3684 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003685 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003686 break;
3687 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003688 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3689 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003690 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003691 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3692 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003693 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003694 rSubmixModule = mHwModules.getModuleFromName(
3695 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3696 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003697 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003698 i);
3699 res = INVALID_OPERATION;
3700 break;
3701 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003702 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003703
Eric Laurent97ac8712018-07-27 18:59:02 -07003704 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003705 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003706 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003707 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003708 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3709 } else {
3710 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3711 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003712 }
François Gaffie036e1e92015-03-19 10:16:24 +01003713
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003714 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003715 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003716 res = INVALID_OPERATION;
3717 break;
3718 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003719 audio_config_t outputConfig = mix.mFormat;
3720 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003721 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3722 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003723 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3724 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003725 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003726 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3727 audio_is_linear_pcm(outputConfig.format)
3728 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003729 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003730 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3731 audio_is_linear_pcm(inputConfig.format)
3732 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003733
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003734 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003735 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003736 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003737 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003738 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003739 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003740 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003741 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3742 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003743 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003744 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003745 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003746
3747 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3748 mix.mDeviceType, mix.mDeviceAddress,
3749 String8(), AUDIO_FORMAT_DEFAULT);
3750 if (device == nullptr) {
3751 res = INVALID_OPERATION;
3752 break;
3753 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003754
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003755 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003756 // First try to find an already opened output supporting the device
3757 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003758 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003759
Eric Laurentc529cf62020-04-17 18:19:10 -07003760 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003761 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003762 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003763 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003764 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003765 } else {
3766 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003767 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003768 }
3769 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003770 // If no output found, try to find a direct output profile supporting the device
3771 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3772 sp<HwModule> module = mHwModules[i];
3773 for (size_t j = 0;
3774 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3775 j++) {
3776 sp<IOProfile> profile = module->getOutputProfiles()[j];
3777 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3778 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3779 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003780 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003781 res = INVALID_OPERATION;
3782 } else {
3783 foundOutput = true;
3784 }
3785 }
3786 }
3787 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003788 if (res != NO_ERROR) {
3789 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003790 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003791 res = INVALID_OPERATION;
3792 break;
3793 } else if (!foundOutput) {
3794 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003795 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003796 res = INVALID_OPERATION;
3797 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003798 } else {
3799 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003800 }
Eric Laurentc722f302014-12-10 11:21:49 -08003801 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003802 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003803 if (res != NO_ERROR) {
3804 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003805 } else if (checkOutputs) {
3806 checkForDeviceAndOutputChanges();
3807 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003808 }
3809 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003810}
3811
3812status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3813{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003814 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003815 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003816 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003817 sp<HwModule> rSubmixModule;
3818 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003819 for (const auto& mix : mixes) {
3820 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003821
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003822 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003823 rSubmixModule = mHwModules.getModuleFromName(
3824 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3825 if (rSubmixModule == 0) {
3826 res = INVALID_OPERATION;
3827 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003828 }
3829 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003830
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003831 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003832
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003833 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003834 res = INVALID_OPERATION;
3835 continue;
3836 }
3837
Kevin Rocard04ed0462019-05-02 17:53:24 -07003838 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003839 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003840 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3841 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003842 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003843 AUDIO_FORMAT_DEFAULT);
3844 if (res != OK) {
3845 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003846 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003847 }
3848 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003849 }
jiabin5740f082019-08-19 15:08:30 -07003850 rSubmixModule->removeOutputProfile(address.c_str());
3851 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003852
Kevin Rocard153f92d2018-12-18 18:33:28 -08003853 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003854 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003855 res = INVALID_OPERATION;
3856 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003857 } else {
3858 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003859 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003860 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003861 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003862 if (res == NO_ERROR && checkOutputs) {
3863 checkForDeviceAndOutputChanges();
3864 updateCallAndOutputRouting();
3865 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003866 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003867}
3868
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003869status_t AudioPolicyManager::updatePolicyMix(
3870 const AudioMix& mix,
3871 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3872 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3873 if (res == NO_ERROR) {
3874 checkForDeviceAndOutputChanges();
3875 updateCallAndOutputRouting();
3876 }
3877 return res;
3878}
3879
Mikhail Naganov100f0122018-11-29 11:22:16 -08003880void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3881{
3882 size_t i = 0;
3883 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3884 for (const auto& fmt : mManualSurroundFormats) {
3885 if (i++ != 0) dst->append(", ");
3886 std::string sfmt;
3887 FormatConverter::toString(fmt, sfmt);
3888 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3889 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3890 }
3891}
3892
Eric Laurentc529cf62020-04-17 18:19:10 -07003893// Returns true if all devices types match the predicate and are supported by one HW module
3894bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003895 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003896 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003897 const char *context,
3898 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003899 for (size_t i = 0; i < devices.size(); i++) {
3900 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003901 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003902 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003903 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003904 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003905 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003906 return false;
3907 }
3908 }
3909 return true;
3910}
3911
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003912void AudioPolicyManager::changeOutputDevicesMuteState(
3913 const AudioDeviceTypeAddrVector& devices) {
3914 ALOGVV("%s() num devices %zu", __func__, devices.size());
3915
3916 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3917 getSoftwareOutputsForDevices(devices);
3918
3919 for (size_t i = 0; i < outputs.size(); i++) {
3920 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3921 DeviceVector prevDevices = outputDesc->devices();
3922 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3923 }
3924}
3925
3926std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3927 const AudioDeviceTypeAddrVector& devices) const
3928{
3929 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3930 DeviceVector deviceDescriptors;
3931 for (size_t j = 0; j < devices.size(); j++) {
3932 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3933 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3934 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3935 ALOGE("%s: device type %#x address %s not supported or not an output device",
3936 __func__, devices[j].mType, devices[j].getAddress());
3937 continue;
3938 }
3939 deviceDescriptors.add(desc);
3940 }
3941 for (size_t i = 0; i < mOutputs.size(); i++) {
3942 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3943 continue;
3944 }
3945 outputs.push_back(mOutputs.valueAt(i));
3946 }
3947 return outputs;
3948}
3949
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003950status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003951 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003952 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003953 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3954 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003955 }
3956 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003957 if (res != NO_ERROR) {
3958 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3959 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003960 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003961
3962 checkForDeviceAndOutputChanges();
3963 updateCallAndOutputRouting();
3964
3965 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003966}
3967
3968status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3969 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003970 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3971 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003972 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003973 __FUNCTION__, uid);
3974 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003975 }
3976
Eric Laurentc529cf62020-04-17 18:19:10 -07003977 checkForDeviceAndOutputChanges();
3978 updateCallAndOutputRouting();
3979
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003980 return res;
3981}
3982
Eric Laurent2517af32020-11-25 15:31:27 +01003983
jiabin0a488932020-08-07 17:32:40 -07003984status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3985 device_role_t role,
3986 const AudioDeviceTypeAddrVector &devices) {
3987 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3988 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003989
Eric Laurentc529cf62020-04-17 18:19:10 -07003990 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003991 return BAD_VALUE;
3992 }
jiabin0a488932020-08-07 17:32:40 -07003993 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003994 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003995 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3996 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003997 return status;
3998 }
3999
4000 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004001
4002 bool forceVolumeReeval = false;
4003 // FIXME: workaround for truncated touch sounds
4004 // to be removed when the problem is handled by system UI
4005 uint32_t delayMs = 0;
4006 if (strategy == mCommunnicationStrategy) {
4007 forceVolumeReeval = true;
4008 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4009 updateInputRouting();
4010 }
4011 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004012
4013 return NO_ERROR;
4014}
4015
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004016void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4017 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004018{
4019 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004020 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004021 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004022 // Only apply special touch sound delay once
4023 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004024 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004025 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004026 for (size_t i = 0; i < mOutputs.size(); i++) {
4027 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4028 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004029 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4030 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004031 // As done in setDeviceConnectionState, we could also fix default device issue by
4032 // preventing the force re-routing in case of default dev that distinguishes on address.
4033 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004034 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004035 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4036 // If the device is using preferred mixer attributes, the output need to reopen
4037 // with default configuration when the new selected devices are different from
4038 // current routing devices.
4039 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4040 continue;
4041 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304042
4043 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4044 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004045 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004046 // Only apply special touch sound delay once
4047 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004048 }
4049 if (forceVolumeReeval && !newDevices.isEmpty()) {
4050 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4051 }
4052 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004053 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004054 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004055}
4056
Eric Laurent2517af32020-11-25 15:31:27 +01004057void AudioPolicyManager::updateInputRouting() {
4058 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304059 // Skip for hotword recording as the input device switch
4060 // is handled within sound trigger HAL
4061 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4062 continue;
4063 }
Eric Laurent2517af32020-11-25 15:31:27 +01004064 auto newDevice = getNewInputDevice(activeDesc);
4065 // Force new input selection if the new device can not be reached via current input
4066 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4067 setInputDevice(activeDesc->mIoHandle, newDevice);
4068 } else {
4069 closeInput(activeDesc->mIoHandle);
4070 }
4071 }
4072}
4073
Paul Wang5d7cdb52022-11-22 09:45:06 +00004074status_t
4075AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4076 device_role_t role,
4077 const AudioDeviceTypeAddrVector &devices) {
4078 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4079 dumpAudioDeviceTypeAddrVector(devices).c_str());
4080
Eric Laurent78fedbf2023-03-09 14:40:44 +01004081 if (!areAllDevicesSupported(
4082 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004083 return BAD_VALUE;
4084 }
4085 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4086 if (status != NO_ERROR) {
4087 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4088 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4089 return status;
4090 }
4091
4092 checkForDeviceAndOutputChanges();
4093
4094 bool forceVolumeReeval = false;
4095 // TODO(b/263479999): workaround for truncated touch sounds
4096 // to be removed when the problem is handled by system UI
4097 uint32_t delayMs = 0;
4098 if (strategy == mCommunnicationStrategy) {
4099 forceVolumeReeval = true;
4100 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4101 updateInputRouting();
4102 }
4103 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4104
4105 return NO_ERROR;
4106}
4107
4108status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4109 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004110{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004111 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004112
Paul Wang5d7cdb52022-11-22 09:45:06 +00004113 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004114 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004115 ALOGW_IF(status != NAME_NOT_FOUND,
4116 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004117 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004118 return status;
4119 }
4120
4121 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004122
4123 bool forceVolumeReeval = false;
4124 // FIXME: workaround for truncated touch sounds
4125 // to be removed when the problem is handled by system UI
4126 uint32_t delayMs = 0;
4127 if (strategy == mCommunnicationStrategy) {
4128 forceVolumeReeval = true;
4129 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4130 updateInputRouting();
4131 }
4132 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004133
4134 return NO_ERROR;
4135}
4136
jiabin0a488932020-08-07 17:32:40 -07004137status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4138 device_role_t role,
4139 AudioDeviceTypeAddrVector &devices) {
4140 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004141}
4142
Jiabin Huang3b98d322020-09-03 17:54:16 +00004143status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4144 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4145 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4146 dumpAudioDeviceTypeAddrVector(devices).c_str());
4147
Mikhail Naganov55773032020-10-01 15:08:13 -07004148 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004149 return BAD_VALUE;
4150 }
4151 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4152 ALOGW_IF(status != NO_ERROR,
4153 "Engine could not set preferred devices %s for audio source %d role %d",
4154 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4155
4156 return status;
4157}
4158
4159status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4160 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4161 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4162 dumpAudioDeviceTypeAddrVector(devices).c_str());
4163
Mikhail Naganov55773032020-10-01 15:08:13 -07004164 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004165 return BAD_VALUE;
4166 }
4167 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4168 ALOGW_IF(status != NO_ERROR,
4169 "Engine could not add preferred devices %s for audio source %d role %d",
4170 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4171
Eric Laurent2517af32020-11-25 15:31:27 +01004172 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004173 return status;
4174}
4175
4176status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4177 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4178{
4179 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4180 dumpAudioDeviceTypeAddrVector(devices).c_str());
4181
Eric Laurent78fedbf2023-03-09 14:40:44 +01004182 if (!areAllDevicesSupported(
4183 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004184 return BAD_VALUE;
4185 }
4186
4187 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4188 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004189 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004190 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004191 if (status == NO_ERROR) {
4192 updateInputRouting();
4193 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004194 return status;
4195}
4196
4197status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4198 device_role_t role) {
4199 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4200
4201 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004202 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004203 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004204 if (status == NO_ERROR) {
4205 updateInputRouting();
4206 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004207 return status;
4208}
4209
4210status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4211 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4212 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4213}
4214
Oscar Azucena90e77632019-11-27 17:12:28 -08004215status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004216 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004217 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004218 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4219 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004220 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004221 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4222 if (status != NO_ERROR) {
4223 ALOGE("%s() could not set device affinity for userId %d",
4224 __FUNCTION__, userId);
4225 return status;
4226 }
4227
4228 // reevaluate outputs for all devices
4229 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004230 changeOutputDevicesMuteState(devices);
4231 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4232 true /* skipDelays */);
4233 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004234
4235 return NO_ERROR;
4236}
4237
4238status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004239 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004240 AudioDeviceTypeAddrVector devices;
4241 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004242 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4243 if (status != NO_ERROR) {
4244 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4245 __FUNCTION__, userId);
4246 return status;
4247 }
4248
4249 // reevaluate outputs for all devices
4250 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004251 changeOutputDevicesMuteState(devices);
4252 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4253 true /* skipDelays */);
4254 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004255
4256 return NO_ERROR;
4257}
4258
Andy Hungc29d82b2018-10-05 12:23:17 -07004259void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004260{
Andy Hungc29d82b2018-10-05 12:23:17 -07004261 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004262 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004263 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004264 std::string stateLiteral;
4265 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004266 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004267 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4268 "communications", "media", "record", "dock", "system",
4269 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4270 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4271 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004272 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4273 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4274 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4275 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4276 dst->append(" (MANUAL: ");
4277 dumpManualSurroundFormats(dst);
4278 dst->append(")");
4279 }
4280 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004281 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004282 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4283 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004284 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004285 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004286
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004287 dst->append("\n");
4288 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4289 dst->append("\n");
4290 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004291 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004292 mOutputs.dump(dst);
4293 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004294 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004295 mAudioPatches.dump(dst);
4296 mPolicyMixes.dump(dst);
4297 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004298
Kevin Rocardb99cc752019-03-21 20:52:24 -07004299 dst->appendFormat(" AllowedCapturePolicies:\n");
4300 for (auto& policy : mAllowedCapturePolicies) {
4301 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4302 }
4303
jiabina84c3d32022-12-02 18:59:55 +00004304 dst->appendFormat(" Preferred mixer audio configuration:\n");
4305 for (const auto it : mPreferredMixerAttrInfos) {
4306 dst->appendFormat(" - device port id: %d\n", it.first);
4307 for (const auto preferredMixerInfoIt : it.second) {
4308 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4309 preferredMixerInfoIt.second->dump(dst);
4310 }
4311 }
4312
François Gaffiec005e562018-11-06 15:04:49 +01004313 dst->appendFormat("\nPolicy Engine dump:\n");
4314 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004315}
4316
4317status_t AudioPolicyManager::dump(int fd)
4318{
4319 String8 result;
4320 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004321 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004322 return NO_ERROR;
4323}
4324
Kevin Rocardb99cc752019-03-21 20:52:24 -07004325status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4326{
4327 mAllowedCapturePolicies[uid] = capturePolicy;
4328 return NO_ERROR;
4329}
4330
Eric Laurente552edb2014-03-10 17:42:56 -07004331// This function checks for the parameters which can be offloaded.
4332// This can be enhanced depending on the capability of the DSP and policy
4333// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004334audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004335{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004336 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004337 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004338 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004339 offloadInfo.format,
4340 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4341 offloadInfo.has_video);
4342
jiabin2b9d5a12021-12-10 01:06:29 +00004343 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004344 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004345 }
4346
4347 // See if there is a profile to support this.
4348 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004349 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004350 offloadInfo.sample_rate,
4351 offloadInfo.format,
4352 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004353 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4354 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004355 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4356 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4357 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004358 if (profile == nullptr) {
4359 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4360 }
4361 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4362 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4363 }
4364 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004365}
4366
Michael Chana94fbb22018-04-24 14:31:19 +10004367bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4368 const audio_attributes_t& attributes) {
4369 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004370 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004371 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4372 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004373 config.sample_rate,
4374 config.format,
4375 config.channel_mask,
4376 output_flags,
4377 true /* directOnly */);
4378 ALOGV("%s() profile %sfound with name: %s, "
4379 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4380 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004381 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004382 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004383
4384 // also try the MSD module if compatible profile not found
4385 if (profile == nullptr) {
4386 profile = getMsdProfileForOutput(outputDevices,
4387 config.sample_rate,
4388 config.format,
4389 config.channel_mask,
4390 output_flags,
4391 true /* directOnly */);
4392 ALOGV("%s() MSD profile %sfound with name: %s, "
4393 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4394 __FUNCTION__, profile != 0 ? "" : "NOT ",
4395 (profile != 0 ? profile->getTagName().c_str() : "null"),
4396 config.sample_rate, config.format, config.channel_mask, output_flags);
4397 }
4398 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004399}
4400
jiabin2b9d5a12021-12-10 01:06:29 +00004401bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4402 bool durationIgnored) {
4403 if (mMasterMono) {
4404 return false; // no offloading if mono is set.
4405 }
4406
4407 // Check if offload has been disabled
4408 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4409 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4410 return false;
4411 }
4412
4413 // Check if stream type is music, then only allow offload as of now.
4414 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4415 {
4416 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4417 return false;
4418 }
4419
4420 //TODO: enable audio offloading with video when ready
4421 const bool allowOffloadWithVideo =
4422 property_get_bool("audio.offload.video", false /* default_value */);
4423 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4424 ALOGV("%s: has_video == true, returning false", __func__);
4425 return false;
4426 }
4427
4428 //If duration is less than minimum value defined in property, return false
4429 const int min_duration_secs = property_get_int32(
4430 "audio.offload.min.duration.secs", -1 /* default_value */);
4431 if (!durationIgnored) {
4432 if (min_duration_secs >= 0) {
4433 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4434 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4435 __func__, min_duration_secs);
4436 return false;
4437 }
4438 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4439 ALOGV("%s: Offload denied by duration < default min(=%u)",
4440 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4441 return false;
4442 }
4443 }
4444
4445 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4446 // creating an offloaded track and tearing it down immediately after start when audioflinger
4447 // detects there is an active non offloadable effect.
4448 // FIXME: We should check the audio session here but we do not have it in this context.
4449 // This may prevent offloading in rare situations where effects are left active by apps
4450 // in the background.
4451 if (mEffects.isNonOffloadableEffectEnabled()) {
4452 return false;
4453 }
4454
4455 return true;
4456}
4457
4458audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4459 const audio_config_t *config) {
4460 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4461 offloadInfo.format = config->format;
4462 offloadInfo.sample_rate = config->sample_rate;
4463 offloadInfo.channel_mask = config->channel_mask;
4464 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4465 offloadInfo.has_video = false;
4466 offloadInfo.is_streaming = false;
4467 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4468
4469 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4470 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4471 audio_flags_to_audio_output_flags(attr->flags, &flags);
4472 // only retain flags that will drive compressed offload or passthrough
4473 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4474 if (offloadPossible) {
4475 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4476 }
4477 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4478
Dorin Drimusfae3c642022-03-17 18:36:30 +01004479 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004480 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004481 DeviceVector outputDevices = engineOutputDevices;
4482 // the MSD module checks for different conditions and output devices
4483 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4484 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4485 continue;
4486 }
4487 outputDevices = getMsdAudioOutDevices();
4488 }
jiabin2b9d5a12021-12-10 01:06:29 +00004489 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004490 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004491 config->sample_rate, nullptr /*updatedSamplingRate*/,
4492 config->format, nullptr /*updatedFormat*/,
4493 config->channel_mask, nullptr /*updatedChannelMask*/,
4494 flags)) {
4495 continue;
4496 }
4497 // reject profiles not corresponding to a device currently available
4498 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4499 continue;
4500 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004501 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4502 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004503 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004504 != AUDIO_DIRECT_NOT_SUPPORTED) {
4505 // Already reports offload gapless supported. No need to report offload support.
4506 continue;
4507 }
4508 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4509 != AUDIO_OUTPUT_FLAG_NONE) {
4510 // If offload gapless is reported, no need to report offload support.
4511 directMode = (audio_direct_mode_t) ((directMode &
4512 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4513 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4514 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004515 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004516 }
4517 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004518 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004519 }
4520 }
4521 }
4522 return directMode;
4523}
4524
Dorin Drimusf2196d82022-01-03 12:11:18 +01004525status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4526 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004527 if (mEffects.isNonOffloadableEffectEnabled()) {
4528 return OK;
4529 }
jiabinf1c73972022-04-14 16:28:52 -07004530 DeviceVector devices;
4531 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004532 if (status != OK) {
4533 return status;
4534 }
4535 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4536 if (devices.empty()) {
4537 return OK; // no output devices for the attributes
4538 }
jiabinf1c73972022-04-14 16:28:52 -07004539 return getProfilesForDevices(devices, audioProfilesVector,
4540 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004541}
4542
jiabina84c3d32022-12-02 18:59:55 +00004543status_t AudioPolicyManager::getSupportedMixerAttributes(
4544 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4545 ALOGV("%s, portId=%d", __func__, portId);
4546 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4547 if (deviceDescriptor == nullptr) {
4548 ALOGE("%s the requested device is currently unavailable", __func__);
4549 return BAD_VALUE;
4550 }
jiabin96daffc2023-05-11 17:51:55 +00004551 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4552 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4553 deviceDescriptor->type());
4554 return BAD_VALUE;
4555 }
jiabina84c3d32022-12-02 18:59:55 +00004556 for (const auto& hwModule : mHwModules) {
4557 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4558 if (curProfile->supportsDevice(deviceDescriptor)) {
4559 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4560 }
4561 }
4562 }
4563 return NO_ERROR;
4564}
4565
4566status_t AudioPolicyManager::setPreferredMixerAttributes(
4567 const audio_attributes_t *attr,
4568 audio_port_handle_t portId,
4569 uid_t uid,
4570 const audio_mixer_attributes_t *mixerAttributes) {
4571 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4572 "mixerBehavior=%d}, uid=%d, portId=%u",
4573 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4574 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4575 mixerAttributes->mixer_behavior, uid, portId);
4576 if (attr->usage != AUDIO_USAGE_MEDIA) {
4577 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4578 return BAD_VALUE;
4579 }
4580 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4581 if (deviceDescriptor == nullptr) {
4582 ALOGE("%s the requested device is currently unavailable", __func__);
4583 return BAD_VALUE;
4584 }
4585 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4586 ALOGE("%s(%d), type=%d, is not a usb output device",
4587 __func__, portId, deviceDescriptor->type());
4588 return BAD_VALUE;
4589 }
4590
4591 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4592 audio_flags_to_audio_output_flags(attr->flags, &flags);
4593 flags = (audio_output_flags_t) (flags |
4594 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4595 sp<IOProfile> profile = nullptr;
4596 DeviceVector devices(deviceDescriptor);
4597 for (const auto& hwModule : mHwModules) {
4598 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4599 if (curProfile->hasDynamicAudioProfile()
4600 && curProfile->isCompatibleProfile(devices,
4601 mixerAttributes->config.sample_rate,
4602 nullptr /*updatedSamplingRate*/,
4603 mixerAttributes->config.format,
4604 nullptr /*updatedFormat*/,
4605 mixerAttributes->config.channel_mask,
4606 nullptr /*updatedChannelMask*/,
4607 flags,
4608 false /*exactMatchRequiredForInputFlags*/)) {
4609 profile = curProfile;
4610 break;
4611 }
4612 }
4613 }
4614 if (profile == nullptr) {
4615 ALOGE("%s, there is no compatible profile found", __func__);
4616 return BAD_VALUE;
4617 }
4618
4619 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4620 sp<PreferredMixerAttributesInfo>::make(
4621 uid, portId, profile, flags, *mixerAttributes);
4622 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4623 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4624
4625 // If 1) there is any client from the preferred mixer configuration owner that is currently
4626 // active and matches the strategy and 2) current output is on the preferred device and the
4627 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4628 // configuration.
4629 std::vector<audio_io_handle_t> outputsToReopen;
4630 for (size_t i = 0; i < mOutputs.size(); i++) {
4631 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004632 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4633 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4634 output->mUsePreferredMixerAttributes = true;
4635 } else {
4636 for (const auto &client: output->getActiveClients()) {
4637 if (client->uid() == uid && client->strategy() == strategy) {
4638 client->setIsInvalid();
4639 outputsToReopen.push_back(output->mIoHandle);
4640 }
jiabina84c3d32022-12-02 18:59:55 +00004641 }
4642 }
4643 }
4644 }
4645 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4646 config.sample_rate = mixerAttributes->config.sample_rate;
4647 config.channel_mask = mixerAttributes->config.channel_mask;
4648 config.format = mixerAttributes->config.format;
4649 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004650 sp<SwAudioOutputDescriptor> desc =
4651 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4652 if (desc == nullptr) {
4653 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4654 continue;
4655 }
4656 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004657 }
4658
4659 return NO_ERROR;
4660}
4661
4662sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004663 audio_port_handle_t devicePortId,
4664 product_strategy_t strategy,
4665 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004666 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4667 if (it == mPreferredMixerAttrInfos.end()) {
4668 return nullptr;
4669 }
jiabind9a58d32023-06-01 17:57:30 +00004670 if (activeBitPerfectPreferred) {
4671 for (auto [strategy, info] : it->second) {
4672 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4673 && info->getActiveClientCount() != 0) {
4674 return info;
4675 }
4676 }
jiabina84c3d32022-12-02 18:59:55 +00004677 }
jiabind9a58d32023-06-01 17:57:30 +00004678 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4679 return strategyMatchedMixerAttrInfoIt == it->second.end()
4680 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004681}
4682
4683status_t AudioPolicyManager::getPreferredMixerAttributes(
4684 const audio_attributes_t *attr,
4685 audio_port_handle_t portId,
4686 audio_mixer_attributes_t* mixerAttributes) {
4687 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4688 portId, mEngine->getProductStrategyForAttributes(*attr));
4689 if (info == nullptr) {
4690 return NAME_NOT_FOUND;
4691 }
4692 *mixerAttributes = info->getMixerAttributes();
4693 return NO_ERROR;
4694}
4695
4696status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4697 audio_port_handle_t portId,
4698 uid_t uid) {
4699 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4700 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4701 if (preferredMixerAttrInfo == nullptr) {
4702 return NAME_NOT_FOUND;
4703 }
4704 if (preferredMixerAttrInfo->getUid() != uid) {
4705 ALOGE("%s, requested uid=%d, owned uid=%d",
4706 __func__, uid, preferredMixerAttrInfo->getUid());
4707 return PERMISSION_DENIED;
4708 }
4709 mPreferredMixerAttrInfos[portId].erase(strategy);
4710 if (mPreferredMixerAttrInfos[portId].empty()) {
4711 mPreferredMixerAttrInfos.erase(portId);
4712 }
4713
4714 // Reconfig existing output
4715 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4716 for (size_t i = 0; i < mOutputs.size(); i++) {
4717 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4718 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4719 }
4720 }
4721 for (const auto output : potentialOutputsToReopen) {
4722 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4723 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4724 preferredMixerAttrInfo->getFlags())) {
4725 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4726 }
4727 }
4728 return NO_ERROR;
4729}
4730
Eric Laurent6a94d692014-05-20 11:18:06 -07004731status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4732 audio_port_type_t type,
4733 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004734 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004735 unsigned int *generation)
4736{
jiabin19cdba52020-11-24 11:28:58 -08004737 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4738 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 return BAD_VALUE;
4740 }
4741 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004742 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 *num_ports = 0;
4744 }
4745
4746 size_t portsWritten = 0;
4747 size_t portsMax = *num_ports;
4748 *num_ports = 0;
4749 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004750 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4751 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004752 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004753 for (const auto& dev : mAvailableOutputDevices) {
4754 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004755 continue;
4756 }
4757 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004758 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004759 }
4760 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004761 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004762 }
4763 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004764 for (const auto& dev : mAvailableInputDevices) {
4765 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004766 continue;
4767 }
4768 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004769 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004770 }
4771 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004772 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004773 }
4774 }
4775 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4776 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4777 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4778 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4779 }
4780 *num_ports += mInputs.size();
4781 }
4782 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004783 size_t numOutputs = 0;
4784 for (size_t i = 0; i < mOutputs.size(); i++) {
4785 if (!mOutputs[i]->isDuplicated()) {
4786 numOutputs++;
4787 if (portsWritten < portsMax) {
4788 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4789 }
4790 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004791 }
Eric Laurent84c70242014-06-23 08:46:27 -07004792 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 }
4794 }
jiabina84c3d32022-12-02 18:59:55 +00004795
Eric Laurent6a94d692014-05-20 11:18:06 -07004796 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004797 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 return NO_ERROR;
4799}
4800
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004801status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4802 std::vector<media::AudioPortFw>* _aidl_return) {
4803 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4804 audio_port_v7 port;
4805 dev->toAudioPort(&port);
4806 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4807 _aidl_return->push_back(std::move(aidlPort));
4808 return OK;
4809 };
4810
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004811 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004812 for (const auto& dev : module->getDeclaredDevices()) {
4813 if (role == media::AudioPortRole::NONE ||
4814 ((role == media::AudioPortRole::SOURCE)
4815 == audio_is_input_device(dev->type()))) {
4816 RETURN_STATUS_IF_ERROR(pushPort(dev));
4817 }
4818 }
4819 }
4820 return OK;
4821}
4822
jiabin19cdba52020-11-24 11:28:58 -08004823status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004824{
Eric Laurent99fcae42018-05-17 16:59:18 -07004825 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4826 return BAD_VALUE;
4827 }
4828 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4829 if (dev != 0) {
4830 dev->toAudioPort(port);
4831 return NO_ERROR;
4832 }
4833 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4834 if (dev != 0) {
4835 dev->toAudioPort(port);
4836 return NO_ERROR;
4837 }
4838 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4839 if (out != 0) {
4840 out->toAudioPort(port);
4841 return NO_ERROR;
4842 }
4843 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4844 if (in != 0) {
4845 in->toAudioPort(port);
4846 return NO_ERROR;
4847 }
4848 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004849}
4850
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004851status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4852 audio_patch_handle_t *handle,
4853 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004854{
François Gaffieafd4cea2019-11-18 15:50:22 +01004855 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 if (handle == NULL || patch == NULL) {
4857 return BAD_VALUE;
4858 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004859 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004860 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004861 return BAD_VALUE;
4862 }
4863 // only one source per audio patch supported for now
4864 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 return INVALID_OPERATION;
4866 }
Eric Laurent874c42872014-08-08 15:13:39 -07004867 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004868 return INVALID_OPERATION;
4869 }
Eric Laurent874c42872014-08-08 15:13:39 -07004870 for (size_t i = 0; i < patch->num_sinks; i++) {
4871 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4872 return INVALID_OPERATION;
4873 }
4874 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004875
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004876 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4877 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4878 if (srcDevice == nullptr || sinkDevice == nullptr) {
4879 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4880 return BAD_VALUE;
4881 }
4882 ALOGV("%s between source %s and sink %s", __func__,
4883 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4884 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4885 // Default attributes, default volume priority, not to infer with non raw audio patches.
4886 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4887 const struct audio_port_config *source = &patch->sources[0];
4888 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004889 new SourceClientDescriptor(
4890 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4891 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4892 true);
4893 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004894
4895 status_t status =
4896 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4897
4898 if (status != NO_ERROR) {
4899 return INVALID_OPERATION;
4900 }
4901 mAudioSources.add(portId, sourceDesc);
4902 return NO_ERROR;
4903}
4904
4905status_t AudioPolicyManager::connectAudioSourceToSink(
4906 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4907 const struct audio_patch *patch,
4908 audio_patch_handle_t &handle,
4909 uid_t uid, uint32_t delayMs)
4910{
4911 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4912 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4913 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4914 return INVALID_OPERATION;
4915 }
4916 sourceDesc->connect(handle, sinkDevice);
4917 if (isMsdPatch(handle)) {
4918 return NO_ERROR;
4919 }
4920 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4921 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4922 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4923 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4924 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4925 goto FailurePatchAdded;
4926 }
4927 status = swOutput->start();
4928 if (status != NO_ERROR) {
4929 goto FailureSourceAdded;
4930 }
4931 swOutput->addClient(sourceDesc);
4932 status = startSource(swOutput, sourceDesc, &delayMs);
4933 if (status != NO_ERROR) {
4934 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4935 goto FailureSourceActive;
4936 }
4937 if (delayMs != 0) {
4938 usleep(delayMs * 1000);
4939 }
4940 return NO_ERROR;
4941
4942FailureSourceActive:
4943 swOutput->stop();
4944 releaseOutput(sourceDesc->portId());
4945FailureSourceAdded:
4946 sourceDesc->setSwOutput(nullptr);
4947FailurePatchAdded:
4948 releaseAudioPatchInternal(handle);
4949 return INVALID_OPERATION;
4950}
4951
4952status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4953 audio_patch_handle_t *handle,
4954 uid_t uid, uint32_t delayMs,
4955 const sp<SourceClientDescriptor>& sourceDesc)
4956{
4957 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 sp<AudioPatch> patchDesc;
4959 ssize_t index = mAudioPatches.indexOfKey(*handle);
4960
François Gaffieafd4cea2019-11-18 15:50:22 +01004961 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4962 patch->sources[0].role,
4963 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004964#if LOG_NDEBUG == 0
4965 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004966 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4967 patch->sinks[i].role,
4968 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004969 }
4970#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004971
4972 if (index >= 0) {
4973 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004974 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4975 __func__, mUidCached, patchDesc->getUid(), uid);
4976 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 return INVALID_OPERATION;
4978 }
4979 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004980 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004981 }
4982
4983 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004984 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004985 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004986 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004987 return BAD_VALUE;
4988 }
Eric Laurent84c70242014-06-23 08:46:27 -07004989 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4990 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004991 if (patchDesc != 0) {
4992 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004993 ALOGV("%s source id differs for patch current id %d new id %d",
4994 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 return BAD_VALUE;
4996 }
4997 }
Eric Laurent874c42872014-08-08 15:13:39 -07004998 DeviceVector devices;
4999 for (size_t i = 0; i < patch->num_sinks; i++) {
5000 // Only support mix to devices connection
5001 // TODO add support for mix to mix connection
5002 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005003 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005004 return INVALID_OPERATION;
5005 }
5006 sp<DeviceDescriptor> devDesc =
5007 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5008 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005009 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005010 return BAD_VALUE;
5011 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005012
François Gaffie11d30102018-11-02 16:09:09 +01005013 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07005014 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01005015 NULL, // updatedSamplingRate
5016 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005017 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01005018 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005019 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01005020 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005021 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005022 return INVALID_OPERATION;
5023 }
5024 devices.add(devDesc);
5025 }
5026 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 return INVALID_OPERATION;
5028 }
Eric Laurent874c42872014-08-08 15:13:39 -07005029
Eric Laurent6a94d692014-05-20 11:18:06 -07005030 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005031 ALOGV("%s setting device %s on output %d",
5032 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305033 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005034 index = mAudioPatches.indexOfKey(*handle);
5035 if (index >= 0) {
5036 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005037 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005038 }
5039 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005040 patchDesc->setUid(uid);
5041 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005043 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005044 return INVALID_OPERATION;
5045 }
5046 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5047 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5048 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005049 // only one sink supported when connecting an input device to a mix
5050 if (patch->num_sinks > 1) {
5051 return INVALID_OPERATION;
5052 }
François Gaffie53615e22015-03-19 09:24:12 +01005053 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005054 if (inputDesc == NULL) {
5055 return BAD_VALUE;
5056 }
5057 if (patchDesc != 0) {
5058 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5059 return BAD_VALUE;
5060 }
5061 }
François Gaffie11d30102018-11-02 16:09:09 +01005062 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005063 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005064 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 return BAD_VALUE;
5066 }
5067
François Gaffie11d30102018-11-02 16:09:09 +01005068 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005069 patch->sinks[0].sample_rate,
5070 NULL, /*updatedSampleRate*/
5071 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005072 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005073 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005074 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005075 // FIXME for the parameter type,
5076 // and the NONE
5077 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005078 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 return INVALID_OPERATION;
5080 }
5081 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005082 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005083 device->toString().c_str(), inputDesc->mIoHandle);
5084 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005085 index = mAudioPatches.indexOfKey(*handle);
5086 if (index >= 0) {
5087 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005088 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005089 }
5090 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005091 patchDesc->setUid(uid);
5092 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005093 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005094 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005095 return INVALID_OPERATION;
5096 }
5097 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5098 // device to device connection
5099 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005100 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005101 return BAD_VALUE;
5102 }
5103 }
François Gaffie11d30102018-11-02 16:09:09 +01005104 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005105 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005106 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005107 return BAD_VALUE;
5108 }
Eric Laurent874c42872014-08-08 15:13:39 -07005109
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 //update source and sink with our own data as the data passed in the patch may
5111 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005112 PatchBuilder patchBuilder;
5113 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005114
5115 // if first sink is to MSD, establish single MSD patch
5116 if (getMsdAudioOutDevices().contains(
5117 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5118 ALOGV("%s patching to MSD", __FUNCTION__);
5119 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5120 goto installPatch;
5121 }
5122
François Gaffieafd4cea2019-11-18 15:50:22 +01005123 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5124 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005125
Eric Laurent874c42872014-08-08 15:13:39 -07005126 for (size_t i = 0; i < patch->num_sinks; i++) {
5127 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005128 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005129 return INVALID_OPERATION;
5130 }
François Gaffie11d30102018-11-02 16:09:09 +01005131 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005132 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005133 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005134 return BAD_VALUE;
5135 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005136 audio_port_config sinkPortConfig = {};
5137 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5138 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005139
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005140 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5141 // volume management purpose (tracking activity)
5142 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5143 // in config XML to reach the sink so that is can be declared as available.
5144 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005145 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005146 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005147 // take care of dynamic routing for SwOutput selection,
5148 audio_attributes_t attributes = sourceDesc->attributes();
5149 audio_stream_type_t stream = sourceDesc->stream();
5150 audio_attributes_t resultAttr;
5151 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5152 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005153 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5154 config.channel_mask =
5155 (audio_channel_mask_get_representation(sourceMask)
5156 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5157 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005158 config.format = sourceDesc->config().format;
5159 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5160 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5161 bool isRequestedDeviceForExclusiveUse = false;
5162 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005163 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005164 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005165 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5166 &stream, sourceDesc->uid(), &config, &flags,
5167 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005168 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005169 if (output == AUDIO_IO_HANDLE_NONE) {
5170 ALOGV("%s no output for device %s",
5171 __FUNCTION__, sinkDevice->toString().c_str());
5172 return INVALID_OPERATION;
5173 }
5174 outputDesc = mOutputs.valueFor(output);
5175 if (outputDesc->isDuplicated()) {
5176 ALOGE("%s output is duplicated", __func__);
5177 return INVALID_OPERATION;
5178 }
François Gaffie7e39df22022-04-26 12:48:49 +02005179 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5180 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005181 } else {
5182 // Same for "raw patches" aka created from createAudioPatch API
5183 SortedVector<audio_io_handle_t> outputs =
5184 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5185 // if the sink device is reachable via an opened output stream, request to
5186 // go via this output stream by adding a second source to the patch
5187 // description
5188 output = selectOutput(outputs);
5189 if (output == AUDIO_IO_HANDLE_NONE) {
5190 ALOGE("%s no output available for internal patch sink", __func__);
5191 return INVALID_OPERATION;
5192 }
5193 outputDesc = mOutputs.valueFor(output);
5194 if (outputDesc->isDuplicated()) {
5195 ALOGV("%s output for device %s is duplicated",
5196 __func__, sinkDevice->toString().c_str());
5197 return INVALID_OPERATION;
5198 }
François Gaffie7e39df22022-04-26 12:48:49 +02005199 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005200 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005201 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005202 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005203 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005204 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005205 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5206 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005207 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5208 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005209 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005210 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005211 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005212 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005213 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005214 return INVALID_OPERATION;
5215 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005216 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005217 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005218 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005219 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005220 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005221 srcMixPortConfig.ext.mix.usecase.stream =
5222 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005223 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5224 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005225 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005226 }
Eric Laurent83b88082014-06-20 18:31:16 -07005227 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005228 }
5229 // TODO: check from routing capabilities in config file and other conflicting patches
5230
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005231installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005232 status_t status = installPatch(
5233 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005234 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005235 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 return INVALID_OPERATION;
5237 }
5238 } else {
5239 return BAD_VALUE;
5240 }
5241 } else {
5242 return BAD_VALUE;
5243 }
5244 return NO_ERROR;
5245}
5246
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005247status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005248{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005249 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005250 ssize_t index = mAudioPatches.indexOfKey(handle);
5251
5252 if (index < 0) {
5253 return BAD_VALUE;
5254 }
5255 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005256 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5257 __func__, mUidCached, patchDesc->getUid(), uid);
5258 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 return INVALID_OPERATION;
5260 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005261 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5262 for (size_t i = 0; i < mAudioSources.size(); i++) {
5263 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5264 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5265 portId = sourceDesc->portId();
5266 break;
5267 }
5268 }
5269 return portId != AUDIO_PORT_HANDLE_NONE ?
5270 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005271}
Eric Laurent6a94d692014-05-20 11:18:06 -07005272
François Gaffieafd4cea2019-11-18 15:50:22 +01005273status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005274 uint32_t delayMs,
5275 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005276{
5277 ALOGV("%s patch %d", __func__, handle);
5278 if (mAudioPatches.indexOfKey(handle) < 0) {
5279 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5280 return BAD_VALUE;
5281 }
5282 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005284 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005286 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005287 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005288 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 return BAD_VALUE;
5290 }
5291
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305292 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005293 getNewOutputDevices(outputDesc, true /*fromCache*/),
5294 true,
5295 0,
5296 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5298 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005299 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005301 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005302 return BAD_VALUE;
5303 }
5304 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005305 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005306 true,
5307 NULL);
5308 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005309 status_t status =
5310 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5311 ALOGV("%s patch panel returned %d patchHandle %d",
5312 __func__, status, patchDesc->getAfHandle());
5313 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005315 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005316 // SW or HW Bridge
5317 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5318 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005319 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005320 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5321 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5322 outputDesc = sourceDesc->swOutput().promote();
5323 }
5324 if (outputDesc == nullptr) {
5325 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5326 // releaseOutput has already called closeOutput in case of direct output
5327 return NO_ERROR;
5328 }
François Gaffie7e39df22022-04-26 12:48:49 +02005329 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005330 // While using a HwBridge, force reconsidering device only if not reusing an existing
5331 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005332 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005333 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5334 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5335 // Reconsider device only for cases:
5336 // 1 / Active Output
5337 // 2 / Inactive Output previously hosting HwBridge
5338 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5339 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5340 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305341 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005342 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5343 outputDesc->devices(),
5344 force,
5345 0,
5346 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005347 } else {
5348 return BAD_VALUE;
5349 }
5350 } else {
5351 return BAD_VALUE;
5352 }
5353 return NO_ERROR;
5354}
5355
5356status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5357 struct audio_patch *patches,
5358 unsigned int *generation)
5359{
François Gaffie53615e22015-03-19 09:24:12 +01005360 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005361 return BAD_VALUE;
5362 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005363 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005364 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005365}
5366
Eric Laurente1715a42014-05-20 11:30:42 -07005367status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005368{
Eric Laurente1715a42014-05-20 11:30:42 -07005369 ALOGV("setAudioPortConfig()");
5370
5371 if (config == NULL) {
5372 return BAD_VALUE;
5373 }
5374 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5375 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005376 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5377 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005378 }
5379
Eric Laurenta121f902014-06-03 13:32:54 -07005380 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005381 if (config->type == AUDIO_PORT_TYPE_MIX) {
5382 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005383 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005384 if (outputDesc == NULL) {
5385 return BAD_VALUE;
5386 }
Eric Laurent84c70242014-06-23 08:46:27 -07005387 ALOG_ASSERT(!outputDesc->isDuplicated(),
5388 "setAudioPortConfig() called on duplicated output %d",
5389 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005390 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005391 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005392 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005393 if (inputDesc == NULL) {
5394 return BAD_VALUE;
5395 }
Eric Laurenta121f902014-06-03 13:32:54 -07005396 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005397 } else {
5398 return BAD_VALUE;
5399 }
5400 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5401 sp<DeviceDescriptor> deviceDesc;
5402 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5403 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5404 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5405 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5406 } else {
5407 return BAD_VALUE;
5408 }
5409 if (deviceDesc == NULL) {
5410 return BAD_VALUE;
5411 }
Eric Laurenta121f902014-06-03 13:32:54 -07005412 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005413 } else {
5414 return BAD_VALUE;
5415 }
5416
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005417 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005418 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5419 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005420 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005421 audioPortConfig->toAudioPortConfig(&newConfig, config);
5422 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005423 }
Eric Laurenta121f902014-06-03 13:32:54 -07005424 if (status != NO_ERROR) {
5425 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005426 }
Eric Laurente1715a42014-05-20 11:30:42 -07005427
5428 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005429}
5430
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005431void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5432{
Eric Laurentd60560a2015-04-10 11:31:20 -07005433 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005434 clearAudioPatches(uid);
5435 clearSessionRoutes(uid);
5436}
5437
Eric Laurent6a94d692014-05-20 11:18:06 -07005438void AudioPolicyManager::clearAudioPatches(uid_t uid)
5439{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005440 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005441 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005442 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005443 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 }
5445 }
5446}
5447
François Gaffiec005e562018-11-06 15:04:49 +01005448void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005449{
François Gaffiec005e562018-11-06 15:04:49 +01005450 // Take the first attributes following the product strategy as it is used to retrieve the routed
5451 // device. All attributes wihin a strategy follows the same "routing strategy"
5452 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5453 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005454 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005455 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005456 for (size_t j = 0; j < mOutputs.size(); j++) {
5457 if (mOutputs.keyAt(j) == ouptutToSkip) {
5458 continue;
5459 }
5460 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005461 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005462 continue;
5463 }
5464 // If the default device for this strategy is on another output mix,
5465 // invalidate all tracks in this strategy to force re connection.
5466 // Otherwise select new device on the output mix.
5467 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005468 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005469 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005470 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5471 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5472 // If the device is using preferred mixer attributes, the output need to reopen
5473 // with default configuration when the new selected devices are different from
5474 // current routing devices.
5475 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5476 continue;
5477 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305478 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005479 }
5480 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005481 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005482}
5483
5484void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5485{
5486 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005487 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005488 for (size_t i = 0; i < mOutputs.size(); i++) {
5489 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005490 for (const auto& client : outputDesc->getClientIterable()) {
5491 if (client->hasPreferredDevice() && client->uid() == uid) {
5492 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005493 auto clientStrategy = client->strategy();
5494 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5495 end(affectedStrategies)) {
5496 continue;
5497 }
5498 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005499 }
5500 }
5501 }
5502 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005503 for (const auto& strategy : affectedStrategies) {
5504 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005505 }
5506
5507 // remove input routes associated with this uid
5508 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005509 for (size_t i = 0; i < mInputs.size(); i++) {
5510 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005511 for (const auto& client : inputDesc->getClientIterable()) {
5512 if (client->hasPreferredDevice() && client->uid() == uid) {
5513 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5514 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005515 }
5516 }
5517 }
5518 // reroute inputs if necessary
5519 SortedVector<audio_io_handle_t> inputsToClose;
5520 for (size_t i = 0; i < mInputs.size(); i++) {
5521 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005522 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005523 inputsToClose.add(inputDesc->mIoHandle);
5524 }
5525 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005526 for (const auto& input : inputsToClose) {
5527 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005528 }
5529}
5530
Eric Laurentd60560a2015-04-10 11:31:20 -07005531void AudioPolicyManager::clearAudioSources(uid_t uid)
5532{
5533 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005534 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5535 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005536 stopAudioSource(mAudioSources.keyAt(i));
5537 }
5538 }
5539}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005540
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005541status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5542 audio_io_handle_t *ioHandle,
5543 audio_devices_t *device)
5544{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005545 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5546 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005547 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005548 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5549 if (deviceDesc == nullptr) {
5550 return INVALID_OPERATION;
5551 }
5552 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005553
François Gaffiedf372692015-03-19 10:43:27 +01005554 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005555}
5556
Eric Laurentd60560a2015-04-10 11:31:20 -07005557status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005558 const audio_attributes_t *attributes,
5559 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005560 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005561{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005562 ALOGV("%s", __FUNCTION__);
5563 *portId = AUDIO_PORT_HANDLE_NONE;
5564
5565 if (source == NULL || attributes == NULL || portId == NULL) {
5566 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5567 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005568 return BAD_VALUE;
5569 }
5570
Eric Laurentd60560a2015-04-10 11:31:20 -07005571 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5572 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005573 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5574 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005575 return INVALID_OPERATION;
5576 }
5577
François Gaffie11d30102018-11-02 16:09:09 +01005578 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005579 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005580 String8(source->ext.device.address),
5581 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005582 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005583 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005584 return BAD_VALUE;
5585 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005586
jiabin4ef93452019-09-10 14:29:54 -07005587 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005588
François Gaffieaaac0fd2018-11-22 17:56:39 +01005589 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005590 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005591 mEngine->getStreamTypeForAttributes(*attributes),
5592 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005593 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005594
5595 status_t status = connectAudioSource(sourceDesc);
5596 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005597 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005598 }
5599 return status;
5600}
5601
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005602status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005603{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005604 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005605
5606 // make sure we only have one patch per source.
5607 disconnectAudioSource(sourceDesc);
5608
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005609 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005610 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5611 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5612 sourceDesc->srcDevice()->type(),
5613 String8(sourceDesc->srcDevice()->address().c_str()),
5614 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005615 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005616 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005617 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005618 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005619 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5620 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5621 return INVALID_OPERATION;
5622 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005623 PatchBuilder patchBuilder;
5624 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5625 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005626
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005627 return connectAudioSourceToSink(
5628 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005629}
5630
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005631status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005632{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005633 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5634 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005635 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005636 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005637 return BAD_VALUE;
5638 }
5639 status_t status = disconnectAudioSource(sourceDesc);
5640
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005641 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005642 return status;
5643}
5644
Andy Hung2ddee192015-12-18 17:34:44 -08005645status_t AudioPolicyManager::setMasterMono(bool mono)
5646{
5647 if (mMasterMono == mono) {
5648 return NO_ERROR;
5649 }
5650 mMasterMono = mono;
5651 // if enabling mono we close all offloaded devices, which will invalidate the
5652 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5653 // for recreating the new AudioTrack as non-offloaded PCM.
5654 //
5655 // If disabling mono, we leave all tracks as is: we don't know which clients
5656 // and tracks are able to be recreated as offloaded. The next "song" should
5657 // play back offloaded.
5658 if (mMasterMono) {
5659 Vector<audio_io_handle_t> offloaded;
5660 for (size_t i = 0; i < mOutputs.size(); ++i) {
5661 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5662 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5663 offloaded.push(desc->mIoHandle);
5664 }
5665 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005666 for (const auto& handle : offloaded) {
5667 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005668 }
5669 }
5670 // update master mono for all remaining outputs
5671 for (size_t i = 0; i < mOutputs.size(); ++i) {
5672 updateMono(mOutputs.keyAt(i));
5673 }
5674 return NO_ERROR;
5675}
5676
5677status_t AudioPolicyManager::getMasterMono(bool *mono)
5678{
5679 *mono = mMasterMono;
5680 return NO_ERROR;
5681}
5682
Eric Laurentac9cef52017-06-09 15:46:26 -07005683float AudioPolicyManager::getStreamVolumeDB(
5684 audio_stream_type_t stream, int index, audio_devices_t device)
5685{
jiabin9a3361e2019-10-01 09:38:30 -07005686 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005687}
5688
jiabin81772902018-04-02 17:52:27 -07005689status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5690 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005691 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005692{
Kriti Dang6537def2021-03-02 13:46:59 +01005693 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5694 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005695 return BAD_VALUE;
5696 }
Kriti Dang6537def2021-03-02 13:46:59 +01005697 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5698 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005699
5700 size_t formatsWritten = 0;
5701 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005702
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005703 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005704 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5705 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005706 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005707 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005708 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005709 bool formatEnabled = true;
5710 switch (forceUse) {
5711 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005712 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005713 break;
5714 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5715 formatEnabled = false;
5716 break;
5717 default: // AUTO or ALWAYS => true
5718 break;
jiabin81772902018-04-02 17:52:27 -07005719 }
5720 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5721 }
jiabin81772902018-04-02 17:52:27 -07005722 }
5723 return NO_ERROR;
5724}
5725
Kriti Dang6537def2021-03-02 13:46:59 +01005726status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5727 audio_format_t *surroundFormats) {
5728 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5729 return BAD_VALUE;
5730 }
5731 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5732 __func__, *numSurroundFormats, surroundFormats);
5733
5734 size_t formatsWritten = 0;
5735 size_t formatsMax = *numSurroundFormats;
5736 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5737
5738 // Return formats from all device profiles that have already been resolved by
5739 // checkOutputsForDevice().
5740 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5741 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5742 audio_devices_t deviceType = device->type();
5743 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5744 // returns formats reported by HDMI devices.
5745 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5746 continue;
5747 }
5748 // Formats reported by sink devices
5749 std::unordered_set<audio_format_t> formatset;
5750 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5751 formatset.insert(it->second.begin(), it->second.end());
5752 }
5753
5754 // Formats hard-coded in the in policy configuration file (if any).
5755 FormatVector encodedFormats = device->encodedFormats();
5756 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5757 // Filter the formats which are supported by the vendor hardware.
5758 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005759 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005760 formats.insert(*it);
5761 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005762 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005763 if (pair.second.count(*it) != 0) {
5764 formats.insert(pair.first);
5765 break;
5766 }
5767 }
5768 }
5769 }
5770 }
5771 *numSurroundFormats = formats.size();
5772 for (const auto& format: formats) {
5773 if (formatsWritten < formatsMax) {
5774 surroundFormats[formatsWritten++] = format;
5775 }
5776 }
5777 return NO_ERROR;
5778}
5779
jiabin81772902018-04-02 17:52:27 -07005780status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5781{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005782 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005783 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5784 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005785 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005786 return BAD_VALUE;
5787 }
5788
Mikhail Naganov100f0122018-11-29 11:22:16 -08005789 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5790 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005791 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005792 return INVALID_OPERATION;
5793 }
5794
Mikhail Naganov100f0122018-11-29 11:22:16 -08005795 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005796 return NO_ERROR;
5797 }
5798
Mikhail Naganov100f0122018-11-29 11:22:16 -08005799 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005800 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005801 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005802 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005803 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005804 }
5805 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005806 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005807 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005808 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005809 }
5810 }
5811
5812 sp<SwAudioOutputDescriptor> outputDesc;
5813 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005814 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5815 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005816 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5817 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005818 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005819 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005820 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5821 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5822 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005823 name.c_str(),
5824 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005825 if (status != NO_ERROR) {
5826 continue;
5827 }
5828 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5829 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5830 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005831 name.c_str(),
5832 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005833 profileUpdated |= (status == NO_ERROR);
5834 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005835 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005836 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005837 AUDIO_DEVICE_IN_HDMI);
5838 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5839 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005840 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005841 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005842 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5843 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5844 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005845 name.c_str(),
5846 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005847 if (status != NO_ERROR) {
5848 continue;
5849 }
5850 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5851 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5852 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005853 name.c_str(),
5854 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005855 profileUpdated |= (status == NO_ERROR);
5856 }
5857
jiabin81772902018-04-02 17:52:27 -07005858 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005859 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005860 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005861 }
5862
5863 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5864}
5865
Eric Laurent5ada82e2019-08-29 17:53:54 -07005866void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005867{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005868 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005869 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005870 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005871 }
5872}
5873
jiabin6012f912018-11-02 17:06:30 -07005874bool AudioPolicyManager::isHapticPlaybackSupported()
5875{
5876 for (const auto& hwModule : mHwModules) {
5877 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5878 for (const auto &outProfile : outputProfiles) {
5879 struct audio_port audioPort;
5880 outProfile->toAudioPort(&audioPort);
5881 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5882 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5883 return true;
5884 }
5885 }
5886 }
5887 }
5888 return false;
5889}
5890
Carter Hsu325a8eb2022-01-19 19:56:51 +08005891bool AudioPolicyManager::isUltrasoundSupported()
5892{
5893 bool hasUltrasoundOutput = false;
5894 bool hasUltrasoundInput = false;
5895 for (const auto& hwModule : mHwModules) {
5896 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5897 if (!hasUltrasoundOutput) {
5898 for (const auto &outProfile : outputProfiles) {
5899 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5900 hasUltrasoundOutput = true;
5901 break;
5902 }
5903 }
5904 }
5905
5906 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5907 if (!hasUltrasoundInput) {
5908 for (const auto &inputProfile : inputProfiles) {
5909 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5910 hasUltrasoundInput = true;
5911 break;
5912 }
5913 }
5914 }
5915
5916 if (hasUltrasoundOutput && hasUltrasoundInput)
5917 return true;
5918 }
5919 return false;
5920}
5921
Atneya Nair698f5ef2022-12-15 16:15:09 -08005922bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5923{
5924 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5925 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5926 for (const auto& hwModule : mHwModules) {
5927 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5928 for (const auto &inputProfile : inputProfiles) {
5929 if ((inputProfile->getFlags() & mask) == mask) {
5930 return true;
5931 }
5932 }
5933 }
5934 return false;
5935}
5936
Eric Laurent8340e672019-11-06 11:01:08 -08005937bool AudioPolicyManager::isCallScreenModeSupported()
5938{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005939 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005940}
5941
5942
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005943status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005944{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005945 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005946 if (!sourceDesc->isConnected()) {
5947 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5948 return NO_ERROR;
5949 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005950 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5951 if (swOutput != 0) {
5952 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005953 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005954 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005955 }
jiabinbce0c1d2020-10-05 11:20:18 -07005956 if (releaseOutput(sourceDesc->portId())) {
5957 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5958 // no need to release audio patch here but just return NO_ERROR.
5959 return NO_ERROR;
5960 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005961 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005962 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005963 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005964 // close Hwoutput and remove from mHwOutputs
5965 } else {
5966 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5967 }
5968 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005969 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005970 sourceDesc->disconnect();
5971 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005972}
5973
François Gaffiec005e562018-11-06 15:04:49 +01005974sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5975 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005976{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005977 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005978 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005979 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005980 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005981 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5982 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005983 source = sourceDesc;
5984 break;
5985 }
5986 }
5987 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005988}
5989
Eric Laurentb4f42a92022-01-17 17:37:31 +01005990bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005991 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005992 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005993{
5994 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5995 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005996 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005997 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005998 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5999 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6000 return false;
6001 }
6002 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6003 return false;
6004 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006005 }
6006
Eric Laurentd332bc82023-08-04 11:45:23 +02006007 // The caller can have the audio config criteria ignored by either passing a null ptr or
6008 // the AUDIO_CONFIG_INITIALIZER value.
6009 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006010 // some positional channel masks and PCM format and for stereo if low latency performance
6011 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006012
6013 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006014 static const bool stereo_spatialization_enabled =
6015 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006016 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006017 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006018 ? audio_channel_mask_contains_stereo(config->channel_mask)
6019 : audio_is_channel_mask_spatialized(config->channel_mask);
6020 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006021 return false;
6022 }
6023 if (!audio_is_linear_pcm(config->format)) {
6024 return false;
6025 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006026 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6027 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6028 return false;
6029 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006030 }
6031
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006032 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006033 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006034 if (profile == nullptr) {
6035 return false;
6036 }
6037
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006038 return true;
6039}
6040
6041void AudioPolicyManager::checkVirtualizerClientRoutes() {
6042 std::set<audio_stream_type_t> streamsToInvalidate;
6043 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006044 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6045 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006046 audio_attributes_t attr = client->attributes();
6047 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6048 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6049 audio_config_base_t clientConfig = client->config();
6050 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006051 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006052 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006053 streamsToInvalidate.insert(client->stream());
6054 }
6055 }
6056 }
6057
jiabinc44b3462022-12-08 12:52:31 -08006058 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006059}
6060
Eric Laurente191d1b2022-04-15 11:59:25 +02006061
6062bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6063 const sp<SwAudioOutputDescriptor>& outputDesc) {
6064 if (outputDesc->isDuplicated()) {
6065 return false;
6066 }
6067 DeviceVector devices = outputDesc->supportedDevices();
6068 for (size_t i = 0; i < mOutputs.size(); i++) {
6069 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6070 if (desc == outputDesc || desc->isDuplicated()) {
6071 continue;
6072 }
6073 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6074 if (!sharedDevices.isEmpty()
6075 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6076 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6077 return false;
6078 }
6079 }
6080 return true;
6081}
6082
6083
Eric Laurentfa0f6742021-08-17 18:39:44 +02006084status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006085 const audio_attributes_t *attr,
6086 audio_io_handle_t *output) {
6087 *output = AUDIO_IO_HANDLE_NONE;
6088
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006089 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6090 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6091 audio_config_t *configPtr = nullptr;
6092 audio_config_t config;
6093 if (mixerConfig != nullptr) {
6094 config = audio_config_initializer(mixerConfig);
6095 configPtr = &config;
6096 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006097 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006098 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006099 return BAD_VALUE;
6100 }
6101
6102 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006103 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006104 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006105 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006106 return BAD_VALUE;
6107 }
6108
Eric Laurente191d1b2022-04-15 11:59:25 +02006109 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006110 for (size_t i = 0; i < mOutputs.size(); i++) {
6111 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006112 if (!desc->isDuplicated()
6113 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6114 spatializerOutputs.push_back(desc);
6115 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006116 }
6117 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006118 mSpatializerOutput.clear();
6119 bool outputsChanged = false;
6120 for (const auto& desc : spatializerOutputs) {
6121 if (desc->mProfile == profile
6122 && (configPtr == nullptr
6123 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6124 mSpatializerOutput = desc;
6125 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6126 } else {
6127 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6128 " and devices %s", __func__, desc->mIoHandle,
6129 configPtr != nullptr ? configPtr->channel_mask : 0,
6130 devices.toString().c_str());
6131 closeOutput(desc->mIoHandle);
6132 outputsChanged = true;
6133 }
Eric Laurent39095982021-08-24 18:29:27 +02006134 }
6135
Eric Laurente191d1b2022-04-15 11:59:25 +02006136 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006137 sp<SwAudioOutputDescriptor> desc =
6138 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006139 if (desc != nullptr) {
6140 mSpatializerOutput = desc;
6141 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006142 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006143 }
6144
6145 checkVirtualizerClientRoutes();
6146
Eric Laurente191d1b2022-04-15 11:59:25 +02006147 if (outputsChanged) {
6148 mPreviousOutputs = mOutputs;
6149 mpClientInterface->onAudioPortListUpdate();
6150 }
6151
6152 if (mSpatializerOutput == nullptr) {
6153 ALOGV("%s could not open spatializer output with requested config", __func__);
6154 return BAD_VALUE;
6155 }
Eric Laurent39095982021-08-24 18:29:27 +02006156 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006157 ALOGV("%s returning new spatializer output %d", __func__, *output);
6158 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006159}
6160
Eric Laurentfa0f6742021-08-17 18:39:44 +02006161status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6162 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006163 return INVALID_OPERATION;
6164 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006165 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006166 return BAD_VALUE;
6167 }
Eric Laurent39095982021-08-24 18:29:27 +02006168
Eric Laurente191d1b2022-04-15 11:59:25 +02006169 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6170 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6171 closeOutput(mSpatializerOutput->mIoHandle);
6172 //from now on mSpatializerOutput is null
6173 checkVirtualizerClientRoutes();
6174 }
Eric Laurent39095982021-08-24 18:29:27 +02006175
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006176 return NO_ERROR;
6177}
6178
Eric Laurente552edb2014-03-10 17:42:56 -07006179// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006180// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006181// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006182uint32_t AudioPolicyManager::nextAudioPortGeneration()
6183{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006184 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006185}
6186
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006187AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006188 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006189 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006190 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006191 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006192 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006193 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006194 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006195 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006196 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006197 mAudioPortGeneration(1),
6198 mBeaconMuteRefCount(0),
6199 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006200 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006201 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006202 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006203 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006204{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006205}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006206
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006207status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006208 if (mEngine == nullptr) {
6209 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006210 }
6211 mEngine->setObserver(this);
6212 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006213 if (status != NO_ERROR) {
6214 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6215 return status;
6216 }
François Gaffie2110e042015-03-24 08:41:51 +01006217
jiabin29230182023-04-04 21:02:36 +00006218 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6219 // at the end of this function.
6220 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006221 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6222 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6223
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006224 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006225 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006226 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006227
Eric Laurent3a4311c2014-03-17 12:00:47 -07006228 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006229 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6230 defaultOutputDevice == nullptr ||
6231 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6232 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6233 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006234 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006235 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006236 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006237
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006238 // Silence ALOGV statements
6239 property_set("log.tag." LOG_TAG, "D");
6240
Eric Laurente552edb2014-03-10 17:42:56 -07006241 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006242 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006243}
6244
Eric Laurente0720872014-03-11 09:30:41 -07006245AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006246{
Eric Laurente552edb2014-03-10 17:42:56 -07006247 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006248 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006249 }
6250 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006251 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006252 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006253 mAvailableOutputDevices.clear();
6254 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006255 mOutputs.clear();
6256 mInputs.clear();
6257 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006258 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006259 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006260}
6261
Eric Laurente0720872014-03-11 09:30:41 -07006262status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006263{
Eric Laurent87ffa392015-05-22 10:32:38 -07006264 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006265}
6266
Eric Laurente552edb2014-03-10 17:42:56 -07006267// ---
6268
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006269void AudioPolicyManager::onNewAudioModulesAvailable()
6270{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006271 DeviceVector newDevices;
6272 onNewAudioModulesAvailableInt(&newDevices);
6273 if (!newDevices.empty()) {
6274 nextAudioPortGeneration();
6275 mpClientInterface->onAudioPortListUpdate();
6276 }
6277}
6278
6279void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6280{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006281 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006282 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6283 continue;
6284 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006285 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006286 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6287 handle != AUDIO_MODULE_HANDLE_NONE) {
6288 hwModule->setHandle(handle);
6289 } else {
6290 ALOGW("could not load HW module %s", hwModule->getName());
6291 continue;
6292 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006293 }
6294 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006295 // open all output streams needed to access attached devices.
6296 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006297 // This also validates mAvailableOutputDevices list
6298 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6299 if (!outProfile->canOpenNewIo()) {
6300 ALOGE("Invalid Output profile max open count %u for profile %s",
6301 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6302 continue;
6303 }
6304 if (!outProfile->hasSupportedDevices()) {
6305 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6306 continue;
6307 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006308 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6309 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006310 mTtsOutputAvailable = true;
6311 }
6312
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006313 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006314 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006315 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006316 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6317 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006318 } else {
6319 // choose first device present in profile's SupportedDevices also part of
6320 // mAvailableOutputDevices.
6321 if (availProfileDevices.isEmpty()) {
6322 continue;
6323 }
6324 supportedDevice = availProfileDevices.itemAt(0);
6325 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006326 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006327 continue;
6328 }
6329 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6330 mpClientInterface);
6331 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006332 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6333 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006334 AUDIO_STREAM_DEFAULT,
6335 AUDIO_OUTPUT_FLAG_NONE, &output);
6336 if (status != NO_ERROR) {
6337 ALOGW("Cannot open output stream for devices %s on hw module %s",
6338 supportedDevice->toString().c_str(), hwModule->getName());
6339 continue;
6340 }
6341 for (const auto &device : availProfileDevices) {
6342 // give a valid ID to an attached device once confirmed it is reachable
6343 if (!device->isAttached()) {
6344 device->attach(hwModule);
6345 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006346 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006347 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006348 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6349 }
6350 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006351 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006352 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6353 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006354 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006355 }
Eric Laurent39095982021-08-24 18:29:27 +02006356 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006357 outputDesc->close();
6358 } else {
6359 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306360 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006361 DeviceVector(supportedDevice),
6362 true,
6363 0,
6364 NULL);
6365 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006366 }
6367 // open input streams needed to access attached devices to validate
6368 // mAvailableInputDevices list
6369 for (const auto& inProfile : hwModule->getInputProfiles()) {
6370 if (!inProfile->canOpenNewIo()) {
6371 ALOGE("Invalid Input profile max open count %u for profile %s",
6372 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6373 continue;
6374 }
6375 if (!inProfile->hasSupportedDevices()) {
6376 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6377 continue;
6378 }
6379 // chose first device present in profile's SupportedDevices also part of
6380 // available input devices
6381 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006382 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006383 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006384 ALOGV("%s: Input device list is empty! for profile %s",
6385 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006386 continue;
6387 }
6388 sp<AudioInputDescriptor> inputDesc =
6389 new AudioInputDescriptor(inProfile, mpClientInterface);
6390
6391 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6392 status_t status = inputDesc->open(nullptr,
6393 availProfileDevices.itemAt(0),
6394 AUDIO_SOURCE_MIC,
6395 AUDIO_INPUT_FLAG_NONE,
6396 &input);
6397 if (status != NO_ERROR) {
6398 ALOGW("Cannot open input stream for device %s on hw module %s",
6399 availProfileDevices.toString().c_str(),
6400 hwModule->getName());
6401 continue;
6402 }
6403 for (const auto &device : availProfileDevices) {
6404 // give a valid ID to an attached device once confirmed it is reachable
6405 if (!device->isAttached()) {
6406 device->attach(hwModule);
6407 device->importAudioPortAndPickAudioProfile(inProfile, true);
6408 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006409 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006410 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6411 }
6412 }
6413 inputDesc->close();
6414 }
6415 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006416
6417 // Check if spatializer outputs can be closed until used.
6418 // mOutputs vector never contains duplicated outputs at this point.
6419 std::vector<audio_io_handle_t> outputsClosed;
6420 for (size_t i = 0; i < mOutputs.size(); i++) {
6421 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6422 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6423 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6424 outputsClosed.push_back(desc->mIoHandle);
6425 desc->close();
6426 }
6427 }
6428 for (auto output : outputsClosed) {
6429 removeOutput(output);
6430 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006431}
6432
Eric Laurent98e38192018-02-15 18:31:53 -08006433void AudioPolicyManager::addOutput(audio_io_handle_t output,
6434 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006435{
Eric Laurent1c333e22014-05-20 10:48:17 -07006436 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006437 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006438 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006439 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006440 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006441}
6442
François Gaffie53615e22015-03-19 09:24:12 +01006443void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6444{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006445 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6446 ALOGV("%s: removing primary output", __func__);
6447 mPrimaryOutput = nullptr;
6448 }
François Gaffie53615e22015-03-19 09:24:12 +01006449 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006450 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006451}
6452
Eric Laurent98e38192018-02-15 18:31:53 -08006453void AudioPolicyManager::addInput(audio_io_handle_t input,
6454 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006455{
Eric Laurent1c333e22014-05-20 10:48:17 -07006456 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006457 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006458}
Eric Laurente552edb2014-03-10 17:42:56 -07006459
François Gaffie11d30102018-11-02 16:09:09 +01006460status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006461 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006462 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006463{
François Gaffie11d30102018-11-02 16:09:09 +01006464 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006465 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006466 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006467
François Gaffie11d30102018-11-02 16:09:09 +01006468 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006469 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006470 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006471 }
Eric Laurente552edb2014-03-10 17:42:56 -07006472
Eric Laurent3b73df72014-03-11 09:06:29 -07006473 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006474 // first call getAudioPort to get the supported attributes from the HAL
6475 struct audio_port_v7 port = {};
6476 device->toAudioPort(&port);
6477 status_t status = mpClientInterface->getAudioPort(&port);
6478 if (status == NO_ERROR) {
6479 device->importAudioPort(port);
6480 }
6481
6482 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006483 for (size_t i = 0; i < mOutputs.size(); i++) {
6484 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006485 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006486 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006487 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6488 mOutputs.keyAt(i), device->toString().c_str());
6489 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006490 }
6491 }
6492 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006493 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006494 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006495 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6496 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006497 if (profile->supportsDevice(device)) {
6498 profiles.add(profile);
6499 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6500 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006501 }
6502 }
6503 }
6504
Eric Laurent7b279bb2015-12-14 10:18:23 -08006505 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006506
Eric Laurente552edb2014-03-10 17:42:56 -07006507 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006508 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006509 return BAD_VALUE;
6510 }
6511
6512 // open outputs for matching profiles if needed. Direct outputs are also opened to
6513 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6514 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006515 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006516
6517 // nothing to do if one output is already opened for this profile
6518 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006519 for (j = 0; j < outputs.size(); j++) {
6520 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006521 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006522 // matching profile: save the sample rates, format and channel masks supported
6523 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006524 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006525 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006526 }
Eric Laurente552edb2014-03-10 17:42:56 -07006527 break;
6528 }
6529 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006530 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006531 continue;
6532 }
6533
Eric Laurent3974e3b2017-12-07 17:58:43 -08006534 if (!profile->canOpenNewIo()) {
6535 ALOGW("Max Output number %u already opened for this profile %s",
6536 profile->maxOpenCount, profile->getTagName().c_str());
6537 continue;
6538 }
6539
Eric Laurent83efe1c2017-07-09 16:51:08 -07006540 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006541 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006542 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6543 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006544 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006545 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006546 profiles.removeAt(profile_index);
6547 profile_index--;
6548 } else {
6549 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006550 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006551 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006552 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6553 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006554 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006555 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006556
François Gaffie11d30102018-11-02 16:09:09 +01006557 if (device_distinguishes_on_address(deviceType)) {
6558 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6559 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306560 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6561 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006562 }
Eric Laurente552edb2014-03-10 17:42:56 -07006563 ALOGV("checkOutputsForDevice(): adding output %d", output);
6564 }
6565 }
6566
6567 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006568 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006569 return BAD_VALUE;
6570 }
Eric Laurentd4692962014-05-05 18:13:44 -07006571 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006572 // check if one opened output is not needed any more after disconnecting one device
6573 for (size_t i = 0; i < mOutputs.size(); i++) {
6574 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006575 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006576 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006577 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006578 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006579 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006580 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006581 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6582 mOutputs.keyAt(i));
6583 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006584 }
Eric Laurente552edb2014-03-10 17:42:56 -07006585 }
6586 }
Eric Laurentd4692962014-05-05 18:13:44 -07006587 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006588 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006589 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6590 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006591 if (!profile->supportsDevice(device)) {
6592 continue;
6593 }
6594 ALOGV("checkOutputsForDevice(): "
6595 "clearing direct output profile %zu on module %s",
6596 j, hwModule->getName());
6597 profile->clearAudioProfiles();
6598 if (!profile->hasDynamicAudioProfile()) {
6599 continue;
6600 }
6601 // When a device is disconnected, if there is an IOProfile that contains dynamic
6602 // profiles and supports the disconnected device, call getAudioPort to repopulate
6603 // the capabilities of the devices that is supported by the IOProfile.
6604 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6605 if (supportedDevice == device ||
6606 !mAvailableOutputDevices.contains(supportedDevice)) {
6607 continue;
6608 }
6609 struct audio_port_v7 port;
6610 supportedDevice->toAudioPort(&port);
6611 status_t status = mpClientInterface->getAudioPort(&port);
6612 if (status == NO_ERROR) {
6613 supportedDevice->importAudioPort(port);
6614 }
Eric Laurente552edb2014-03-10 17:42:56 -07006615 }
6616 }
6617 }
6618 }
6619 return NO_ERROR;
6620}
6621
François Gaffie11d30102018-11-02 16:09:09 +01006622status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006623 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006624{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006625 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006626
François Gaffie11d30102018-11-02 16:09:09 +01006627 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006628 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006629 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006630 }
6631
Eric Laurentd4692962014-05-05 18:13:44 -07006632 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006633 // first call getAudioPort to get the supported attributes from the HAL
6634 struct audio_port_v7 port = {};
6635 device->toAudioPort(&port);
6636 status_t status = mpClientInterface->getAudioPort(&port);
6637 if (status == NO_ERROR) {
6638 device->importAudioPort(port);
6639 }
6640
Eric Laurent0dd51852019-04-19 18:18:58 -07006641 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006642 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006643 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006644 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006645 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006646 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006647 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006648
François Gaffie11d30102018-11-02 16:09:09 +01006649 if (profile->supportsDevice(device)) {
6650 profiles.add(profile);
6651 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6652 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006653 }
6654 }
6655 }
6656
Eric Laurent0dd51852019-04-19 18:18:58 -07006657 if (profiles.isEmpty()) {
6658 ALOGW("%s: No input profile available for device %s",
6659 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006660 return BAD_VALUE;
6661 }
6662
6663 // open inputs for matching profiles if needed. Direct inputs are also opened to
6664 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6665 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6666
Eric Laurent1c333e22014-05-20 10:48:17 -07006667 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006668
Eric Laurentd4692962014-05-05 18:13:44 -07006669 // nothing to do if one input is already opened for this profile
6670 size_t input_index;
6671 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6672 desc = mInputs.valueAt(input_index);
6673 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006674 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006675 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006676 }
Eric Laurentd4692962014-05-05 18:13:44 -07006677 break;
6678 }
6679 }
6680 if (input_index != mInputs.size()) {
6681 continue;
6682 }
6683
Eric Laurent3974e3b2017-12-07 17:58:43 -08006684 if (!profile->canOpenNewIo()) {
6685 ALOGW("Max Input number %u already opened for this profile %s",
6686 profile->maxOpenCount, profile->getTagName().c_str());
6687 continue;
6688 }
6689
Eric Laurentfe231122017-11-17 17:48:06 -08006690 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006691 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006692 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006693
Eric Laurentcf2c0212014-07-25 16:20:43 -07006694 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006695 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006696 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006697 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006698 mpClientInterface->setParameters(input, String8(param));
6699 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006700 }
jiabin12537fc2023-10-12 17:56:08 +00006701 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006702 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006703 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006704 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006705 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006706 }
6707
Eric Laurent0dd51852019-04-19 18:18:58 -07006708 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006709 addInput(input, desc);
6710 }
6711 } // endif input != 0
6712
Eric Laurentcf2c0212014-07-25 16:20:43 -07006713 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006714 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006715 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006716 profiles.removeAt(profile_index);
6717 profile_index--;
6718 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006719 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006720 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006721 }
Eric Laurentd4692962014-05-05 18:13:44 -07006722 ALOGV("checkInputsForDevice(): adding input %d", input);
6723 }
6724 } // end scan profiles
6725
6726 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006727 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006728 return BAD_VALUE;
6729 }
6730 } else {
6731 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006732 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006733 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006734 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006735 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006736 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006737 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006738 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006739 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6740 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006741 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006742 }
6743 }
6744 }
6745 } // end disconnect
6746
6747 return NO_ERROR;
6748}
6749
6750
Eric Laurente0720872014-03-11 09:30:41 -07006751void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006752{
6753 ALOGV("closeOutput(%d)", output);
6754
François Gaffie1c878552018-11-22 16:53:21 +01006755 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6756 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006757 ALOGW("closeOutput() unknown output %d", output);
6758 return;
6759 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006760 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006761 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006762
Eric Laurente552edb2014-03-10 17:42:56 -07006763 // look for duplicated outputs connected to the output being removed.
6764 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006765 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6766 if (dupOutput->isDuplicated() &&
6767 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6768 sp<SwAudioOutputDescriptor> remainingOutput =
6769 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006770 // As all active tracks on duplicated output will be deleted,
6771 // and as they were also referenced on the other output, the reference
6772 // count for their stream type must be adjusted accordingly on
6773 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006774 const bool wasActive = remainingOutput->isActive();
6775 // Note: no-op on the closing output where all clients has already been set inactive
6776 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006777 // stop() will be a no op if the output is still active but is needed in case all
6778 // active streams refcounts where cleared above
6779 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006780 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006781 }
Eric Laurente552edb2014-03-10 17:42:56 -07006782 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6783 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6784
6785 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006786 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006787 }
6788 }
6789
Eric Laurent05b90f82014-08-27 15:32:29 -07006790 nextAudioPortGeneration();
6791
François Gaffie1c878552018-11-22 16:53:21 +01006792 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006793 if (index >= 0) {
6794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006795 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6796 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006797 mAudioPatches.removeItemsAt(index);
6798 mpClientInterface->onAudioPatchListUpdate();
6799 }
6800
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006801 if (closingOutputWasActive) {
6802 closingOutput->stop();
6803 }
François Gaffie1c878552018-11-22 16:53:21 +01006804 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006805 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6806 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6807 for (const auto device : closingOutput->devices()) {
6808 device->setPreferredConfig(nullptr);
6809 }
6810 }
Eric Laurente552edb2014-03-10 17:42:56 -07006811
François Gaffie53615e22015-03-19 09:24:12 +01006812 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006813 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006814 if (closingOutput == mSpatializerOutput) {
6815 mSpatializerOutput.clear();
6816 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006817
6818 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6819 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006820 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006821 bool directOutputOpen = false;
6822 for (size_t i = 0; i < mOutputs.size(); i++) {
6823 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6824 directOutputOpen = true;
6825 break;
6826 }
6827 }
6828 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006829 ALOGV("no direct outputs open, reset MSD patches");
6830 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6831 // how output devices for patching are resolved. Avoid by caching and reusing the
6832 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6833 // devices to patch to. This may be complicated by the fact that devices may become
6834 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006835 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006836 }
6837 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006838}
6839
6840void AudioPolicyManager::closeInput(audio_io_handle_t input)
6841{
6842 ALOGV("closeInput(%d)", input);
6843
6844 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6845 if (inputDesc == NULL) {
6846 ALOGW("closeInput() unknown input %d", input);
6847 return;
6848 }
6849
Eric Laurent6a94d692014-05-20 11:18:06 -07006850 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006851
François Gaffie11d30102018-11-02 16:09:09 +01006852 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006853 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006854 if (index >= 0) {
6855 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006856 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6857 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006858 mAudioPatches.removeItemsAt(index);
6859 mpClientInterface->onAudioPatchListUpdate();
6860 }
6861
François Gaffie6ebbce02023-07-19 13:27:53 +02006862 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006863 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006864 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006865
François Gaffie11d30102018-11-02 16:09:09 +01006866 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6867 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006868 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006869 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006870 }
Eric Laurente552edb2014-03-10 17:42:56 -07006871}
6872
François Gaffie11d30102018-11-02 16:09:09 +01006873SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6874 const DeviceVector &devices,
6875 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006876{
6877 SortedVector<audio_io_handle_t> outputs;
6878
François Gaffie11d30102018-11-02 16:09:09 +01006879 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006880 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006881 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006882 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006883 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006884 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006885 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006886 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006887 outputs.add(openOutputs.keyAt(i));
6888 }
6889 }
6890 return outputs;
6891}
6892
Mikhail Naganov37977152018-07-11 15:54:44 -07006893void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6894{
6895 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6896 // output is suspended before any tracks are moved to it
6897 checkA2dpSuspend();
6898 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006899 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006900 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006901 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006902 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006903 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6904 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6905 // configuration changes will ultimately be rerouted correctly. We can still avoid
6906 // unnecessary rerouting by caching and reusing the arguments to
6907 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6908 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006909 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006910 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006911 // an event that changed routing likely occurred, inform upper layers
6912 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006913}
6914
François Gaffiec005e562018-11-06 15:04:49 +01006915bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6916 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006917{
François Gaffiec005e562018-11-06 15:04:49 +01006918 return mEngine->getProductStrategyForAttributes(lAttr) ==
6919 mEngine->getProductStrategyForAttributes(rAttr);
6920}
6921
Francois Gaffieff1eb522020-05-06 18:37:04 +02006922void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6923{
6924 for (size_t i = 0; i < mAudioSources.size(); i++) {
6925 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6926 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006927 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006928 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006929 connectAudioSource(sourceDesc);
6930 }
6931 }
6932}
6933
6934void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6935{
6936 for (size_t i = 0; i < mAudioSources.size(); i++) {
6937 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6938 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6939 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6940 disconnectAudioSource(sourceDesc);
6941 }
6942 }
6943}
6944
François Gaffiec005e562018-11-06 15:04:49 +01006945void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6946{
6947 auto psId = mEngine->getProductStrategyForAttributes(attr);
6948
6949 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6950 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006951
François Gaffie11d30102018-11-02 16:09:09 +01006952 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6953 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006954
Eric Laurentc209fe42020-06-05 18:11:23 -07006955 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006956 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006957 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006958 // take into account dynamic audio policies related changes: if a client is now associated
6959 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006960 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006961 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6962 if (desc->isDuplicated()) {
6963 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006964 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006965 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6966 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6967 continue;
6968 }
6969 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006970 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006971 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6972 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6973 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006974 if (status != OK) {
6975 continue;
6976 }
yucliuf4de36d2020-09-14 14:57:56 -07006977 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006978 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006979 maxLatency = desc->latency();
6980 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006981 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006982 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006983 }
6984 }
6985
Eric Laurent56ed8842022-11-15 16:04:41 +01006986 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006987 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6988 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006989 for (audio_io_handle_t srcOut : srcOutputs) {
6990 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006991 if (desc == nullptr) continue;
6992
6993 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006994 maxLatency = desc->latency();
6995 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006996
Eric Laurent56ed8842022-11-15 16:04:41 +01006997 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006998 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006999 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007000 // a client on a non direct outputs has necessarily a linear PCM format
7001 // so we can call selectOutput() safely
7002 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7003 client->flags(),
7004 client->config().format,
7005 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007006 client->config().sample_rate,
7007 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007008 if (newOutput != srcOut) {
7009 invalidate = true;
7010 break;
7011 }
7012 } else {
7013 sp<IOProfile> profile = getProfileForOutput(newDevices,
7014 client->config().sample_rate,
7015 client->config().format,
7016 client->config().channel_mask,
7017 client->flags(),
7018 true /* directOnly */);
7019 if (profile != desc->mProfile) {
7020 invalidate = true;
7021 break;
7022 }
7023 }
7024 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007025 // mute strategy while moving tracks from one output to another
7026 if (invalidate) {
7027 invalidatedOutputs.push_back(desc);
7028 if (desc->isStrategyActive(psId)) {
7029 setStrategyMute(psId, true, desc);
7030 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7031 newDevices.types());
7032 }
Eric Laurente552edb2014-03-10 17:42:56 -07007033 }
François Gaffiec005e562018-11-06 15:04:49 +01007034 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007035 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007036 connectAudioSource(source);
7037 }
Eric Laurente552edb2014-03-10 17:42:56 -07007038 }
7039
Eric Laurent56ed8842022-11-15 16:04:41 +01007040 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7041 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7042 std::to_string(srcOutputs[0]).c_str(),
7043 std::to_string(dstOutputs[0]).c_str());
7044
François Gaffiec005e562018-11-06 15:04:49 +01007045 // Move effects associated to this stream from previous output to new output
7046 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007047 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007048 }
François Gaffiec005e562018-11-06 15:04:49 +01007049 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007050 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007051 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007052 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007053 desc->setTracksInvalidatedStatusByStrategy(psId);
7054 }
Eric Laurente552edb2014-03-10 17:42:56 -07007055 }
7056 }
7057}
7058
Eric Laurente0720872014-03-11 09:30:41 -07007059void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007060{
François Gaffiec005e562018-11-06 15:04:49 +01007061 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7062 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7063 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007064 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007065 }
Eric Laurente552edb2014-03-10 17:42:56 -07007066}
7067
Kevin Rocard153f92d2018-12-18 18:33:28 -08007068void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007069 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007070 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007071 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007072 for (size_t i = 0; i < mOutputs.size(); i++) {
7073 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7074 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007075 sp<AudioPolicyMix> primaryMix;
7076 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007077 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007078 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7079 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7080 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007081 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7082 for (auto &secondaryMix : secondaryMixes) {
7083 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7084 if (outputDesc != nullptr &&
7085 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7086 secondaryDescs.push_back(outputDesc);
7087 }
7088 }
7089
jiabinc44b3462022-12-08 12:52:31 -08007090 if (status != OK &&
7091 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7092 // When it failed to query secondary output, only invalidate the client that is not
7093 // MMAP. The reason is that MMAP stream will not support secondary output.
7094 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007095 } else if (!std::equal(
7096 client->getSecondaryOutputs().begin(),
7097 client->getSecondaryOutputs().end(),
7098 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007099 if (!audio_is_linear_pcm(client->config().format)) {
7100 // If the format is not PCM, the tracks should be invalidated to get correct
7101 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007102 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007103 } else {
7104 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7105 std::vector<audio_io_handle_t> secondaryOutputIds;
7106 for (const auto &secondaryDesc: secondaryDescs) {
7107 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7108 weakSecondaryDescs.push_back(secondaryDesc);
7109 }
7110 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7111 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007112 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007113 }
7114 }
7115 }
jiabin10a03f12021-05-07 23:46:28 +00007116 if (!trackSecondaryOutputs.empty()) {
7117 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7118 }
jiabinc44b3462022-12-08 12:52:31 -08007119 if (!clientsToInvalidate.empty()) {
7120 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7121 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007122 }
7123}
7124
Eric Laurent2517af32020-11-25 15:31:27 +01007125bool AudioPolicyManager::isScoRequestedForComm() const {
7126 AudioDeviceTypeAddrVector devices;
7127 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7128 for (const auto &device : devices) {
7129 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7130 return true;
7131 }
7132 }
7133 return false;
7134}
7135
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007136bool AudioPolicyManager::isHearingAidUsedForComm() const {
7137 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7138 true /*fromCache*/);
7139 for (const auto &device : devices) {
7140 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7141 return true;
7142 }
7143 }
7144 return false;
7145}
7146
7147
Eric Laurente0720872014-03-11 09:30:41 -07007148void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007149{
François Gaffie53615e22015-03-19 09:24:12 +01007150 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007151 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007152 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007153 return;
7154 }
7155
Eric Laurent3a4311c2014-03-17 12:00:47 -07007156 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007157 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7158 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007159 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007160
7161 // if suspended, restore A2DP output if:
7162 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007163 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007164 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007165 //
Eric Laurentf732e072016-08-03 19:30:28 -07007166 // if not suspended, suspend A2DP output if:
7167 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007168 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007169 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007170 //
7171 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007172 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007173 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007174 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007175 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007176
7177 mpClientInterface->restoreOutput(a2dpOutput);
7178 mA2dpSuspended = false;
7179 }
7180 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007181 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007182 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007183 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007184 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007185
7186 mpClientInterface->suspendOutput(a2dpOutput);
7187 mA2dpSuspended = true;
7188 }
7189 }
7190}
7191
François Gaffie11d30102018-11-02 16:09:09 +01007192DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7193 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007194{
François Gaffiedb1755b2023-09-01 11:50:35 +02007195 if (outputDesc == nullptr) {
7196 return DeviceVector{};
7197 }
François Gaffie11d30102018-11-02 16:09:09 +01007198
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007199 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007200 if (index >= 0) {
7201 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007202 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007203 ALOGV("%s device %s forced by patch %d", __func__,
7204 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7205 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007206 }
7207 }
7208
Dean Wheatley514b4312020-06-17 21:45:00 +10007209 // Do not retrieve engine device for outputs through MSD
7210 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7211 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7212 return outputDesc->devices();
7213 }
7214
Eric Laurent97ac8712018-07-27 18:59:02 -07007215 // Honor explicit routing requests only if no client using default routing is active on this
7216 // input: a specific app can not force routing for other apps by setting a preferred device.
7217 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007218 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007219 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007220 if (device != nullptr) {
7221 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007222 }
7223
François Gaffiea807ef92018-11-05 10:44:33 +01007224 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7225 // of setForceUse / Default Bus device here
7226 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7227 if (device != nullptr) {
7228 return DeviceVector(device);
7229 }
7230
François Gaffiedb1755b2023-09-01 11:50:35 +02007231 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007232 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7233 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7234 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307235 auto hasStreamActive = [&](auto stream) {
7236 return hasStream(streams, stream) && isStreamActive(stream, 0);
7237 };
Eric Laurent484e9272018-06-07 17:29:23 -07007238
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307239 auto doGetOutputDevicesForVoice = [&]() {
7240 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007241 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307242 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007243 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7244 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307245 };
7246
7247 // With low-latency playing on speaker, music on WFD, when the first low-latency
7248 // output is stopped, getNewOutputDevices checks for a product strategy
7249 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007250 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307251 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7252 // stream is associated to the output descriptor.
7253 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7254 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7255 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7256 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007257 // Retrieval of devices for voice DL is done on primary output profile, cannot
7258 // check the route (would force modifying configuration file for this profile)
7259 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7260 break;
7261 }
Eric Laurente552edb2014-03-10 17:42:56 -07007262 }
François Gaffiec005e562018-11-06 15:04:49 +01007263 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007264 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007265}
7266
François Gaffie11d30102018-11-02 16:09:09 +01007267sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7268 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007269{
François Gaffie11d30102018-11-02 16:09:09 +01007270 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007271
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007272 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007273 if (index >= 0) {
7274 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007275 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007276 ALOGV("getNewInputDevice() device %s forced by patch %d",
7277 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7278 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007279 }
7280 }
7281
Eric Laurent97ac8712018-07-27 18:59:02 -07007282 // Honor explicit routing requests only if no client using default routing is active on this
7283 // input: a specific app can not force routing for other apps by setting a preferred device.
7284 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007285 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7286 if (device != nullptr) {
7287 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007288 }
7289
Eric Laurentdc95a252018-04-12 12:46:56 -07007290 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007291 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007292 audio_attributes_t attributes;
7293 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007294 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007295 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7296 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007297 attributes = topClient->attributes();
7298 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007299 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007300 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007301 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7302 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007303 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007304 }
7305
Francois Gaffie716e1432019-01-14 16:58:59 +01007306 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7307 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007308 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007309 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007310 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007311 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007312
Eric Laurente552edb2014-03-10 17:42:56 -07007313 return device;
7314}
7315
Eric Laurent794fde22016-03-11 09:50:45 -08007316bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7317 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007318 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007319}
7320
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007321status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007322 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007323 if (devices == nullptr) {
7324 return BAD_VALUE;
7325 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007326
Andy Hung6d23c0f2022-02-16 09:37:15 -08007327 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007328 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7329 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007330 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007331 for (const auto& device : curDevices) {
7332 devices->push_back(device->getDeviceTypeAddr());
7333 }
7334 return NO_ERROR;
7335}
7336
Eric Laurente0720872014-03-11 09:30:41 -07007337void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007338 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007339 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007340 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007341 updateDevicesAndOutputs();
7342 break;
7343 default:
7344 break;
7345 }
7346}
7347
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007348uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007349
7350 // skip beacon mute management if a dedicated TTS output is available
7351 if (mTtsOutputAvailable) {
7352 return 0;
7353 }
7354
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007355 switch(event) {
7356 case STARTING_OUTPUT:
7357 mBeaconMuteRefCount++;
7358 break;
7359 case STOPPING_OUTPUT:
7360 if (mBeaconMuteRefCount > 0) {
7361 mBeaconMuteRefCount--;
7362 }
7363 break;
7364 case STARTING_BEACON:
7365 mBeaconPlayingRefCount++;
7366 break;
7367 case STOPPING_BEACON:
7368 if (mBeaconPlayingRefCount > 0) {
7369 mBeaconPlayingRefCount--;
7370 }
7371 break;
7372 }
7373
7374 if (mBeaconMuteRefCount > 0) {
7375 // any playback causes beacon to be muted
7376 return setBeaconMute(true);
7377 } else {
7378 // no other playback: unmute when beacon starts playing, mute when it stops
7379 return setBeaconMute(mBeaconPlayingRefCount == 0);
7380 }
7381}
7382
7383uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7384 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7385 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7386 // keep track of muted state to avoid repeating mute/unmute operations
7387 if (mBeaconMuted != mute) {
7388 // mute/unmute AUDIO_STREAM_TTS on all outputs
7389 ALOGV("\t muting %d", mute);
7390 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007391 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7392 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7393 ALOGV("\t no tts volume source available");
7394 return 0;
7395 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007396 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007397 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007398 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007399 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007400 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007401 maxLatency = latency;
7402 }
7403 }
7404 mBeaconMuted = mute;
7405 return maxLatency;
7406 }
7407 return 0;
7408}
7409
Eric Laurente0720872014-03-11 09:30:41 -07007410void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007411{
François Gaffiec005e562018-11-06 15:04:49 +01007412 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007413 mPreviousOutputs = mOutputs;
7414}
7415
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007416uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007417 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007418 uint32_t delayMs)
7419{
7420 // mute/unmute strategies using an incompatible device combination
7421 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7422 // if unmuting, unmute only after the specified delay
7423 if (outputDesc->isDuplicated()) {
7424 return 0;
7425 }
7426
7427 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007428 DeviceVector devices = outputDesc->devices();
7429 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007430
François Gaffiec005e562018-11-06 15:04:49 +01007431 auto productStrategies = mEngine->getOrderedProductStrategies();
7432 for (const auto &productStrategy : productStrategies) {
7433 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7434 DeviceVector curDevices =
7435 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7436 curDevices = curDevices.filter(outputDesc->supportedDevices());
7437 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007438 bool doMute = false;
7439
François Gaffiec005e562018-11-06 15:04:49 +01007440 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007441 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007442 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7443 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007444 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007445 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007446 }
Eric Laurent99401132014-05-07 19:48:15 -07007447 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007448 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007449 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007450 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007451 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007452 continue;
7453 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307454 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007455 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7456 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7457 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007458 if (mute) {
7459 // FIXME: should not need to double latency if volume could be applied
7460 // immediately by the audioflinger mixer. We must account for the delay
7461 // between now and the next time the audioflinger thread for this output
7462 // will process a buffer (which corresponds to one buffer size,
7463 // usually 1/2 or 1/4 of the latency).
7464 if (muteWaitMs < desc->latency() * 2) {
7465 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007466 }
7467 }
7468 }
7469 }
7470 }
7471 }
7472
Eric Laurent99401132014-05-07 19:48:15 -07007473 // temporary mute output if device selection changes to avoid volume bursts due to
7474 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007475 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007476 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007477
Eric Laurentdc462862016-07-19 12:29:53 -07007478 if (muteWaitMs < tempMuteWaitMs) {
7479 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007480 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007481
7482 // If recommended duration is defined, replace temporary mute duration to avoid
7483 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7484 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7485 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7486 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7487 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7488
François Gaffieaaac0fd2018-11-22 17:56:39 +01007489 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7490 // make sure that we do not start the temporary mute period too early in case of
7491 // delayed device change
7492 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7493 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007494 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007495 }
7496 }
7497
Eric Laurente552edb2014-03-10 17:42:56 -07007498 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7499 if (muteWaitMs > delayMs) {
7500 muteWaitMs -= delayMs;
7501 usleep(muteWaitMs * 1000);
7502 return muteWaitMs;
7503 }
7504 return 0;
7505}
7506
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307507uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7508 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007509 const DeviceVector &devices,
7510 bool force,
7511 int delayMs,
7512 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007513 bool requiresMuteCheck, bool requiresVolumeCheck,
7514 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007515{
jiabin3ff8d7d2022-12-13 06:27:44 +00007516 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307517 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7518 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7519 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007520 uint32_t muteWaitMs;
7521
7522 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307523 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007524 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307525 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007526 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007527 return muteWaitMs;
7528 }
Eric Laurente552edb2014-03-10 17:42:56 -07007529
7530 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007531 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007532 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007533 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007534
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307535 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7536 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007537
7538 if (!filteredDevices.isEmpty()) {
7539 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007540 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007541
7542 // if the outputs are not materially active, there is no need to mute.
7543 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007544 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007545 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307546 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7547 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007548 muteWaitMs = 0;
7549 }
Eric Laurente552edb2014-03-10 17:42:56 -07007550
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007551 bool outputRouted = outputDesc->isRouted();
7552
Eric Laurent79ea9582020-06-11 18:49:24 -07007553 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7554 // output profile or if new device is not supported AND previous device(s) is(are) still
7555 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007556 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307557 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7558 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007559 // restore previous device after evaluating strategy mute state
7560 outputDesc->setDevices(prevDevices);
7561 return muteWaitMs;
7562 }
7563
Eric Laurente552edb2014-03-10 17:42:56 -07007564 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007565 // the requested device is AUDIO_DEVICE_NONE
7566 // OR the requested device is the same as current device
7567 // AND force is not specified
7568 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007569 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007570 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307571 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7572 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7573 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007574 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307575 ALOGV("%s %s setting same device on routed output, force apply volumes",
7576 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007577 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7578 }
Eric Laurente552edb2014-03-10 17:42:56 -07007579 return muteWaitMs;
7580 }
7581
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307582 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7583 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007584
Eric Laurente552edb2014-03-10 17:42:56 -07007585 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007586 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007587 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007588 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007589 PatchBuilder patchBuilder;
7590 patchBuilder.addSource(outputDesc);
7591 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7592 for (const auto &filteredDevice : filteredDevices) {
7593 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007594 }
7595
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007596 // Add half reported latency to delayMs when muteWaitMs is null in order
7597 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007598 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7599 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7600 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007601 }
Eric Laurente552edb2014-03-10 17:42:56 -07007602
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007603 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7604 if (!skipMuteDelay) {
7605 // update stream volumes according to new device
7606 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7607 }
Eric Laurente552edb2014-03-10 17:42:56 -07007608
7609 return muteWaitMs;
7610}
7611
Eric Laurentc75307b2015-03-17 15:29:32 -07007612status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007613 int delayMs,
7614 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007615{
Eric Laurent6a94d692014-05-20 11:18:06 -07007616 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007617 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7618 return INVALID_OPERATION;
7619 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007620 if (patchHandle) {
7621 index = mAudioPatches.indexOfKey(*patchHandle);
7622 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007623 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007624 }
7625 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007626 return INVALID_OPERATION;
7627 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007628 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007629 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007630 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007631 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007632 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007633 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007634 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007635 return status;
7636}
7637
7638status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007639 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007640 bool force,
7641 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007642{
7643 status_t status = NO_ERROR;
7644
Eric Laurent1f2f2232014-06-02 12:01:23 -07007645 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007646 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7647 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007648
François Gaffie11d30102018-11-02 16:09:09 +01007649 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007650 PatchBuilder patchBuilder;
7651 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007652 // AUDIO_SOURCE_HOTWORD is for internal use only:
7653 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007654 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7655 auto result = usecase;
7656 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7657 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7658 }
7659 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007660 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007661 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007662 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007663 }
7664 }
7665 return status;
7666}
7667
Eric Laurent6a94d692014-05-20 11:18:06 -07007668status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7669 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007670{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007671 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007672 ssize_t index;
7673 if (patchHandle) {
7674 index = mAudioPatches.indexOfKey(*patchHandle);
7675 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007676 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007677 }
7678 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007679 return INVALID_OPERATION;
7680 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007681 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007682 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007683 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007684 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007685 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007686 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007687 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007688 return status;
7689}
7690
François Gaffie11d30102018-11-02 16:09:09 +01007691sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007692 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007693 audio_format_t& format,
7694 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007695 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007696{
7697 // Choose an input profile based on the requested capture parameters: select the first available
7698 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007699 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007700 //
7701 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7702 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007703
Atneya Nair0f0a8032022-12-12 16:20:12 -08007704 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7705 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7706 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7707
7708 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007709
jiabin2fd710d2022-05-02 23:20:22 +00007710 for (;;) {
7711 sp<IOProfile> firstInexact = nullptr;
7712 uint32_t updatedSamplingRate = 0;
7713 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7714 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7715 for (const auto& hwModule : mHwModules) {
7716 for (const auto& profile : hwModule->getInputProfiles()) {
7717 // profile->log();
7718 //updatedFormat = format;
7719 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7720 &samplingRate /*updatedSamplingRate*/,
7721 format,
7722 &format, /*updatedFormat*/
7723 channelMask,
7724 &channelMask /*updatedChannelMask*/,
7725 // FIXME ugly cast
7726 (audio_output_flags_t) flags,
7727 true /*exactMatchRequiredForInputFlags*/)) {
7728 return profile;
7729 }
7730 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7731 samplingRate,
7732 &updatedSamplingRate,
7733 format,
7734 &updatedFormat,
7735 channelMask,
7736 &updatedChannelMask,
7737 // FIXME ugly cast
7738 (audio_output_flags_t) flags,
7739 false /*exactMatchRequiredForInputFlags*/)) {
7740 firstInexact = profile;
7741 }
7742 }
7743 }
7744
7745 if (firstInexact != nullptr) {
7746 samplingRate = updatedSamplingRate;
7747 format = updatedFormat;
7748 channelMask = updatedChannelMask;
7749 return firstInexact;
7750 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7751 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7752 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7753 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7754 flags = AUDIO_INPUT_FLAG_NONE;
7755 } else { // fail
7756 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7757 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7758 samplingRate, format, channelMask, oriFlags);
7759 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007760 }
7761 }
jiabin2fd710d2022-05-02 23:20:22 +00007762
7763 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007764}
7765
François Gaffieaaac0fd2018-11-22 17:56:39 +01007766float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7767 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007768 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007769 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007770{
jiabin9a3361e2019-10-01 09:38:30 -07007771 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007772
7773 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7774 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7775 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7776 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007777 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7778 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7779 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7780 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7781 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007782 // Verify that the current volume source is not the ringer volume to prevent recursively
7783 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7784 // to the same volume group.
7785 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007786 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7787 mOutputs.isActive(ringVolumeSrc, 0)) {
7788 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007789 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007790 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007791 }
7792
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007793 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007794 if ((volumeSource != callVolumeSrc && (isInCall() ||
7795 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007796 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007797 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7798 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007799 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7800 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7801 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007802 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007803 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007804 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007805 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007806 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007807 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007808 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7809 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7810 // programmatically muted.
7811 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7812 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7813 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007814 bool exemptFromCapping =
7815 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7816 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007817 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7818 volumeSource, volumeDb);
7819 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007820 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7821 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7822 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007823 }
7824 }
Eric Laurente552edb2014-03-10 17:42:56 -07007825 // if a headset is connected, apply the following rules to ring tones and notifications
7826 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007827 // - always attenuate notifications volume by 6dB
7828 // - attenuate ring tones volume by 6dB unless music is not playing and
7829 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007830 // - if music is playing, always limit the volume to current music volume,
7831 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007832 if (!Intersection(deviceTypes,
7833 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7834 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007835 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7836 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007837 ((volumeSource == alarmVolumeSrc ||
7838 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007839 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7840 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7841 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007842 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7843 curves.canBeMuted()) {
7844
Eric Laurente552edb2014-03-10 17:42:56 -07007845 // when the phone is ringing we must consider that music could have been paused just before
7846 // by the music application and behave as if music was active if the last music track was
7847 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007848 // Verify that the current volume source is not the music volume to prevent recursively
7849 // calling to compute volume. This could happen in cases where music and
7850 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7851 if (volumeSource != musicVolumeSrc &&
7852 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7853 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007854 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007855 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007856 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7857 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007858 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007859 float musicVolDb = computeVolume(musicCurves,
7860 musicVolumeSrc,
7861 musicCurves.getVolumeIndex(musicDevice),
7862 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007863 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7864 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7865 if (volumeDb > minVolDb) {
7866 volumeDb = minVolDb;
7867 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007868 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007869 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7870 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7871 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007872 // on A2DP, also ensure notification volume is not too low compared to media when
7873 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007874 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007875 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007876 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7877 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007878 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7879 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007880 }
7881 }
jiabin9a3361e2019-10-01 09:38:30 -07007882 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007883 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007884 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007885 }
7886 }
7887
François Gaffie43c73442018-11-08 08:21:55 +01007888 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007889}
7890
Eric Laurent3839bc02018-07-10 18:33:34 -07007891int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007892 VolumeSource fromVolumeSource,
7893 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007894{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007895 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007896 return srcIndex;
7897 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007898 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7899 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007900 float minSrc = (float)srcCurves.getVolumeIndexMin();
7901 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7902 float minDst = (float)dstCurves.getVolumeIndexMin();
7903 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007904
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007905 // preserve mute request or correct range
7906 if (srcIndex < minSrc) {
7907 if (srcIndex == 0) {
7908 return 0;
7909 }
7910 srcIndex = minSrc;
7911 } else if (srcIndex > maxSrc) {
7912 srcIndex = maxSrc;
7913 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007914 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7915}
7916
François Gaffieaaac0fd2018-11-22 17:56:39 +01007917status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7918 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007919 int index,
7920 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007921 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007922 int delayMs,
7923 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007924{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007925 // do not change actual attributes volume if the attributes is muted
7926 if (outputDesc->isMuted(volumeSource)) {
7927 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7928 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007929 return NO_ERROR;
7930 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007931
Eric Laurentae6e88c2024-01-10 14:42:57 +01007932 bool isVoiceVolSrc;
7933 bool isBtScoVolSrc;
7934 if (!isVolumeConsistentForCalls(
7935 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007936 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01007937 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007938 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007939 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01007940
jiabin9a3361e2019-10-01 09:38:30 -07007941 if (deviceTypes.empty()) {
7942 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007943 index = curves.getVolumeIndex(deviceTypes);
7944 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7945 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007946 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007947
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007948 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7949 ALOGE("invalid volume index range");
7950 return BAD_VALUE;
7951 }
7952
jiabin9a3361e2019-10-01 09:38:30 -07007953 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7954 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007955 // Force VoIP volume to max for bluetooth SCO device except if muted
7956 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007957 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007958 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007959 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007960 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007961 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7962 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007963
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007964 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01007965 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007966 }
Eric Laurente552edb2014-03-10 17:42:56 -07007967 return NO_ERROR;
7968}
7969
Eric Laurentae6e88c2024-01-10 14:42:57 +01007970void AudioPolicyManager::setVoiceVolume(
7971 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7972 float voiceVolume;
7973 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7974 // by the headset
7975 if (isVoiceVolSrc) {
7976 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7977 } else {
7978 voiceVolume = index == 0 ? 0.0 : 1.0;
7979 }
7980 if (voiceVolume != mLastVoiceVolume) {
7981 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7982 mLastVoiceVolume = voiceVolume;
7983 }
7984}
7985
7986bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
7987 const DeviceTypeSet& deviceTypes,
7988 bool& isVoiceVolSrc,
7989 bool& isBtScoVolSrc,
7990 const char* caller) {
7991 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7992 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7993 const bool isScoRequested = isScoRequestedForComm();
7994 const bool isHAUsed = isHearingAidUsedForComm();
7995
7996 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7997 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
7998
7999 if ((callVolSrc != btScoVolSrc) &&
8000 ((isVoiceVolSrc && isScoRequested) ||
8001 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8002 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8003 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8004 volumeSource, isScoRequested ? " " : " not ");
8005 return false;
8006 }
8007 return true;
8008}
8009
Eric Laurentc75307b2015-03-17 15:29:32 -07008010void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008011 const DeviceTypeSet& deviceTypes,
8012 int delayMs,
8013 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008014{
jiabincd510522020-01-22 09:40:55 -08008015 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008016 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8017 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8018 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008019 curves.getVolumeIndex(deviceTypes),
8020 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008021 }
8022}
8023
François Gaffiec005e562018-11-06 15:04:49 +01008024void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8025 bool on,
8026 const sp<AudioOutputDescriptor>& outputDesc,
8027 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008028 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008029{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008030 std::vector<VolumeSource> sourcesToMute;
8031 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8032 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8033 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008034 VolumeSource source = toVolumeSource(attributes, false);
8035 if ((source != VOLUME_SOURCE_NONE) &&
8036 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8037 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008038 sourcesToMute.push_back(source);
8039 }
Eric Laurente552edb2014-03-10 17:42:56 -07008040 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008041 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008042 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008043 }
8044
Eric Laurente552edb2014-03-10 17:42:56 -07008045}
8046
François Gaffieaaac0fd2018-11-22 17:56:39 +01008047void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8048 bool on,
8049 const sp<AudioOutputDescriptor>& outputDesc,
8050 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008051 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008052{
jiabin9a3361e2019-10-01 09:38:30 -07008053 if (deviceTypes.empty()) {
8054 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008055 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008056 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008057 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008058 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008059 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008060 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008061 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8062 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008063 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008064 }
8065 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008066 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8067 // ignored
8068 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008069 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008070 if (!outputDesc->isMuted(volumeSource)) {
8071 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008072 return;
8073 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008074 if (outputDesc->decMuteCount(volumeSource) == 0) {
8075 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008076 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008077 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008078 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008079 delayMs);
8080 }
8081 }
8082}
8083
François Gaffie53615e22015-03-19 09:24:12 +01008084bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8085{
François Gaffiec005e562018-11-06 15:04:49 +01008086 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008087 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8088 return true;
8089 }
8090
8091 // has known usage?
8092 switch (paa->usage) {
8093 case AUDIO_USAGE_UNKNOWN:
8094 case AUDIO_USAGE_MEDIA:
8095 case AUDIO_USAGE_VOICE_COMMUNICATION:
8096 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8097 case AUDIO_USAGE_ALARM:
8098 case AUDIO_USAGE_NOTIFICATION:
8099 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8100 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8101 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8102 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8103 case AUDIO_USAGE_NOTIFICATION_EVENT:
8104 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8105 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8106 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8107 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008108 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008109 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008110 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008111 case AUDIO_USAGE_EMERGENCY:
8112 case AUDIO_USAGE_SAFETY:
8113 case AUDIO_USAGE_VEHICLE_STATUS:
8114 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008115 break;
8116 default:
8117 return false;
8118 }
8119 return true;
8120}
8121
François Gaffie2110e042015-03-24 08:41:51 +01008122audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8123{
8124 return mEngine->getForceUse(usage);
8125}
8126
Eric Laurent96d1dda2022-03-14 17:14:19 +01008127bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008128 return isStateInCall(mEngine->getPhoneState());
8129}
8130
Eric Laurent96d1dda2022-03-14 17:14:19 +01008131bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008132 return is_state_in_call(state);
8133}
8134
Eric Laurentf9cccec2022-11-16 19:12:00 +01008135bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008136 audio_mode_t mode = mEngine->getPhoneState();
8137 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008138 || (mode == AUDIO_MODE_CALL_SCREEN)
8139 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008140}
8141
Eric Laurentf9cccec2022-11-16 19:12:00 +01008142bool AudioPolicyManager::isInCallOrScreening() const {
8143 audio_mode_t mode = mEngine->getPhoneState();
8144 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8145}
8146
Eric Laurentd60560a2015-04-10 11:31:20 -07008147void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8148{
8149 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008150 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008151 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008152 sourceDesc->sinkDevice()->equals(deviceDesc))
8153 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008154 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008155 }
8156 }
8157
8158 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8159 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8160 bool release = false;
8161 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8162 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8163 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8164 source->ext.device.type == deviceDesc->type()) {
8165 release = true;
8166 }
8167 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008168 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008169 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8170 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8171 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008172 sink->ext.device.type == deviceDesc->type() &&
8173 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8174 || strncmp(sink->ext.device.address, address,
8175 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008176 release = true;
8177 }
8178 }
8179 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008180 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8181 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008182 }
8183 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008184
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008185 mInputs.clearSessionRoutesForDevice(deviceDesc);
8186
Francois Gaffie716e1432019-01-14 16:58:59 +01008187 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008188}
8189
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008190void AudioPolicyManager::modifySurroundFormats(
8191 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008192 std::unordered_set<audio_format_t> enforcedSurround(
8193 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008194 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008195 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008196 allSurround.insert(pair.first);
8197 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8198 }
Phil Burk09bc4612016-02-24 15:58:15 -08008199
8200 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8201 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008202 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008203 // This is the resulting set of formats depending on the surround mode:
8204 // 'all surround' = allSurround
8205 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8206 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8207 // 'manual surround' = mManualSurroundFormats
8208 // AUTO: formats v 'enforced surround'
8209 // ALWAYS: formats v 'all surround' v 'enforced surround'
8210 // NEVER: formats ^ 'non-surround'
8211 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008212
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008213 std::unordered_set<audio_format_t> formatSet;
8214 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8215 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008216 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008217 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008218 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008219 formatSet.insert(*formatIter);
8220 }
8221 }
8222 } else {
8223 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8224 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008225 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008226
jiabin81772902018-04-02 17:52:27 -07008227 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008228 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008229 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8230 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8231 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008232 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008233 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8234 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8235 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008236 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008237 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008238 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008239 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008240 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008241 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008242}
8243
jiabin06e4bab2019-07-29 10:13:34 -07008244void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8245 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008246 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8247 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8248
8249 // If NEVER, then remove support for channelMasks > stereo.
8250 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008251 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8252 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008253 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008254 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008255 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008256 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008257 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008258 }
8259 }
jiabin81772902018-04-02 17:52:27 -07008260 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8261 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8262 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008263 bool supports5dot1 = false;
8264 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008265 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008266 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8267 supports5dot1 = true;
8268 break;
8269 }
8270 }
8271 // If not then add 5.1 support.
8272 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008273 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008274 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008275 }
Phil Burk09bc4612016-02-24 15:58:15 -08008276 }
8277}
8278
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008279void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008280 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008281 const sp<IOProfile>& profile) {
8282 if (!profile->hasDynamicAudioProfile()) {
8283 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008284 }
François Gaffie112b0af2015-11-19 16:13:25 +01008285
jiabin12537fc2023-10-12 17:56:08 +00008286 audio_port_v7 devicePort;
8287 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008288
jiabin12537fc2023-10-12 17:56:08 +00008289 audio_port_v7 mixPort;
8290 profile->toAudioPort(&mixPort);
8291 mixPort.ext.mix.handle = ioHandle;
8292
8293 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8294 if (status != NO_ERROR) {
8295 ALOGE("%s failed to query the attributes of the mix port", __func__);
8296 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008297 }
jiabin12537fc2023-10-12 17:56:08 +00008298
8299 std::set<audio_format_t> supportedFormats;
8300 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8301 supportedFormats.insert(mixPort.audio_profiles[i].format);
8302 }
8303 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8304 mReportedFormatsMap[devDesc] = formats;
8305
8306 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8307 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8308 modifySurroundFormats(devDesc, &formats);
8309 size_t modifiedNumProfiles = 0;
8310 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8311 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8312 formats.end()) {
8313 // Skip the format that is not present after modifying surround formats.
8314 continue;
8315 }
8316 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8317 sizeof(struct audio_profile));
8318 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8319 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8320 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8321 modifySurroundChannelMasks(&channels);
8322 std::copy(channels.begin(), channels.end(),
8323 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8324 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8325 }
8326 mixPort.num_audio_profiles = modifiedNumProfiles;
8327 }
8328 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008329}
Eric Laurentd60560a2015-04-10 11:31:20 -07008330
Mikhail Naganovdc769682018-05-04 15:34:08 -07008331status_t AudioPolicyManager::installPatch(const char *caller,
8332 audio_patch_handle_t *patchHandle,
8333 AudioIODescriptorInterface *ioDescriptor,
8334 const struct audio_patch *patch,
8335 int delayMs)
8336{
8337 ssize_t index = mAudioPatches.indexOfKey(
8338 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8339 *patchHandle : ioDescriptor->getPatchHandle());
8340 sp<AudioPatch> patchDesc;
8341 status_t status = installPatch(
8342 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8343 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008344 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008345 }
8346 return status;
8347}
8348
8349status_t AudioPolicyManager::installPatch(const char *caller,
8350 ssize_t index,
8351 audio_patch_handle_t *patchHandle,
8352 const struct audio_patch *patch,
8353 int delayMs,
8354 uid_t uid,
8355 sp<AudioPatch> *patchDescPtr)
8356{
8357 sp<AudioPatch> patchDesc;
8358 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8359 if (index >= 0) {
8360 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008361 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008362 }
8363
8364 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8365 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8366 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8367 if (status == NO_ERROR) {
8368 if (index < 0) {
8369 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008370 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008371 } else {
8372 patchDesc->mPatch = *patch;
8373 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008374 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008375 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008376 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008377 }
8378 nextAudioPortGeneration();
8379 mpClientInterface->onAudioPatchListUpdate();
8380 }
8381 if (patchDescPtr) *patchDescPtr = patchDesc;
8382 return status;
8383}
8384
jiabinbce0c1d2020-10-05 11:20:18 -07008385bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8386{
8387 const TrackClientVector activeClients = output->getActiveClients();
8388 if (activeClients.empty()) {
8389 return true;
8390 }
8391 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8392 if (index < 0) {
8393 ALOGE("%s, no audio patch found while there are active clients on output %d",
8394 __func__, output->getId());
8395 return false;
8396 }
8397 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8398 DeviceVector routedDevices;
8399 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8400 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8401 patchDesc->mPatch.sinks[i].id);
8402 if (device == nullptr) {
8403 ALOGE("%s, no audio device found with id(%d)",
8404 __func__, patchDesc->mPatch.sinks[i].id);
8405 return false;
8406 }
8407 routedDevices.add(device);
8408 }
8409 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008410 if (client->isInvalid()) {
8411 // No need to take care about invalidated clients.
8412 continue;
8413 }
jiabinbce0c1d2020-10-05 11:20:18 -07008414 sp<DeviceDescriptor> preferredDevice =
8415 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8416 if (mEngine->getOutputDevicesForAttributes(
8417 client->attributes(), preferredDevice, false) == routedDevices) {
8418 return false;
8419 }
8420 }
8421 return true;
8422}
8423
8424sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008425 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008426 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8427 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008428{
8429 for (const auto& device : devices) {
8430 // TODO: This should be checking if the profile supports the device combo.
8431 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008432 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8433 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008434 return nullptr;
8435 }
8436 }
8437 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8438 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008439 status_t status = desc->open(halConfig, mixerConfig, devices,
8440 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008441 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008442 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008443 return nullptr;
8444 }
jiabin14b50cc2023-12-13 19:01:52 +00008445 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8446 auto portConfig = desc->getConfig();
8447 for (const auto& device : devices) {
8448 device->setPreferredConfig(&portConfig);
8449 }
8450 }
jiabinbce0c1d2020-10-05 11:20:18 -07008451
8452 // Here is where the out_set_parameters() for card & device gets called
8453 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8454 const audio_devices_t deviceType = device->type();
8455 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008456 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008457 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8458 mpClientInterface->setParameters(output, String8(param));
8459 free(param);
8460 }
jiabin12537fc2023-10-12 17:56:08 +00008461 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008462 if (!profile->hasValidAudioProfile()) {
8463 ALOGW("%s() missing param", __func__);
8464 desc->close();
8465 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008466 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8467 // Reopen the output with the best audio profile picked by APM when the profile supports
8468 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008469 desc->close();
8470 output = AUDIO_IO_HANDLE_NONE;
8471 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8472 profile->pickAudioProfile(
8473 config.sample_rate, config.channel_mask, config.format);
8474 config.offload_info.sample_rate = config.sample_rate;
8475 config.offload_info.channel_mask = config.channel_mask;
8476 config.offload_info.format = config.format;
8477
jiabina84c3d32022-12-02 18:59:55 +00008478 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008479 if (status != NO_ERROR) {
8480 return nullptr;
8481 }
8482 }
8483
8484 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008485
baek.kim -61c20122022-07-27 10:05:32 +00008486 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8487 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8488
jiabinbce0c1d2020-10-05 11:20:18 -07008489 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8490 sp<AudioPolicyMix> policyMix;
8491 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8492 policyMix->setOutput(desc);
8493 desc->mPolicyMix = policyMix;
8494 } else {
8495 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008496 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008497 }
8498
baek.kim -61c20122022-07-27 10:05:32 +00008499 } else if (hasPrimaryOutput() && speaker != nullptr
8500 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008501 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8502 // no duplicated output for:
8503 // - direct outputs
8504 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008505 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008506 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8507
8508 //TODO: configure audio effect output stage here
8509
8510 // open a duplicating output thread for the new output and the primary output
8511 sp<SwAudioOutputDescriptor> dupOutputDesc =
8512 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8513 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8514 if (status == NO_ERROR) {
8515 // add duplicated output descriptor
8516 addOutput(duplicatedOutput, dupOutputDesc);
8517 } else {
8518 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8519 mPrimaryOutput->mIoHandle, output);
8520 desc->close();
8521 removeOutput(output);
8522 nextAudioPortGeneration();
8523 return nullptr;
8524 }
8525 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008526 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8527 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8528 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008529 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008530 }
jiabinbce0c1d2020-10-05 11:20:18 -07008531 return desc;
8532}
8533
jiabinf1c73972022-04-14 16:28:52 -07008534status_t AudioPolicyManager::getDevicesForAttributes(
8535 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8536 // Devices are determined in the following precedence:
8537 //
8538 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8539 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8540 //
8541 // If no such dynamic policy then
8542 // 2) Devices containing an active client using setPreferredDevice
8543 // with same strategy as the attributes.
8544 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8545 //
8546 // If no corresponding active client with setPreferredDevice then
8547 // 3) Devices associated with the strategy determined by the attributes
8548 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8549 //
8550 // See related getOutputForAttrInt().
8551
8552 // check dynamic policies but only for primary descriptors (secondary not used for audible
8553 // audio routing, only used for duplication for playback capture)
8554 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008555 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008556 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008557 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8558 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8559 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008560 if (status != OK) {
8561 return status;
8562 }
8563
8564 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8565 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8566 // as they are unaffected by device/stream volume
8567 // (per SwAudioOutputDescriptor::isFixedVolume()).
8568 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8569 ) {
8570 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8571 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8572 devices.add(deviceDesc);
8573 } else {
8574 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8575 // which selects setPreferredDevice if active. This means forVolume call
8576 // will take an active setPreferredDevice, if such exists.
8577
8578 devices = mEngine->getOutputDevicesForAttributes(
8579 attr, nullptr /* preferredDevice */, false /* fromCache */);
8580 }
8581
8582 if (forVolume) {
8583 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8584 // for single volume control in AudioService (such relationship should exist if
8585 // SPEAKER_SAFE is present).
8586 //
8587 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8588 DeviceVector speakerSafeDevices =
8589 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8590 if (!speakerSafeDevices.isEmpty()) {
8591 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8592 devices.remove(speakerSafeDevices);
8593 }
8594 }
8595
8596 return NO_ERROR;
8597}
8598
8599status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8600 AudioProfileVector& audioProfiles,
8601 uint32_t flags,
8602 bool isInput) {
8603 for (const auto& hwModule : mHwModules) {
8604 // the MSD module checks for different conditions
8605 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8606 continue;
8607 }
8608 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8609 : hwModule->getOutputProfiles();
8610 for (const auto& profile : ioProfiles) {
8611 if (!profile->areAllDevicesSupported(devices) ||
8612 !profile->isCompatibleProfileForFlags(
8613 flags, false /*exactMatchRequiredForInputFlags*/)) {
8614 continue;
8615 }
8616 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8617 }
8618 }
8619
8620 if (!isInput) {
8621 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8622 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8623 if (msdModule != nullptr) {
8624 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8625 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8626 for (const auto &profile: msdModule->getOutputProfiles()) {
8627 if (!profile->asAudioPort()->isDirectOutput()) {
8628 continue;
8629 }
8630 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8631 }
8632 } else {
8633 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8634 }
8635 }
8636 }
8637
8638 return NO_ERROR;
8639}
8640
jiabin3ff8d7d2022-12-13 06:27:44 +00008641sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8642 const audio_config_t *config,
8643 audio_output_flags_t flags,
8644 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008645 closeOutput(outputDesc->mIoHandle);
8646 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8647 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8648 if (preferredOutput == nullptr) {
8649 ALOGE("%s failed to reopen output device=%d, caller=%s",
8650 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008651 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008652 return preferredOutput;
8653}
8654
8655void AudioPolicyManager::reopenOutputsWithDevices(
8656 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8657 for (const auto& [output, devices] : outputsToReopen) {
8658 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8659 closeOutput(output);
8660 openOutputWithProfileAndDevice(desc->mProfile, devices);
8661 }
jiabina84c3d32022-12-02 18:59:55 +00008662}
8663
jiabinc44b3462022-12-08 12:52:31 -08008664PortHandleVector AudioPolicyManager::getClientsForStream(
8665 audio_stream_type_t streamType) const {
8666 PortHandleVector clients;
8667 for (size_t i = 0; i < mOutputs.size(); ++i) {
8668 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8669 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8670 }
8671 return clients;
8672}
8673
8674void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8675 PortHandleVector clients;
8676 for (auto stream : streams) {
8677 PortHandleVector clientsForStream = getClientsForStream(stream);
8678 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8679 }
8680 mpClientInterface->invalidateTracks(clients);
8681}
8682
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008683} // namespace android