blob: 87b6c3d351b70d16ef1c53cc19b0f297a97c2405 [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>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700377 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700378 } // end if is output device
379
Eric Laurente552edb2014-03-10 17:42:56 -0700380 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700381 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100382 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700383 switch (state)
384 {
385 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700386 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100388 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700389 return INVALID_OPERATION;
390 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700391
392 if (mAvailableInputDevices.add(device) < 0) {
393 return NO_MEMORY;
394 }
395
François Gaffie44481e72016-04-20 07:49:57 +0200396 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
397 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200399
Eric Laurent0dd51852019-04-19 18:18:58 -0700400 if (checkInputsForDevice(device, state) != NO_ERROR) {
401 mAvailableInputDevices.remove(device);
402
jiabinc0048632023-04-27 22:04:31 +0000403 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100404
405 mHwModules.cleanUpForDevice(device);
406
Eric Laurentd4692962014-05-05 18:13:44 -0700407 return INVALID_OPERATION;
408 }
409
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700413 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700414 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100415 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700416 return INVALID_OPERATION;
417 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700420
jiabinc0048632023-04-27 22:04:31 +0000421 // Notify the HAL to prepare to disconnect device
422 broadcastDeviceConnectionState(
423 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700424
François Gaffie11d30102018-11-02 16:09:09 +0100425 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700426
427 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100428
jiabinc0048632023-04-27 22:04:31 +0000429 // Set Disconnect to HALs
430 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
431
Kriti Dangef6be8f2020-11-05 11:58:19 +0100432 // remove device from mReportedFormatsMap cache
433 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700434 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700435
436 default:
François Gaffie11d30102018-11-02 16:09:09 +0100437 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700438 return BAD_VALUE;
439 }
440
Eric Laurent736a1022019-03-27 18:28:46 -0700441 // Propagate device availability to Engine
442 setEngineDeviceConnectionState(device, state);
443
Eric Laurent0dd51852019-04-19 18:18:58 -0700444 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700445 // As the input device list can impact the output device selection, update
446 // getDeviceForStrategy() cache
447 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700448
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100449 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200450 // Reconnect Audio Source
451 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
452 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
453 checkAudioSourceForAttributes(attributes);
454 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700455 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100456 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700457 }
458
Eric Laurentb52c1522014-05-20 11:27:36 -0700459 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700460 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700461 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700462
François Gaffie11d30102018-11-02 16:09:09 +0100463 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700464 return BAD_VALUE;
465}
466
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100467status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
468 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800469 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700470 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
471 devDescr->setName(device_name);
472 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100473}
474
Eric Laurent736a1022019-03-27 18:28:46 -0700475void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
476 audio_policy_dev_state_t state) {
477
478 // the Engine does not have to know about remote submix devices used by dynamic audio policies
479 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
480 return;
481 }
482 mEngine->setDeviceConnectionState(device, state);
483}
484
485
Eric Laurente0720872014-03-11 09:30:41 -0700486audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100487 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700488{
Eric Laurent634b7142016-04-20 13:48:02 -0700489 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800490 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
491 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700492 (strlen(device_address) != 0)/*matchAddress*/);
493
494 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100495 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700496 device, device_address);
497 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
498 }
François Gaffie53615e22015-03-19 09:24:12 +0100499
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 DeviceVector *deviceVector;
501
Eric Laurente552edb2014-03-10 17:42:56 -0700502 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700503 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700504 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700505 deviceVector = &mAvailableInputDevices;
506 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100507 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700509 }
Eric Laurent634b7142016-04-20 13:48:02 -0700510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 return (deviceVector->getDevice(
512 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700513 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800514}
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
517 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 const char *device_name,
519 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800521 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
522 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800524 // connect/disconnect only 1 device at a time
525 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
526
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700528 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800530 // Nothing to do: device is not connected
531 return NO_ERROR;
532 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800534
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700535 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800536 // configure codecs.
537 // Handle two specific cases by sending a set parameter to
538 // configure A2DP codecs. No need to toggle device state.
539 // Case 1: A2DP active device switches from primary to primary
540 // module
541 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100542 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700543 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
545 if (availablePrimaryOutputDevices().contains(devDesc) &&
546 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 bool isA2dp = audio_is_a2dp_out_device(device);
548 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
549 : String8(AudioParameter::keyReconfigLeSupported);
550 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100552 int isReconfigSupported;
553 repliedParameters.getInt(supportKey, isReconfigSupported);
554 if (isReconfigSupported) {
555 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
556 : String8(AudioParameter::keyReconfigLe);
557 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800558 param.add(key, String8("true"));
559 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
560 devDesc->setEncodedFormat(encodedFormat);
561 return NO_ERROR;
562 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700563 }
564 }
cnx421bd2dcc42020-07-11 14:58:44 +0800565 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000566 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800567 for (size_t i = 0; i < mOutputs.size(); i++) {
568 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000569 // mute media strategies to avoid sending the music tail into
570 // the earpiece or headset.
571 if (desc->isStrategyActive(musicStrategy)) {
572 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
573 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
574 tempRecommendedMuteDuration : desc->latency() * 4;
575 if (muteWaitMs < tempMuteDurationMs) {
576 muteWaitMs = tempMuteDurationMs;
577 }
578 }
cnx421bd2dcc42020-07-11 14:58:44 +0800579 setStrategyMute(musicStrategy, true, desc);
580 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
581 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
582 nullptr, true /*fromCache*/).types());
583 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000584 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
585 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
586 // happens after the actual device switch.
587 if (muteWaitMs > 0) {
588 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
589 usleep(muteWaitMs * 1000);
590 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800591 // Toggle the device state: UNAVAILABLE -> AVAILABLE
592 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100593 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800594 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800595 device_address, device_name,
596 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800597 if (status != NO_ERROR) {
598 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
599 status);
600 return status;
601 }
602
603 status = setDeviceConnectionState(device,
604 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800605 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800606 if (status != NO_ERROR) {
607 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
608 status);
609 return status;
610 }
611
612 return NO_ERROR;
613}
614
Pattydd807582021-11-04 21:01:03 +0800615status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
616 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800617{
Pattydd807582021-11-04 21:01:03 +0800618 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800619 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800620 std::unordered_set<audio_format_t> formatSet;
621 sp<HwModule> primaryModule =
622 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700623 if (primaryModule == nullptr) {
624 ALOGE("%s() unable to get primary module", __func__);
625 return NO_INIT;
626 }
Pattydd807582021-11-04 21:01:03 +0800627
628 DeviceTypeSet audioDeviceSet;
629
630 switch(device) {
631 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
632 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
633 break;
634 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800635 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
636 break;
637 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
638 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800639 break;
640 default:
641 ALOGE("%s() device type 0x%08x not supported", __func__, device);
642 return BAD_VALUE;
643 }
644
jiabin9a3361e2019-10-01 09:38:30 -0700645 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800646 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800647 for (const auto& device : declaredDevices) {
648 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800649 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800650 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800651 return status;
652}
653
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100654DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
655{
656 DeviceVector rxSinkdevices{};
657 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
658 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
659 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
660 auto rxSinkDevice = rxSinkdevices.itemAt(0);
661 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
662 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
663 // retrieve Rx Source device descriptor
664 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
665 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
666
667 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
668 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
669 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
670 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
671 return DeviceVector(rxSinkDevice);
672 }
673 }
674 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
675 // the device returned is not necessarily reachable via this output
676 // (filter later by setOutputDevices())
677 return getNewOutputDevices(mPrimaryOutput, fromCache);
678}
679
680status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
681{
François Gaffiedb1755b2023-09-01 11:50:35 +0200682 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100683 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
684 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
685 }
686 return INVALID_OPERATION;
687}
688
689status_t AudioPolicyManager::updateCallRoutingInternal(
690 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691{
692 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100693 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700694 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200695 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700696 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100697 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700698 }
François Gaffie11d30102018-11-02 16:09:09 +0100699
Francois Gaffie716e1432019-01-14 16:58:59 +0100700 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100701 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200702
703 disconnectTelephonyAudioSource(mCallRxSourceClient);
704 disconnectTelephonyAudioSource(mCallTxSourceClient);
705
706 if (rxDevices.isEmpty()) {
707 ALOGW("%s() no selected output device", __func__);
708 return INVALID_OPERATION;
709 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000710 if (txSourceDevice == nullptr) {
711 ALOGE("%s() selected input device not available", __func__);
712 return INVALID_OPERATION;
713 }
François Gaffiec005e562018-11-06 15:04:49 +0100714
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100715 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100716 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700717
François Gaffie9eb18552018-11-05 10:33:26 +0100718 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700719 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100720 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700721 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100722 // retrieve Rx Source and Tx Sink device descriptors
723 sp<DeviceDescriptor> rxSourceDevice =
724 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
725 String8(),
726 AUDIO_FORMAT_DEFAULT);
727 sp<DeviceDescriptor> txSinkDevice =
728 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
729 String8(),
730 AUDIO_FORMAT_DEFAULT);
731
732 // RX and TX Telephony device are declared by Primary Audio HAL
733 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
734 (telephonyRxModule->getHalVersionMajor() >= 3)) {
735 if (rxSourceDevice == 0 || txSinkDevice == 0) {
736 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100737 ALOGE("%s() no telephony Tx and/or RX device", __func__);
738 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100739 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100740 // createAudioPatchInternal now supports both HW / SW bridging
741 createRxPatch = true;
742 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100743 } else {
744 // If the RX device is on the primary HW module, then use legacy routing method for
745 // voice calls via setOutputDevice() on primary output.
746 // Otherwise, create two audio patches for TX and RX path.
747 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
748 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700749 // If the TX device is also on the primary HW module, setOutputDevice() will take care
750 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100751 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
752 (txSinkDevice != 0);
753 }
754 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
755 // Otherwise, create two audio patches for TX and RX path.
756 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200757 if (!hasPrimaryOutput()) {
758 ALOGW("%s() no primary output available", __func__);
759 return INVALID_OPERATION;
760 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530761 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700762 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200763 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800764 // If the TX device is on the primary HW module but RX device is
765 // on other HW module, SinkMetaData of telephony input should handle it
766 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700767 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700768 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100769 // terminate active capture if on the same HW module as the call TX source device
770 // FIXME: would be better to refine to only inputs whose profile connects to the
771 // call TX device but this information is not in the audio patch and logic here must be
772 // symmetric to the one in startInput()
773 for (const auto& activeDesc : mInputs.getActiveInputs()) {
774 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
775 closeActiveClients(activeDesc);
776 }
777 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200778 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800779 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100780 if (waitMs != nullptr) {
781 *waitMs = muteWaitMs;
782 }
783 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800784}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700785
Mikhail Naganov100f0122018-11-29 11:22:16 -0800786bool AudioPolicyManager::isDeviceOfModule(
787 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
788 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
789 if (module != 0) {
790 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
791 .indexOf(devDesc) != NAME_NOT_FOUND
792 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
793 .indexOf(devDesc) != NAME_NOT_FOUND;
794 }
795 return false;
796}
797
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200798void AudioPolicyManager::connectTelephonyRxAudioSource()
799{
Francois Gaffie601801d2021-06-22 13:27:39 +0200800 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200801 const struct audio_port_config source = {
802 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
803 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
804 };
805 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100806
807 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
808 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
809 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
810 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200811 ALOGE_IF(mCallRxSourceClient == nullptr,
812 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200813}
814
Francois Gaffie601801d2021-06-22 13:27:39 +0200815void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200816{
Francois Gaffie601801d2021-06-22 13:27:39 +0200817 if (clientDesc == nullptr) {
818 return;
819 }
820 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
821 "%s error stopping audio source", __func__);
822 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200823}
824
825void AudioPolicyManager::connectTelephonyTxAudioSource(
826 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
827 uint32_t delayMs)
828{
Francois Gaffie601801d2021-06-22 13:27:39 +0200829 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200830 if (srcDevice == nullptr || sinkDevice == nullptr) {
831 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
832 return;
833 }
834 PatchBuilder patchBuilder;
835 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
836 ALOGV("%s between source %s and sink %s", __func__,
837 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200839 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
840
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200841 struct audio_port_config source = {};
842 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100843 mCallTxSourceClient = new SourceClientDescriptor(
844 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
845 mCommunnicationStrategy, toVolumeSource(aa), true);
846 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
847
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200848 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
849 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200850 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
851 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200852 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
853 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200855 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200856}
857
Eric Laurente0720872014-03-11 09:30:41 -0700858void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700859{
860 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100861 // store previous phone state for management of sonification strategy below
862 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100863 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100864
865 if (mEngine->setPhoneState(state) != NO_ERROR) {
866 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700867 return;
868 }
François Gaffie2110e042015-03-24 08:41:51 +0100869 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700870 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700871 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700872 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800873 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
875
François Gaffie2110e042015-03-24 08:41:51 +0100876 /**
877 * Switching to or from incall state or switching between telephony and VoIP lead to force
878 * routing command.
879 */
Eric Laurent74b71512019-11-06 17:21:57 -0800880 bool force = ((isStateInCall(oldState) != isStateInCall(state))
881 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700882
883 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700884 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700885
Eric Laurente552edb2014-03-10 17:42:56 -0700886 int delayMs = 0;
887 if (isStateInCall(state)) {
888 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100889 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
890 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700891 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700892 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700893 // mute media and sonification strategies and delay device switch by the largest
894 // latency of any output where either strategy is active.
895 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100896 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
897 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
898 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700899 (delayMs < (int)desc->latency()*2)) {
900 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700901 }
François Gaffiec005e562018-11-06 15:04:49 +0100902 setStrategyMute(musicStrategy, true, desc);
903 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
904 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
905 nullptr, true /*fromCache*/).types());
906 setStrategyMute(sonificationStrategy, true, desc);
907 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
908 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
909 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700910 }
911 }
912
François Gaffiedb1755b2023-09-01 11:50:35 +0200913 if (state == AUDIO_MODE_IN_CALL) {
914 (void)updateCallRouting(false /*fromCache*/, delayMs);
915 } else {
916 if (oldState == AUDIO_MODE_IN_CALL) {
917 disconnectTelephonyAudioSource(mCallRxSourceClient);
918 disconnectTelephonyAudioSource(mCallTxSourceClient);
919 }
920 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100921 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
922 // force routing command to audio hardware when ending call
923 // even if no device change is needed
924 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
925 rxDevices = mPrimaryOutput->devices();
926 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530927 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700928 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700929 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700930
jiabin3ff8d7d2022-12-13 06:27:44 +0000931 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700932 // reevaluate routing on all outputs in case tracks have been started during the call
933 for (size_t i = 0; i < mOutputs.size(); i++) {
934 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100935 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000936 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
937 && desc->mPreferredAttrInfo != nullptr) {
938 // If the output is using preferred mixer attributes and the audio mode is not normal,
939 // the output need to reopen with default configuration.
940 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
941 continue;
942 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200943 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
944 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530945 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200946 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700947 }
948 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000949 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700950
Eric Laurent96d1dda2022-03-14 17:14:19 +0100951 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
952
Eric Laurente552edb2014-03-10 17:42:56 -0700953 if (isStateInCall(state)) {
954 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700955 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800956 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700957 }
958
959 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100960 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
961 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700962}
963
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700964audio_mode_t AudioPolicyManager::getPhoneState() {
965 return mEngine->getPhoneState();
966}
967
Eric Laurente0720872014-03-11 09:30:41 -0700968void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100969 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700970{
François Gaffie2110e042015-03-24 08:41:51 +0100971 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700972 if (config == mEngine->getForceUse(usage)) {
973 return;
974 }
Eric Laurente552edb2014-03-10 17:42:56 -0700975
François Gaffie2110e042015-03-24 08:41:51 +0100976 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
977 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
978 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
François Gaffie2110e042015-03-24 08:41:51 +0100980 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
981 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
982 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700983
984 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700985 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800986
Eric Laurent22fcda22019-05-17 16:28:47 -0700987 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
988 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800989 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700990 }
991
Eric Laurentdc462862016-07-19 12:29:53 -0700992 //FIXME: workaround for truncated touch sounds
993 // to be removed when the problem is handled by system UI
994 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700995 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
996 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
997 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700998
999 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001000 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001001}
1002
Eric Laurente0720872014-03-11 09:30:41 -07001003void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001004{
1005 ALOGV("setSystemProperty() property %s, value %s", property, value);
1006}
1007
Dorin Drimusecc9f422022-03-09 17:57:40 +01001008// Find an MSD output profile compatible with the parameters passed.
1009// When "directOnly" is set, restrict search to profiles for direct outputs.
1010sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1011 const DeviceVector& devices,
1012 uint32_t samplingRate,
1013 audio_format_t format,
1014 audio_channel_mask_t channelMask,
1015 audio_output_flags_t flags,
1016 bool directOnly)
1017{
1018 flags = getRelevantFlags(flags, directOnly);
1019
1020 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1021 if (msdModule != nullptr) {
1022 // for the msd module check if there are patches to the output devices
1023 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1024 HwModuleCollection modules;
1025 modules.add(msdModule);
1026 return searchCompatibleProfileHwModules(
1027 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1028 flags, directOnly);
1029 }
1030 }
1031 return nullptr;
1032}
1033
Michael Chana94fbb22018-04-24 14:31:19 +10001034// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1035// search to profiles for direct outputs.
1036sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001037 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001038 uint32_t samplingRate,
1039 audio_format_t format,
1040 audio_channel_mask_t channelMask,
1041 audio_output_flags_t flags,
1042 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001043{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001044 flags = getRelevantFlags(flags, directOnly);
1045
1046 return searchCompatibleProfileHwModules(
1047 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1048}
1049
1050audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1051 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001052 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001053 // only retain flags that will drive the direct output profile selection
1054 // if explicitly requested
1055 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001056 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001057 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1058 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001059 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001060 return flags;
1061}
Eric Laurent861a6282015-05-18 15:40:16 -07001062
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1064 const HwModuleCollection& hwModules,
1065 const DeviceVector& devices,
1066 uint32_t samplingRate,
1067 audio_format_t format,
1068 audio_channel_mask_t channelMask,
1069 audio_output_flags_t flags,
1070 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001071 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001072 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001073 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001074 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001075 samplingRate, NULL /*updatedSamplingRate*/,
1076 format, NULL /*updatedFormat*/,
1077 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001078 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001079 continue;
1080 }
1081 // reject profiles not corresponding to a device currently available
1082 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1083 continue;
1084 }
1085 // reject profiles if connected device does not support codec
1086 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1087 continue;
1088 }
1089 if (!directOnly) {
1090 return curProfile;
1091 }
1092
1093 // when searching for direct outputs, if several profiles are compatible, give priority
1094 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001095 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001096 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001097 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001098 }
1099 profile = curProfile;
1100 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1101 break;
1102 }
Eric Laurente552edb2014-03-10 17:42:56 -07001103 }
1104 }
Eric Laurent861a6282015-05-18 15:40:16 -07001105 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001106}
1107
Eric Laurentfa0f6742021-08-17 18:39:44 +02001108sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001109 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001110{
1111 for (const auto& hwModule : mHwModules) {
1112 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001113 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001114 continue;
1115 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001116 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001117 // reject profiles not corresponding to a device currently available
1118 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1119 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1120 continue;
1121 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001122 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1123 != devices.size()) {
1124 continue;
1125 }
1126 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001127 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1128 return curProfile;
1129 }
1130 }
1131 return nullptr;
1132}
1133
Eric Laurentf4e63452017-11-06 19:31:46 +00001134audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001135{
François Gaffiec005e562018-11-06 15:04:49 +01001136 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001137
1138 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1139 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1140 // format, flags, etc. This may result in some discrepancy for functions that utilize
1141 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1142 // and AudioSystem::getOutputSamplingRate().
1143
François Gaffie11d30102018-11-02 16:09:09 +01001144 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001145 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1146 if (stream == AUDIO_STREAM_MUSIC &&
1147 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1148 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1149 }
1150 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001151
François Gaffie11d30102018-11-02 16:09:09 +01001152 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1153 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001154 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001155}
1156
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001157status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1158 const audio_attributes_t *srcAttr,
1159 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001160{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001161 if (srcAttr != NULL) {
1162 if (!isValidAttributes(srcAttr)) {
1163 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1164 __func__,
1165 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1166 srcAttr->tags);
1167 return BAD_VALUE;
1168 }
1169 *dstAttr = *srcAttr;
1170 } else {
1171 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1172 ALOGE("%s: invalid stream type", __func__);
1173 return BAD_VALUE;
1174 }
François Gaffiec005e562018-11-06 15:04:49 +01001175 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001176 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001177
1178 // Only honor audibility enforced when required. The client will be
1179 // forced to reconnect if the forced usage changes.
1180 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001181 dstAttr->flags = static_cast<audio_flags_mask_t>(
1182 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001183 }
1184
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001185 return NO_ERROR;
1186}
1187
Kevin Rocard153f92d2018-12-18 18:33:28 -08001188status_t AudioPolicyManager::getOutputForAttrInt(
1189 audio_attributes_t *resultAttr,
1190 audio_io_handle_t *output,
1191 audio_session_t session,
1192 const audio_attributes_t *attr,
1193 audio_stream_type_t *stream,
1194 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001195 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001196 audio_output_flags_t *flags,
1197 audio_port_handle_t *selectedDeviceId,
1198 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001199 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001200 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001201 bool *isSpatialized,
1202 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001203{
François Gaffiec005e562018-11-06 15:04:49 +01001204 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001205 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001206 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001207 const sp<DeviceDescriptor> requestedDevice =
1208 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1209
Eric Laurent8a1095a2019-11-08 14:44:16 -08001210 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001211 *isSpatialized = false;
1212
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001213 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1214 if (status != NO_ERROR) {
1215 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001216 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001217 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001218 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001219 }
François Gaffiec005e562018-11-06 15:04:49 +01001220 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001221
François Gaffiec005e562018-11-06 15:04:49 +01001222 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1223 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001224
Oscar Azucena873d10f2023-01-12 18:34:42 -08001225 bool usePrimaryOutputFromPolicyMixes = false;
1226
Kevin Rocard153f92d2018-12-18 18:33:28 -08001227 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1228 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1229 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001230 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001231 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1232 .channel_mask = config->channel_mask,
1233 .format = config->format,
1234 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001235 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001236 mAvailableOutputDevices, requestedDevice, primaryMix,
1237 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001238 if (status != OK) {
1239 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001240 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001241
Kevin Rocard153f92d2018-12-18 18:33:28 -08001242 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001243 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1244 && !audio_is_linear_pcm(config->format)) {
1245 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001246 return BAD_VALUE;
1247 }
1248 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001249 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1251 primaryMix->mDeviceAddress,
1252 AUDIO_FORMAT_DEFAULT);
1253 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001254 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001255 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1256 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001257 // if a direct output can be opened to deliver the track's multi-channel content to the
1258 // output rather than being downmixed by the primary output, then use this direct
1259 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1260 // mix.
1261 bool tryDirectForChannelMask = policyDesc != nullptr
1262 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1263 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001264 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001265 audio_io_handle_t newOutput;
1266 status = openDirectOutput(
1267 *stream, session, config,
1268 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001269 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001270 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001271 policyDesc = mOutputs.valueFor(newOutput);
1272 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001273 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001274 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001275 policyDesc = nullptr;
1276 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001277 }
1278 if (policyDesc != nullptr) {
1279 policyDesc->mPolicyMix = primaryMix;
1280 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001281 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1282 : AUDIO_PORT_HANDLE_NONE;
1283 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1284 // Remove direct flag as it is not on a direct output.
1285 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1286 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001287
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001288 ALOGV("getOutputForAttr() returns output %d", *output);
1289 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1290 *outputType = API_OUT_MIX_PLAYBACK;
1291 } else {
1292 *outputType = API_OUTPUT_LEGACY;
1293 }
1294 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001295 } else {
1296 if (policyMixDevice != nullptr) {
1297 ALOGE("%s, try to use primary mix but no output found", __func__);
1298 return INVALID_OPERATION;
1299 }
1300 // Fallback to default engine selection as the selected primary mix device is not
1301 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001302 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001303 }
François Gaffiec005e562018-11-06 15:04:49 +01001304 // Virtual sources must always be dynamicaly or explicitly routed
1305 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1306 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1307 return BAD_VALUE;
1308 }
1309 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1310 // in order to let the choice of the order to future vendor engine
1311 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001312
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001313 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001314 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001315 }
1316
Nadav Barb2f18162018-07-18 13:01:53 +03001317 // Set incall music only if device was explicitly set, and fallback to the device which is
1318 // chosen by the engine if not.
1319 // FIXME: provide a more generic approach which is not device specific and move this back
1320 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001321 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001322 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001323 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001324 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001325 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001326 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001327 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001328 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001329 }
1330 }
1331
François Gaffiec005e562018-11-06 15:04:49 +01001332 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1333 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1334 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001335
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001336 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001337 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001338 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001339 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001340 ALOGV("%s() Using MSD devices %s instead of devices %s",
1341 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001342 } else {
1343 *output = AUDIO_IO_HANDLE_NONE;
1344 }
1345 }
1346 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001347 sp<PreferredMixerAttributesInfo> info = nullptr;
1348 if (outputDevices.size() == 1) {
1349 info = getPreferredMixerAttributesInfo(
1350 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001351 mEngine->getProductStrategyForAttributes(*resultAttr),
1352 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001353 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1354 // and it is currently active.
1355 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001356 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001357 info = nullptr;
1358 }
jiabin220eea12024-05-17 17:55:20 +00001359 if (com::android::media::audioserver::
1360 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1361 if (info != nullptr && info->getUid() == uid &&
1362 info->configMatches(*config) &&
1363 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1364 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1365 [this, &outputDevices](audio_usage_t usage) {
1366 return mOutputs.isUsageActiveOnDevice(
1367 usage, outputDevices[0]); }))) {
1368 // Bit-perfect request is not allowed when the phone mode is not normal or
1369 // there is any higher priority user case active.
1370 return INVALID_OPERATION;
1371 }
1372 }
jiabina84c3d32022-12-02 18:59:55 +00001373 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001374 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001375 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001376 // The client will be active if the client is currently preferred mixer owner and the
1377 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001378 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001379 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001380 && info->getUid() == uid
1381 && *output != AUDIO_IO_HANDLE_NONE
1382 // When bit-perfect output is selected for the preferred mixer attributes owner,
1383 // only need to consider the config matches.
1384 && mOutputs.valueFor(*output)->isConfigurationMatched(
1385 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001386
1387 if (*isBitPerfect) {
1388 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1389 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001390 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001391 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001392 AudioProfileVector profiles;
1393 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1394 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001395 const auto channels = profiles[0]->getChannels();
1396 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1397 config->channel_mask = *channels.begin();
1398 }
1399 const auto sampleRates = profiles[0]->getSampleRates();
1400 if (!sampleRates.empty() &&
1401 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1402 config->sample_rate = *sampleRates.begin();
1403 }
jiabinf1c73972022-04-14 16:28:52 -07001404 config->format = profiles[0]->getFormat();
1405 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001406 return INVALID_OPERATION;
1407 }
Paul McLeanaa981192015-03-21 09:55:15 -07001408
François Gaffiec005e562018-11-06 15:04:49 +01001409 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001410 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001411 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001412 *selectedDeviceId = outputDevice->getId();
1413 break;
1414 }
1415 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001416
Eric Laurent8a1095a2019-11-08 14:44:16 -08001417 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1418 *outputType = API_OUTPUT_TELEPHONY_TX;
1419 } else {
1420 *outputType = API_OUTPUT_LEGACY;
1421 }
1422
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001423 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1424
1425 return NO_ERROR;
1426}
1427
1428status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1429 audio_io_handle_t *output,
1430 audio_session_t session,
1431 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001432 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001433 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001434 audio_output_flags_t *flags,
1435 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001436 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001437 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001438 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001439 bool *isSpatialized,
1440 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001441{
1442 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1443 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1444 return INVALID_OPERATION;
1445 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001446 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001447 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001448 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001449 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001450 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001451 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001452 const sp<DeviceDescriptor> requestedDevice =
1453 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1454
1455 // Prevent from storing invalid requested device id in clients
1456 const audio_port_handle_t sanitizedRequestedPortId =
1457 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1458 *selectedDeviceId = sanitizedRequestedPortId;
1459
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001460 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001461 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001462 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1463 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001464 if (status != NO_ERROR) {
1465 return status;
1466 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001467 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001468 if (secondaryOutputs != nullptr) {
1469 for (auto &secondaryMix : secondaryMixes) {
1470 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1471 if (outputDesc != nullptr &&
1472 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1473 secondaryOutputs->push_back(outputDesc->mIoHandle);
1474 weakSecondaryOutputDescs.push_back(outputDesc);
1475 }
1476 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001477 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001478
Eric Laurent8fc147b2018-07-22 19:13:55 -07001479 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001480 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001481 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001482 };
jiabin4ef93452019-09-10 14:29:54 -07001483 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001484
Eric Laurentc209fe42020-06-05 18:11:23 -07001485 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001486 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001487 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001488 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001489 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001490 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001491 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001492 std::move(weakSecondaryOutputDescs),
1493 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001494 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001495
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001496 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1497 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001498
Eric Laurente83b55d2014-11-14 10:06:21 -08001499 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001500}
1501
Eric Laurentc529cf62020-04-17 18:19:10 -07001502status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1503 audio_session_t session,
1504 const audio_config_t *config,
1505 audio_output_flags_t flags,
1506 const DeviceVector &devices,
1507 audio_io_handle_t *output) {
1508
1509 *output = AUDIO_IO_HANDLE_NONE;
1510
1511 // skip direct output selection if the request can obviously be attached to a mixed output
1512 // and not explicitly requested
1513 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1514 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1515 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1516 return NAME_NOT_FOUND;
1517 }
1518
1519 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1520 // This prevents creating an offloaded track and tearing it down immediately after start
1521 // when audioflinger detects there is an active non offloadable effect.
1522 // FIXME: We should check the audio session here but we do not have it in this context.
1523 // This may prevent offloading in rare situations where effects are left active by apps
1524 // in the background.
1525 sp<IOProfile> profile;
1526 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1527 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1528 profile = getProfileForOutput(
1529 devices, config->sample_rate, config->format, config->channel_mask,
1530 flags, true /* directOnly */);
1531 }
1532
1533 if (profile == nullptr) {
1534 return NAME_NOT_FOUND;
1535 }
1536
1537 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1538 for (size_t i = 0; i < mOutputs.size(); i++) {
1539 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1540 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1541 // reuse direct output if currently open by the same client
1542 // and configured with same parameters
1543 if ((config->sample_rate == desc->getSamplingRate()) &&
1544 (config->format == desc->getFormat()) &&
1545 (config->channel_mask == desc->getChannelMask()) &&
1546 (session == desc->mDirectClientSession)) {
1547 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001548 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001549 mOutputs.keyAt(i), session);
1550 *output = mOutputs.keyAt(i);
1551 return NO_ERROR;
1552 }
1553 }
1554 }
1555
1556 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001557 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1558 return NAME_NOT_FOUND;
1559 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1560 // MMAP gracefully handles lack of an exclusive track resource by mixing
1561 // above the audio framework. For AAudio to know that the limit is reached,
1562 // return an error.
1563 return NAME_NOT_FOUND;
1564 } else {
1565 // Close outputs on this profile, if available, to free resources for this request
1566 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1567 const auto desc = mOutputs.valueAt(i);
1568 if (desc->mProfile == profile) {
1569 closeOutput(desc->mIoHandle);
1570 }
1571 }
1572 }
1573 }
1574
1575 // Unable to close streams to find free resources for this request
1576 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001577 return NAME_NOT_FOUND;
1578 }
1579
Atneya Nairb16666a2023-12-11 20:18:33 -08001580 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001581
Michael Chan6fb34492020-12-08 15:44:49 +11001582 // An MSD patch may be using the only output stream that can service this request. Release
1583 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001584 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001585
Eric Laurentf1f22e72021-07-13 14:04:14 +02001586 status_t status =
1587 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001588
1589 // only accept an output with the requested parameters
1590 if (status != NO_ERROR ||
1591 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1592 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1593 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1594 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1595 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1596 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1597 config->channel_mask, outputDesc->getChannelMask());
1598 if (*output != AUDIO_IO_HANDLE_NONE) {
1599 outputDesc->close();
1600 }
1601 // fall back to mixer output if possible when the direct output could not be open
1602 if (audio_is_linear_pcm(config->format) &&
1603 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1604 return NAME_NOT_FOUND;
1605 }
1606 *output = AUDIO_IO_HANDLE_NONE;
1607 return BAD_VALUE;
1608 }
1609 outputDesc->mDirectOpenCount = 1;
1610 outputDesc->mDirectClientSession = session;
1611
1612 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001613 setOutputDevices(__func__, outputDesc,
1614 devices,
1615 true,
1616 0,
1617 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001618 mPreviousOutputs = mOutputs;
1619 ALOGV("%s returns new direct output %d", __func__, *output);
1620 mpClientInterface->onAudioPortListUpdate();
1621 return NO_ERROR;
1622}
1623
François Gaffie11d30102018-11-02 16:09:09 +01001624audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1625 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001626 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001627 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001628 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001629 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001630 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001631 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001632 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001633{
Andy Hungc88b0642018-04-27 15:42:35 -07001634 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001635
jiabine375d412019-02-26 12:54:53 -08001636 // Discard haptic channel mask when forcing muting haptic channels.
1637 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001638 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1639 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001640
Eric Laurente552edb2014-03-10 17:42:56 -07001641 // open a direct output if required by specified parameters
1642 //force direct flag if offload flag is set: offloading implies a direct output stream
1643 // and all common behaviors are driven by checking only the direct flag
1644 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001645 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1646 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001647 }
Nadav Bar766fb022018-01-07 12:18:03 +02001648 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1649 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001650 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001651
1652 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1653
Eric Laurente83b55d2014-11-14 10:06:21 -08001654 // only allow deep buffering for music stream type
1655 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001656 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001657 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001658 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001659 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1660 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001661 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001662 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001663 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001664 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001665 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001666 audio_is_linear_pcm(config->format) &&
1667 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001668 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001669 AUDIO_OUTPUT_FLAG_DIRECT);
1670 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001671 }
Eric Laurente552edb2014-03-10 17:42:56 -07001672
Carter Hsua3abb402021-10-26 11:11:20 +08001673 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1674 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1675 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1676 }
1677
Eric Laurentf9230d52024-01-26 18:49:09 +01001678 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001679 // was specified and offload or direct playback is not explicitly requested, and there is no
1680 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001681 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001682 if (mSpatializerOutput != nullptr &&
1683 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1684 prefMixerConfigInfo == nullptr &&
1685 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1686 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001687 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001688 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001689 }
1690
Eric Laurentc529cf62020-04-17 18:19:10 -07001691 audio_config_t directConfig = *config;
1692 directConfig.channel_mask = channelMask;
1693 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1694 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001695 return output;
1696 }
1697
Eric Laurent14cbfca2016-03-17 09:42:16 -07001698 // A request for HW A/V sync cannot fallback to a mixed output because time
1699 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001700 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001701 return AUDIO_IO_HANDLE_NONE;
1702 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001703 // A request for Tuner cannot fallback to a mixed output
1704 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1705 return AUDIO_IO_HANDLE_NONE;
1706 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001707
Eric Laurente552edb2014-03-10 17:42:56 -07001708 // ignoring channel mask due to downmix capability in mixer
1709
1710 // open a non direct output
1711
1712 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001713 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001714 // get which output is suitable for the specified stream. The actual
1715 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001716 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001717 if (prefMixerConfigInfo != nullptr) {
1718 for (audio_io_handle_t outputHandle : outputs) {
1719 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1720 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1721 output = outputHandle;
1722 break;
1723 }
1724 }
1725 if (output == AUDIO_IO_HANDLE_NONE) {
1726 // No output open with the preferred profile. Open a new one.
1727 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1728 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1729 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1730 config.format = prefMixerConfigInfo->getConfigBase().format;
1731 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1732 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1733 &config, prefMixerConfigInfo->getFlags());
1734 if (preferredOutput == nullptr) {
1735 ALOGE("%s failed to open output with preferred mixer config", __func__);
1736 } else {
1737 output = preferredOutput->mIoHandle;
1738 }
1739 }
1740 } else {
1741 // at this stage we should ignore the DIRECT flag as no direct output could be
1742 // found earlier
1743 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001744 if (com::android::media::audioserver::
1745 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1746 // If the preferred mixer attributes is null, do not select the bit-perfect output
1747 // unless the bit-perfect output is the only output.
1748 // The bit-perfect output can exist while the passed in preferred mixer attributes
1749 // info is null when it is a high priority client. The high priority clients are
1750 // ringtone or alarm, which is not a bit-perfect use case.
1751 size_t i = 0;
1752 while (i < outputs.size() && outputs.size() > 1) {
1753 auto desc = mOutputs.valueFor(outputs[i]);
1754 // The output descriptor must not be null here.
1755 if (desc->isBitPerfect()) {
1756 outputs.removeItemsAt(i);
1757 } else {
1758 i += 1;
1759 }
1760 }
1761 }
jiabina84c3d32022-12-02 18:59:55 +00001762 output = selectOutput(
1763 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1764 }
Eric Laurente552edb2014-03-10 17:42:56 -07001765 }
François Gaffie11d30102018-11-02 16:09:09 +01001766 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001767 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001768 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001769
Eric Laurente552edb2014-03-10 17:42:56 -07001770 return output;
1771}
1772
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001773sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001774 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1775 mAvailableInputDevices);
1776 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1777}
1778
1779DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1780 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1781 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001782}
1783
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001784const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001786 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1787 if (msdModule != 0) {
1788 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1789 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1790 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1791 const struct audio_port_config *source = &patch->mPatch.sources[j];
1792 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1793 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001794 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001795 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001796 }
1797 }
1798 }
1799 return msdPatches;
1800}
1801
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001802bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1803 ssize_t index = mAudioPatches.indexOfKey(handle);
1804 if (index < 0) {
1805 return false;
1806 }
1807 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1808 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1809 if (msdModule == nullptr) {
1810 return false;
1811 }
1812 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1813 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1814 return true;
1815 }
1816 index = getMsdOutputPatches().indexOfKey(handle);
1817 if (index < 0) {
1818 return false;
1819 }
1820 return true;
1821}
1822
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001823status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1824 const InputProfileCollection &inputProfiles,
1825 const OutputProfileCollection &outputProfiles,
1826 const sp<DeviceDescriptor> &sourceDevice,
1827 const sp<DeviceDescriptor> &sinkDevice,
1828 AudioProfileVector& sourceProfiles,
1829 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001830 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001831 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 return NO_INIT;
1833 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001834 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001835 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 return NO_INIT;
1837 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001838 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1840 inProfile->supportsDevice(sourceDevice)) {
1841 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 }
1843 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001845 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001846 outProfile->supportsDevice(sinkDevice)) {
1847 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001848 }
1849 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001850 return NO_ERROR;
1851}
1852
1853status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1854 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1855 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1856{
Dean Wheatley16809da2022-12-09 14:55:46 +11001857 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1858 static const std::vector<audio_format_t> formatsOrder = {{
1859 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001860 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1861 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001862 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1863 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1864 // preferred).
1865 std::vector<audio_channel_mask_t> masks = {{
1866 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1867 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1868 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1869 // insert index masks (higher counts most preferred) as preferred over position masks
1870 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1871 masks.insert(
1872 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1873 }
1874 return masks;
1875 }();
1876
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001878 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1879 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001880 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001881 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1882 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001883 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 }
1885 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1886 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1887 sinkConfig->format = bestSinkConfig.format;
1888 // For encoded streams force direct flag to prevent downstream mixing.
1889 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1890 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001891 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1892 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001893 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001894 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1895 // raw and IEC61937 framed streams.
1896 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1897 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1898 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1900 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001901 sourceConfig->channel_mask =
1902 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1903 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1904 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001905 sourceConfig->format = bestSinkConfig.format;
1906 // Copy input stream directly without any processing (e.g. resampling).
1907 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1908 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1909 if (hwAvSync) {
1910 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1911 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1912 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1913 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1914 }
1915 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1916 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1917 sinkConfig->config_mask |= config_mask;
1918 sourceConfig->config_mask |= config_mask;
1919 return NO_ERROR;
1920}
1921
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001922PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1923 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001924{
1925 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001926 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1927 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1928 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1929 if (deviceModule == nullptr) {
1930 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1931 return patchBuilder;
1932 }
1933 const InputProfileCollection inputProfiles = msdIsSource ?
1934 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1935 const OutputProfileCollection outputProfiles = msdIsSource ?
1936 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1937
1938 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1939 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1940 device : getMsdAudioOutDevices().itemAt(0);
1941 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1942
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1944 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001945 AudioProfileVector sourceProfiles;
1946 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001947 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1948 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001949 for (auto hwAvSync : { true, false }) {
1950 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1951 sourceProfiles, sinkProfiles) != NO_ERROR) {
1952 continue;
1953 }
1954 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1955 &sinkConfig) == NO_ERROR) {
1956 // Found a matching config. Re-create PatchBuilder with this config.
1957 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1958 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001959 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001960 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001961 " supporting PCM format conversion.", __func__);
1962 return patchBuilder;
1963}
1964
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001965status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001966 DeviceVector devices;
1967 if (outputDevices != nullptr && outputDevices->size() > 0) {
1968 devices.add(*outputDevices);
1969 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001970 // Use media strategy for unspecified output device. This should only
1971 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1972 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001973 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001974 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001975 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001976 }
Michael Chan6fb34492020-12-08 15:44:49 +11001977 std::vector<PatchBuilder> patchesToCreate;
1978 for (auto i = 0u; i < devices.size(); ++i) {
1979 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001980 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001981 }
1982 // Retain only the MSD patches associated with outputDevices request.
1983 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001984 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001985 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1986 auto retainedPatch = false;
1987 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1988 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1989 patchesToRemove.removeItemsAt(i);
1990 retainedPatch = true;
1991 break;
1992 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001993 }
Michael Chan6fb34492020-12-08 15:44:49 +11001994 if (retainedPatch) {
1995 it = patchesToCreate.erase(it);
1996 continue;
1997 }
1998 ++it;
1999 }
2000 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2001 return NO_ERROR;
2002 }
2003 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2004 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002005 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002006 }
Michael Chan6fb34492020-12-08 15:44:49 +11002007 status_t status = NO_ERROR;
2008 for (const auto &p : patchesToCreate) {
2009 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2010 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2011 char message[256];
2012 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2013 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2014 currStatus == NO_ERROR ? "Success" : "Error",
2015 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2016 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2017 if (currStatus == NO_ERROR) {
2018 ALOGD("%s", message);
2019 } else {
2020 ALOGE("%s", message);
2021 if (status == NO_ERROR) {
2022 status = currStatus;
2023 }
2024 }
2025 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002026 return status;
2027}
2028
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002029void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2030 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002031 for (size_t i = 0; i < msdPatches.size(); i++) {
2032 const auto& patch = msdPatches[i];
2033 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2034 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2035 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2036 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2037 releaseAudioPatch(patch->getHandle(), mUidCached);
2038 break;
2039 }
2040 }
2041 }
2042}
2043
Dorin Drimus94d94412022-02-02 09:05:02 +01002044bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002045 DeviceVector devicesToCheck =
2046 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002047 AudioPatchCollection msdPatches = getMsdOutputPatches();
2048 for (size_t i = 0; i < msdPatches.size(); i++) {
2049 const auto& patch = msdPatches[i];
2050 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2051 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2052 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2053 const auto& foundDevice = devicesToCheck.getDevice(
2054 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2055 if (foundDevice != nullptr) {
2056 devicesToCheck.remove(foundDevice);
2057 if (devicesToCheck.isEmpty()) {
2058 return true;
2059 }
2060 }
2061 }
2062 }
2063 }
2064 return false;
2065}
2066
Eric Laurente0720872014-03-11 09:30:41 -07002067audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002068 audio_output_flags_t flags,
2069 audio_format_t format,
2070 audio_channel_mask_t channelMask,
2071 uint32_t samplingRate,
2072 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002073{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002074 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2075 "%s called with format %#x", __func__, format);
2076
jiabinebb6af42020-06-09 17:31:17 -07002077 // Return the output that haptic-generating attached to when 1) session id is specified,
2078 // 2) haptic-generating effect exists for given session id and 3) the output that
2079 // haptic-generating effect attached to is in given outputs.
2080 if (sessionId != AUDIO_SESSION_NONE) {
2081 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2082 sessionId, FX_IID_HAPTICGENERATOR);
2083 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2084 return hapticGeneratingOutput;
2085 }
2086 }
2087
Eric Laurent16c66dd2019-05-01 17:54:10 -07002088 // Flags disqualifying an output: the match must happen before calling selectOutput()
2089 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2090 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2091
2092 // Flags expressing a functional request: must be honored in priority over
2093 // other criteria
2094 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2095 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002096 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2097 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002098 // Flags expressing a performance request: have lower priority than serving
2099 // requested sampling rate or channel mask
2100 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2101 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2102 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2103
2104 const audio_output_flags_t functionalFlags =
2105 (audio_output_flags_t)(flags & kFunctionalFlags);
2106 const audio_output_flags_t performanceFlags =
2107 (audio_output_flags_t)(flags & kPerformanceFlags);
2108
2109 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2110
Eric Laurente552edb2014-03-10 17:42:56 -07002111 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002112 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002113 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002114 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002115 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002116 // with tiebreak preferring the minimum number of extra functional flags
2117 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002118 // 3: the output supporting the exact channel mask
2119 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002120 // 5: the output with the highest sampling rate if the requested sample rate is
2121 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002122 // 6: the output with the highest number of requested performance flags
2123 // 7: the output with the bit depth the closest to the requested one
2124 // 8: the primary output
2125 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002126
Eric Laurent16c66dd2019-05-01 17:54:10 -07002127 // matching criteria values in priority order for best matching output so far
2128 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002129
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002130 const bool hasOrphanHaptic =
2131 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002132 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2133 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2134 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002135
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002136 for (audio_io_handle_t output : outputs) {
2137 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002138 // matching criteria values in priority order for current output
2139 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002140
Eric Laurent16c66dd2019-05-01 17:54:10 -07002141 if (outputDesc->isDuplicated()) {
2142 continue;
2143 }
2144 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2145 continue;
2146 }
Eric Laurent8838a382014-09-08 16:44:28 -07002147
Eric Laurent16c66dd2019-05-01 17:54:10 -07002148 // If haptic channel is specified, use the haptic output if present.
2149 // When using haptic output, same audio format and sample rate are required.
2150 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002151 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002152 // skip if haptic channel specified but output does not support it, or output support haptic
2153 // but there is no haptic channel requested AND no orphan haptic effect exist
2154 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2155 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002156 continue;
2157 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002158 // In the case of audio-coupled-haptic playback, there is no format conversion and
2159 // resampling in the framework, same format/channel/sampleRate for client and the output
2160 // thread is required. In the case of HapticGenerator effect, do not require format
2161 // matching.
2162 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2163 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002164 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002165 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002166 }
2167
2168 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002169 const int matchingFunctionalFlags =
2170 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2171 const int totalFunctionalFlags =
2172 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2173 // Prefer matching functional flags, but subtract unnecessary functional flags.
2174 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002175
2176 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002177 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2178 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002179 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2180 channelCount <= outputChannelCount) {
2181 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002182 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2183 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002184 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002185 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002186 currentMatchCriteria[3] = outputChannelCount;
2187 }
2188
2189 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002190 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002191 int diff; // avoid unsigned integer overflow.
2192 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2193
2194 // prefer the closest output sampling rate greater than or equal to target
2195 // if none exists, prefer the closest output sampling rate less than target.
2196 //
2197 // criteria is offset to make non-negative.
2198 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002199 }
2200
2201 // performance flags match
2202 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2203
2204 // format match
2205 if (format != AUDIO_FORMAT_INVALID) {
2206 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002207 PolicyAudioPort::kFormatDistanceMax -
2208 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002209 }
2210
2211 // primary output match
2212 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2213
2214 // compare match criteria by priority then value
2215 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2216 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2217 bestMatchCriteria = currentMatchCriteria;
2218 bestOutput = output;
2219
2220 std::stringstream result;
2221 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2222 std::ostream_iterator<int>(result, " "));
2223 ALOGV("%s new bestOutput %d criteria %s",
2224 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002225 }
2226 }
2227
Eric Laurent16c66dd2019-05-01 17:54:10 -07002228 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002229}
2230
Eric Laurent8fc147b2018-07-22 19:13:55 -07002231status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002232{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002233 ALOGV("%s portId %d", __FUNCTION__, portId);
2234
2235 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2236 if (outputDesc == 0) {
2237 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002238 return BAD_VALUE;
2239 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002240 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002241
Eric Laurent8fc147b2018-07-22 19:13:55 -07002242 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002243 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002244
jiabin220eea12024-05-17 17:55:20 +00002245 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2246 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2247 && outputDesc->isBitPerfect()) {
2248 // Usually, APM selects bit-perfect output for high priority use cases only when
2249 // bit-perfect output is the only output that can be routed to the selected device.
2250 // However, here is no need to play high priority use cases such as ringtone and alarm
2251 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2252 // can attach to new output.
2253 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2254 __func__, client->stream());
2255 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2256 return DEAD_OBJECT;
2257 }
2258
Eric Laurent733ce942017-12-07 12:18:25 -08002259 status_t status = outputDesc->start();
2260 if (status != NO_ERROR) {
2261 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002262 }
2263
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 uint32_t delayMs;
2265 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002266
2267 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002268 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002269 if (status == DEAD_OBJECT) {
2270 sp<SwAudioOutputDescriptor> desc =
2271 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2272 if (desc == nullptr) {
2273 // This is not common, it may indicate something wrong with the HAL.
2274 ALOGE("%s unable to open output with default config", __func__);
2275 return status;
2276 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002277 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002278 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002279 }
jiabina84c3d32022-12-02 18:59:55 +00002280
2281 // If the client is the first one active on preferred mixer parameters, reopen the output
2282 // if the current mixer parameters doesn't match the preferred one.
2283 if (outputDesc->devices().size() == 1) {
2284 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2285 outputDesc->devices()[0]->getId(), client->strategy());
2286 if (info != nullptr && info->getUid() == client->uid()) {
2287 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2288 info->getConfigBase(), info->getFlags())) {
2289 stopSource(outputDesc, client);
2290 outputDesc->stop();
2291 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2292 config.channel_mask = info->getConfigBase().channel_mask;
2293 config.sample_rate = info->getConfigBase().sample_rate;
2294 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002295 sp<SwAudioOutputDescriptor> desc =
2296 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2297 if (desc == nullptr) {
2298 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002299 }
jiabin220eea12024-05-17 17:55:20 +00002300 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002301 // Intentionally return error to let the client side resending request for
2302 // creating and starting.
2303 return DEAD_OBJECT;
2304 }
2305 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002306 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002307 // If it is first bit-perfect client, reroute all clients that will be routed to
2308 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2309 PortHandleVector clientsToInvalidate;
2310 for (size_t i = 0; i < mOutputs.size(); i++) {
2311 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002312 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002313 continue;
2314 }
2315 for (const auto& c : mOutputs[i]->getClientIterable()) {
2316 clientsToInvalidate.push_back(c->portId());
2317 }
2318 }
2319 if (!clientsToInvalidate.empty()) {
2320 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2321 __func__);
2322 mpClientInterface->invalidateTracks(clientsToInvalidate);
2323 }
2324 }
jiabina84c3d32022-12-02 18:59:55 +00002325 }
2326 }
2327
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002328 if (client->hasPreferredDevice()) {
2329 // playback activity with preferred device impacts routing occurred, inform upper layers
2330 mpClientInterface->onRoutingUpdated();
2331 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002332 if (delayMs != 0) {
2333 usleep(delayMs * 1000);
2334 }
2335
jiabin220eea12024-05-17 17:55:20 +00002336 if (status == NO_ERROR &&
2337 outputDesc->mPreferredAttrInfo != nullptr &&
2338 outputDesc->isBitPerfect() &&
2339 com::android::media::audioserver::
2340 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2341 // A new client is started on bit-perfect output, update all clients internal mute.
2342 updateClientsInternalMute(outputDesc);
2343 }
2344
Eric Laurentc75307b2015-03-17 15:29:32 -07002345 return status;
2346}
2347
Eric Laurent96d1dda2022-03-14 17:14:19 +01002348bool AudioPolicyManager::isLeUnicastActive() const {
2349 if (isInCall()) {
2350 return true;
2351 }
2352 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2353}
2354
2355bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2356 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2357 return false;
2358 }
2359 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2360 ALOGV("%s active %d", __func__, active);
2361 return active;
2362}
2363
Eric Laurent97ac8712018-07-27 18:59:02 -07002364status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2365 const sp<TrackClientDescriptor>& client,
2366 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002367{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002368 // cannot start playback of STREAM_TTS if any other output is being used
2369 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002370
2371 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002372 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002373 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002374 auto clientStrategy = client->strategy();
2375 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002376 if (stream == AUDIO_STREAM_TTS) {
2377 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002378 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002379 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002380 return INVALID_OPERATION;
2381 } else {
2382 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2383 }
2384 } else {
2385 // some playback other than beacon starts
2386 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2387 }
2388
Eric Laurent77305a62016-07-25 16:39:22 -07002389 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002390 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002391 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002392
François Gaffie11d30102018-11-02 16:09:09 +01002393 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002394 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002395 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002396 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002397 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002398 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002399 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002400 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002401 } else {
2402 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002403 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002404 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2405 AUDIO_FORMAT_DEFAULT);
2406 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2407 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002408 }
2409
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002410 // requiresMuteCheck is false when we can bypass mute strategy.
2411 // It covers a common case when there is no materially active audio
2412 // and muting would result in unnecessary delay and dropped audio.
2413 const uint32_t outputLatencyMs = outputDesc->latency();
2414 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002415 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002416
Eric Laurente552edb2014-03-10 17:42:56 -07002417 // increment usage count for this stream on the requested output:
2418 // NOTE that the usage count is the same for duplicated output and hardware output which is
2419 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002420 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002421
2422 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002423 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002424 // Preferred device may be exclusive, use only if no other active clients on this output
2425 devices = DeviceVector(
2426 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2427 } else {
2428 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2429 }
François Gaffie11d30102018-11-02 16:09:09 +01002430 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002431 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002432 }
2433 }
Eric Laurente552edb2014-03-10 17:42:56 -07002434
François Gaffiec005e562018-11-06 15:04:49 +01002435 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002436 selectOutputForMusicEffects();
2437 }
2438
François Gaffie1c878552018-11-22 16:53:21 +01002439 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002440 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002441 if (devices.isEmpty()) {
2442 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002443 }
François Gaffiec005e562018-11-06 15:04:49 +01002444 bool shouldWait =
2445 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2446 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2447 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002448 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002449 const bool needToCloseBitPerfectOutput =
2450 (com::android::media::audioserver::
2451 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2452 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2453 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002454 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002455 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002456 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002457 // An output has a shared device if
2458 // - managed by the same hw module
2459 // - supports the currently selected device
2460 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002461 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002462
Eric Laurent77305a62016-07-25 16:39:22 -07002463 // force a device change if any other output is:
2464 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002465 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002466 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002467 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002468 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002469 // change the device currently selected by the other output.
2470 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002471 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002472 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002473 force = true;
2474 }
2475 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002476 // a notification so that audio focus effect can propagate, or that a mute/unmute
2477 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002478 const uint32_t latencyMs = desc->latency();
2479 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2480
2481 if (shouldWait && isActive && (waitMs < latencyMs)) {
2482 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002483 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002484
2485 // Require mute check if another output is on a shared device
2486 // and currently active to have proper drain and avoid pops.
2487 // Note restoring AudioTracks onto this output needs to invoke
2488 // a volume ramp if there is no mute.
2489 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002490
2491 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2492 outputsToReopen.push_back(desc);
2493 }
Eric Laurente552edb2014-03-10 17:42:56 -07002494 }
2495 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002496
jiabin220eea12024-05-17 17:55:20 +00002497 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002498 // If the output is open with preferred mixer attributes, but the routed device is
2499 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2500 // changed.
2501 return DEAD_OBJECT;
2502 }
jiabin220eea12024-05-17 17:55:20 +00002503 for (auto& outputToReopen : outputsToReopen) {
2504 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2505 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002506 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302507 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2508 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002509
Eric Laurente552edb2014-03-10 17:42:56 -07002510 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002511 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002512 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002513 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002514 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002515 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002516 outputDesc->useHwGain() /*force*/)) {
2517 // request AudioService to reinitialize the volume curves asynchronously
2518 ALOGE("checkAndSetVolume failed, requesting volume range init");
2519 mpClientInterface->onVolumeRangeInitRequest();
2520 };
Eric Laurente552edb2014-03-10 17:42:56 -07002521
2522 // update the outputs if starting an output with a stream that can affect notification
2523 // routing
2524 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002525
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002526 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002527 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002528 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002529 }
Eric Laurentdc462862016-07-19 12:29:53 -07002530
2531 if (waitMs > muteWaitMs) {
2532 *delayMs = waitMs - muteWaitMs;
2533 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002534
2535 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2536 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2537 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2538 // change occurs after the MixerThread starts and causes a stream volume
2539 // glitch.
2540 //
2541 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002542 }
Eric Laurentdc462862016-07-19 12:29:53 -07002543
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002544 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002545 mEngine->getForceUse(
2546 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002547 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002548 }
2549
Eric Laurent97ac8712018-07-27 18:59:02 -07002550 // Automatically enable the remote submix input when output is started on a re routing mix
2551 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002552 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2553 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2555 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2556 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002557 "remote-submix",
2558 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002559 }
2560
Eric Laurent96d1dda2022-03-14 17:14:19 +01002561 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2562
Eric Laurente552edb2014-03-10 17:42:56 -07002563 return NO_ERROR;
2564}
2565
Eric Laurent96d1dda2022-03-14 17:14:19 +01002566void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2567 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2568 bool isUnicastActive = isLeUnicastActive();
2569
2570 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002571 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002572 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2573 for (size_t i = 0; i < mOutputs.size(); i++) {
2574 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2575 if (desc != ignoredOutput && desc->isActive()
2576 && ((isUnicastActive &&
2577 !desc->devices().
2578 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2579 || (wasUnicastActive &&
2580 !desc->devices().getDevicesFromTypes(
2581 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2582 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2583 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002584 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002585 // If the device is using preferred mixer attributes, the output need to reopen
2586 // with default configuration when the new selected devices are different from
2587 // current routing devices.
2588 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2589 continue;
2590 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302591 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002592 // re-apply device specific volume if not done by setOutputDevice()
2593 if (!force) {
2594 applyStreamVolumes(desc, newDevices.types(), delayMs);
2595 }
2596 }
2597 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002598 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002599 }
2600}
2601
Eric Laurent8fc147b2018-07-22 19:13:55 -07002602status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002603{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002604 ALOGV("%s portId %d", __FUNCTION__, portId);
2605
2606 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2607 if (outputDesc == 0) {
2608 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002609 return BAD_VALUE;
2610 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002611 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002612
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002613 if (client->hasPreferredDevice(true)) {
2614 // playback activity with preferred device impacts routing occurred, inform upper layers
2615 mpClientInterface->onRoutingUpdated();
2616 }
2617
Eric Laurent97ac8712018-07-27 18:59:02 -07002618 ALOGV("stopOutput() output %d, stream %d, session %d",
2619 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002620
Eric Laurent97ac8712018-07-27 18:59:02 -07002621 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002622
Eric Laurent733ce942017-12-07 12:18:25 -08002623 if (status == NO_ERROR ) {
2624 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002625 } else {
2626 return status;
2627 }
2628
2629 if (outputDesc->devices().size() == 1) {
2630 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2631 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002632 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002633 if (info != nullptr && info->getUid() == client->uid()) {
2634 info->decreaseActiveClient();
2635 if (info->getActiveClientCount() == 0) {
2636 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002637 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002638 }
2639 }
jiabin220eea12024-05-17 17:55:20 +00002640 if (com::android::media::audioserver::
2641 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2642 !outputReopened && outputDesc->isBitPerfect()) {
2643 // Only need to update the clients' internal mute when the output is bit-perfect and it
2644 // is not reopened.
2645 updateClientsInternalMute(outputDesc);
2646 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002647 }
2648 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002649}
2650
Eric Laurent97ac8712018-07-27 18:59:02 -07002651status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2652 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002653{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002654 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002655 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002656 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002657 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002658
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002659 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2660
François Gaffie1c878552018-11-22 16:53:21 +01002661 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2662 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002663 // Automatically disable the remote submix input when output is stopped on a
2664 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002665 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002666 if (isSingleDeviceType(
2667 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002668 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002669 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002670 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2671 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002672 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002673 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002674 }
2675 }
2676 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002677 if (client->hasPreferredDevice(true) &&
2678 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002679 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002680 forceDeviceUpdate = true;
2681 }
2682
Eric Laurente552edb2014-03-10 17:42:56 -07002683 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002684 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002685
Eric Laurente552edb2014-03-10 17:42:56 -07002686 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002687 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002688 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002689 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002690
2691 // If the routing does not change, if an output is routed on a device using HwGain
2692 // (aka setAudioPortConfig) and there are still active clients following different
2693 // volume group(s), force reapply volume
2694 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2695 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2696
Eric Laurente552edb2014-03-10 17:42:56 -07002697 // delay the device switch by twice the latency because stopOutput() is executed when
2698 // the track stop() command is received and at that time the audio track buffer can
2699 // still contain data that needs to be drained. The latency only covers the audio HAL
2700 // and kernel buffers. Also the latency does not always include additional delay in the
2701 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302702 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002703 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002704
2705 // force restoring the device selection on other active outputs if it differs from the
2706 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002707 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002708 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002709 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002710 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002711 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002712 desc->isActive() &&
2713 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002714 (newDevices != desc->devices())) {
2715 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2716 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002717
jiabin220eea12024-05-17 17:55:20 +00002718 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002719 // If the device is using preferred mixer attributes, the output need to
2720 // reopen with default configuration when the new selected devices are
2721 // different from current routing devices.
2722 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2723 continue;
2724 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302725 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002726
Eric Laurent57de36c2016-09-28 16:59:11 -07002727 // re-apply device specific volume if not done by setOutputDevice()
2728 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002729 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002730 }
Eric Laurente552edb2014-03-10 17:42:56 -07002731 }
2732 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002733 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002734 // update the outputs if stopping one with a stream that can affect notification routing
2735 handleNotificationRoutingForStream(stream);
2736 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002737
2738 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2739 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002740 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002741 }
2742
François Gaffiec005e562018-11-06 15:04:49 +01002743 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002744 selectOutputForMusicEffects();
2745 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002746
2747 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2748
Eric Laurente552edb2014-03-10 17:42:56 -07002749 return NO_ERROR;
2750 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002751 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002752 return INVALID_OPERATION;
2753 }
2754}
2755
jiabinbce0c1d2020-10-05 11:20:18 -07002756bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002757{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002758 ALOGV("%s portId %d", __FUNCTION__, portId);
2759
2760 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2761 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002762 // If an output descriptor is closed due to a device routing change,
2763 // then there are race conditions with releaseOutput from tracks
2764 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2765 // destroyed shortly thereafter.
2766 //
2767 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002768 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002769 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002770 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002771
2772 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002773
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302774 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2775 if (outputDesc->isClientActive(client)) {
2776 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2777 stopOutput(portId);
2778 }
2779
Eric Laurent8fc147b2018-07-22 19:13:55 -07002780 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2781 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002782 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002783 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002784 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002785 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002786 if (--outputDesc->mDirectOpenCount == 0) {
2787 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002788 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002789 }
2790 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302791
Andy Hung39efb7a2018-09-26 15:39:28 -07002792 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002793 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2794 // The output is pending reopened to query dynamic profiles and
2795 // there is no active clients
2796 closeOutput(outputDesc->mIoHandle);
2797 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2798 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2799 if (newOutputDesc == nullptr) {
2800 ALOGE("%s failed to open output", __func__);
2801 }
2802 return true;
2803 }
2804 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002805}
2806
Eric Laurentcaf7f482014-11-25 17:50:47 -08002807status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2808 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002809 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002810 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002811 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002812 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002813 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002814 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002815 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002816 audio_port_handle_t *portId,
2817 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002818{
François Gaffiec005e562018-11-06 15:04:49 +01002819 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002820 "flags %#x attributes=%s requested device ID %d",
2821 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2822 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002823
Eric Laurentad2e7b92017-09-14 20:06:42 -07002824 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002825 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002826 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002827 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002828 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002829 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002830 sp<RecordClientDescriptor> clientDesc;
2831 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002832 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002833 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002834
2835 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2836 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2837 return INVALID_OPERATION;
2838 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002839
Francois Gaffie716e1432019-01-14 16:58:59 +01002840 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2841 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002842 }
2843
Paul McLean466dc8e2015-04-17 13:15:36 -06002844 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002845 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002846 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002847
Eric Laurentad2e7b92017-09-14 20:06:42 -07002848 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2849 // possible
2850 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2851 *input != AUDIO_IO_HANDLE_NONE) {
2852 ssize_t index = mInputs.indexOfKey(*input);
2853 if (index < 0) {
2854 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2855 status = BAD_VALUE;
2856 goto error;
2857 }
2858 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002859 RecordClientVector clients = inputDesc->getClientsForSession(session);
2860 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002861 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2862 status = BAD_VALUE;
2863 goto error;
2864 }
2865 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2866 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002867 // corresponds to a new client and is only permitted from the same UID.
2868 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002869 if (clients.size() > 1) {
2870 for (const auto& client : clients) {
2871 // The client map is ordered by key values (portId) and portIds are allocated
2872 // incrementaly. So the first client in this list is the one opened by audio flinger
2873 // when the mmap stream is created and should be ignored as it does not correspond
2874 // to an actual client
2875 if (client == *clients.cbegin()) {
2876 continue;
2877 }
2878 if (uid != client->uid() && !client->isSilenced()) {
2879 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2880 uid, client->portId(), client->uid());
2881 status = INVALID_OPERATION;
2882 goto error;
2883 }
Eric Laurent331679c2018-04-16 17:03:16 -07002884 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002885 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002886 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002887 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002888
Eric Laurentfecbceb2021-02-09 14:46:43 +01002889 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002890 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002891 }
2892
2893 *input = AUDIO_IO_HANDLE_NONE;
2894 *inputType = API_INPUT_INVALID;
2895
Francois Gaffie716e1432019-01-14 16:58:59 +01002896 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002897 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002898 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002899 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002900 ALOGW("%s could not find input mix for attr %s",
2901 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002902 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002903 }
jiabinc1de2df2019-05-07 14:26:40 -07002904 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2905 String8(attr->tags + strlen("addr=")),
2906 AUDIO_FORMAT_DEFAULT);
2907 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002908 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002909 __func__, attributes.source, attributes.tags);
2910 status = BAD_VALUE;
2911 goto error;
2912 }
2913
Kevin Rocard25f9b052019-02-27 15:08:54 -08002914 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2915 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2916 } else {
2917 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2918 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002919 if (virtualDeviceId) {
2920 *virtualDeviceId = policyMix->mVirtualDeviceId;
2921 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002922 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002923 if (explicitRoutingDevice != nullptr) {
2924 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002925 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002926 // Prevent from storing invalid requested device id in clients
2927 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002928 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002929 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2930 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002931 }
François Gaffie11d30102018-11-02 16:09:09 +01002932 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002933 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002934 status = BAD_VALUE;
2935 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002936 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002937 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2938 *inputType = API_INPUT_MIX_CAPTURE;
2939 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002940 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2941 // there is an external policy, but this input is attached to a mix of recorders,
2942 // meaning it receives audio injected into the framework, so the recorder doesn't
2943 // know about it and is therefore considered "legacy"
2944 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002945
2946 if (virtualDeviceId) {
2947 *virtualDeviceId = policyMix->mVirtualDeviceId;
2948 }
François Gaffie11d30102018-11-02 16:09:09 +01002949 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002950 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002951 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002952 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002953 } else {
2954 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002955 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002956
Eric Laurent599c7582015-12-07 18:05:55 -08002957 }
2958
François Gaffiec005e562018-11-06 15:04:49 +01002959 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002960 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002961 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002962 AudioProfileVector profiles;
2963 status_t ret = getProfilesForDevices(
2964 DeviceVector(device), profiles, flags, true /*isInput*/);
2965 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002966 const auto channels = profiles[0]->getChannels();
2967 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2968 config->channel_mask = *channels.begin();
2969 }
2970 const auto sampleRates = profiles[0]->getSampleRates();
2971 if (!sampleRates.empty() &&
2972 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2973 config->sample_rate = *sampleRates.begin();
2974 }
jiabinf1c73972022-04-14 16:28:52 -07002975 config->format = profiles[0]->getFormat();
2976 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002977 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002978 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002979
Marvin Ramine5a122d2023-12-07 13:57:59 +01002980
2981 if (policyMix != nullptr && virtualDeviceId != nullptr) {
2982 *virtualDeviceId = policyMix->mVirtualDeviceId;
2983 }
2984
Eric Laurent8f42ea12018-08-08 09:08:25 -07002985exit:
2986
François Gaffiec005e562018-11-06 15:04:49 +01002987 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2988 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002989
Francois Gaffie716e1432019-01-14 16:58:59 +01002990 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002991 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002992 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002993
Mikhail Naganov2996f672019-04-18 12:29:59 -07002994 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002995 requestedDeviceId, attributes.source, flags,
2996 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002997 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002998 // Move (if found) effect for the client session to its input
2999 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003000 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003001
3002 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3003 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003004
Eric Laurent599c7582015-12-07 18:05:55 -08003005 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003006
3007error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003008 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003009}
3010
3011
François Gaffie11d30102018-11-02 16:09:09 +01003012audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003013 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003014 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003015 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003016 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003017 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003018{
3019 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003020 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003021 bool isSoundTrigger = false;
3022
François Gaffiec005e562018-11-06 15:04:49 +01003023 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003024 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3025 if (index >= 0) {
3026 input = mSoundTriggerSessions.valueFor(session);
3027 isSoundTrigger = true;
3028 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3029 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3030 } else {
3031 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003032 }
François Gaffiec005e562018-11-06 15:04:49 +01003033 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003034 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003035 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003036 }
3037
Carter Hsua3abb402021-10-26 11:11:20 +08003038 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3039 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3040 }
3041
Eric Laurentfe231122017-11-17 17:48:06 -08003042 // sampling rate and flags may be updated by getInputProfile
3043 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3044 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003045 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003046 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003047 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003048 // find a compatible input profile (not necessarily identical in parameters)
3049 sp<IOProfile> profile = getInputProfile(
3050 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3051 if (profile == nullptr) {
3052 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003053 }
jiabin2fd710d2022-05-02 23:20:22 +00003054
Glenn Kasten05ddca52016-02-11 08:17:12 -08003055 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003056 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003057 if (samplingRate == 0) {
3058 samplingRate = profileSamplingRate;
3059 }
Eric Laurente552edb2014-03-10 17:42:56 -07003060
Eric Laurent322b4d22015-04-03 15:57:54 -07003061 if (profile->getModuleHandle() == 0) {
3062 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003063 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003064 }
3065
Eric Laurentec376dc2021-04-08 20:41:22 +02003066 // Reuse an already opened input if a client with the same session ID already exists
3067 // on that input
3068 for (size_t i = 0; i < mInputs.size(); i++) {
3069 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3070 if (desc->mProfile != profile) {
3071 continue;
3072 }
3073 RecordClientVector clients = desc->clientsList();
3074 for (const auto &client : clients) {
3075 if (session == client->session()) {
3076 return desc->mIoHandle;
3077 }
3078 }
3079 }
3080
Eric Laurent3974e3b2017-12-07 17:58:43 -08003081 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003082 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003083 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003084 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003085 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003086 continue;
3087 }
3088 // if sound trigger, reuse input if used by other sound trigger on same session
3089 // else
3090 // reuse input if active client app is not in IDLE state
3091 //
3092 RecordClientVector clients = desc->clientsList();
3093 bool doClose = false;
3094 for (const auto& client : clients) {
3095 if (isSoundTrigger != client->isSoundTrigger()) {
3096 continue;
3097 }
3098 if (client->isSoundTrigger()) {
3099 if (session == client->session()) {
3100 return desc->mIoHandle;
3101 }
3102 continue;
3103 }
3104 if (client->active() && client->appState() != APP_STATE_IDLE) {
3105 return desc->mIoHandle;
3106 }
3107 doClose = true;
3108 }
3109 if (doClose) {
3110 closeInput(desc->mIoHandle);
3111 } else {
3112 i++;
3113 }
3114 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003115 }
3116
Eric Laurentfe231122017-11-17 17:48:06 -08003117 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003118
Eric Laurentfe231122017-11-17 17:48:06 -08003119 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3120 lConfig.sample_rate = profileSamplingRate;
3121 lConfig.channel_mask = profileChannelMask;
3122 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003123
François Gaffie11d30102018-11-02 16:09:09 +01003124 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003125
3126 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003127 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003128 (profileSamplingRate != lConfig.sample_rate) ||
3129 !audio_formats_match(profileFormat, lConfig.format) ||
3130 (profileChannelMask != lConfig.channel_mask)) {
3131 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003132 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003133 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003134 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003135 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003136 }
Eric Laurent599c7582015-12-07 18:05:55 -08003137 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003138 }
3139
Eric Laurentc722f302014-12-10 11:21:49 -08003140 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003141
Eric Laurent599c7582015-12-07 18:05:55 -08003142 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003143 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003144
Eric Laurent599c7582015-12-07 18:05:55 -08003145 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003146}
3147
Eric Laurent4eb58f12018-12-07 16:41:02 -08003148status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003149{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003150 ALOGV("%s portId %d", __FUNCTION__, portId);
3151
3152 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3153 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003154 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003155 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003156 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003157 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003158 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003159 if (client->active()) {
3160 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3161 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003162 }
3163
Eric Laurent8f42ea12018-08-08 09:08:25 -07003164 audio_session_t session = client->session();
3165
Eric Laurent4eb58f12018-12-07 16:41:02 -08003166 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003167
Eric Laurent4eb58f12018-12-07 16:41:02 -08003168 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003169
Eric Laurent4eb58f12018-12-07 16:41:02 -08003170 status_t status = inputDesc->start();
3171 if (status != NO_ERROR) {
3172 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003173 }
Eric Laurente552edb2014-03-10 17:42:56 -07003174
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003175 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003176 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003177 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003178
Eric Laurent8f42ea12018-08-08 09:08:25 -07003179 // indicate active capture to sound trigger service if starting capture from a mic on
3180 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003181 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003182 if (device != nullptr) {
3183 status = setInputDevice(input, device, true /* force */);
3184 } else {
3185 ALOGW("%s no new input device can be found for descriptor %d",
3186 __FUNCTION__, inputDesc->getId());
3187 status = BAD_VALUE;
3188 }
Eric Laurente552edb2014-03-10 17:42:56 -07003189
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003190 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003191 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003192 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003193 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003194 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3195 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003196 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003197 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003198
François Gaffie11d30102018-11-02 16:09:09 +01003199 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3200 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003201 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003202 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003203 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003204
Eric Laurent8f42ea12018-08-08 09:08:25 -07003205 // automatically enable the remote submix output when input is started if not
3206 // used by a policy mix of type MIX_TYPE_RECORDERS
3207 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003208 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003209 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003210 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003211 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003212 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3213 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003214 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003215 if (address != "") {
3216 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3217 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003218 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003219 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003220 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003221 } else if (status != NO_ERROR) {
3222 // Restore client activity state.
3223 inputDesc->setClientActive(client, false);
3224 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003225 }
3226
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003227 ALOGV("%s input %d source = %d status = %d exit",
3228 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003229
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003230 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003231}
3232
Eric Laurent8fc147b2018-07-22 19:13:55 -07003233status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003234{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003235 ALOGV("%s portId %d", __FUNCTION__, portId);
3236
3237 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3238 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003239 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003240 return BAD_VALUE;
3241 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003242 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003243 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003244 if (!client->active()) {
3245 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003246 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003247 }
Carter Hsue6139d52021-07-08 10:30:20 +08003248 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003249 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003250
Eric Laurent8f42ea12018-08-08 09:08:25 -07003251 inputDesc->stop();
3252 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003253 auto current_source = inputDesc->source();
3254 setInputDevice(input, getNewInputDevice(inputDesc),
3255 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003256 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003257 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003258 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003259 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003260 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3261 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003262 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003263 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003264
3265 // automatically disable the remote submix output when input is stopped if not
3266 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003267 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003268 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003269 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003270 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003271 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3272 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003273 }
3274 if (address != "") {
3275 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3276 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003277 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003278 }
3279 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003280 resetInputDevice(input);
3281
3282 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3283 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003284 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3285 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003286 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003287 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003288 }
3289 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003290 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003291 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003292}
3293
Eric Laurent8fc147b2018-07-22 19:13:55 -07003294void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003295{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003296 ALOGV("%s portId %d", __FUNCTION__, portId);
3297
3298 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3299 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003300 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003301 return;
3302 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003303 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003304 audio_io_handle_t input = inputDesc->mIoHandle;
3305
Eric Laurent8f42ea12018-08-08 09:08:25 -07003306 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003307
Andy Hung39efb7a2018-09-26 15:39:28 -07003308 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003309
3310 // If no more clients are present in this session, park effects to an orphan chain
3311 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3312 if (clientsOnSession.size() == 0) {
3313 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3314 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003315 if (inputDesc->getClientCount() > 0) {
3316 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003317 return;
3318 }
3319
Eric Laurent05b90f82014-08-27 15:32:29 -07003320 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003321 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003322 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003323}
3324
Eric Laurent8f42ea12018-08-08 09:08:25 -07003325void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003326{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003327 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003328
3329 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003330 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003331 }
3332}
3333
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3335{
3336 stopInput(portId);
3337 releaseInput(portId);
3338}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003339
Eric Laurent0dd51852019-04-19 18:18:58 -07003340void AudioPolicyManager::checkCloseInputs() {
3341 // After connecting or disconnecting an input device, close input if:
3342 // - it has no client (was just opened to check profile) OR
3343 // - none of its supported devices are connected anymore OR
3344 // - one of its clients cannot be routed to one of its supported
3345 // devices anymore. Otherwise update device selection
3346 std::vector<audio_io_handle_t> inputsToClose;
3347 for (size_t i = 0; i < mInputs.size(); i++) {
3348 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3349 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003350 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003351 inputsToClose.push_back(mInputs.keyAt(i));
3352 } else {
3353 bool close = false;
3354 for (const auto& client : input->clientsList()) {
3355 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003356 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3357 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003358 if (!input->supportedDevices().contains(device)) {
3359 close = true;
3360 break;
3361 }
3362 }
3363 if (close) {
3364 inputsToClose.push_back(mInputs.keyAt(i));
3365 } else {
3366 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3367 }
3368 }
3369 }
3370
3371 for (const audio_io_handle_t handle : inputsToClose) {
3372 ALOGV("%s closing input %d", __func__, handle);
3373 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003374 }
Eric Laurentd4692962014-05-05 18:13:44 -07003375}
3376
François Gaffie251c7f02018-11-07 10:41:08 +01003377void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003378{
3379 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003380 if (indexMin < 0 || indexMax < 0) {
3381 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3382 return;
3383 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003384 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003385
3386 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003387 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3388 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003389 continue;
3390 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003391 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003392 }
Eric Laurente552edb2014-03-10 17:42:56 -07003393}
3394
Eric Laurente0720872014-03-11 09:30:41 -07003395status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003396 int index,
3397 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003398{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003399 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003400 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3401 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3402 return NO_ERROR;
3403 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003404 ALOGV("%s: stream %s attributes=%s", __func__,
3405 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003406 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003407}
3408
Eric Laurente0720872014-03-11 09:30:41 -07003409status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003410 int *index,
3411 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003412{
François Gaffiec005e562018-11-06 15:04:49 +01003413 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3414 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003415 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003416 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003417 deviceTypes = mEngine->getOutputDevicesForStream(
3418 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003419 }
jiabin9a3361e2019-10-01 09:38:30 -07003420 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003421}
3422
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003423status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003424 int index,
3425 audio_devices_t device)
3426{
3427 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003428 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3429 if (group == VOLUME_GROUP_NONE) {
3430 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003431 return BAD_VALUE;
3432 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003433 ALOGV("%s: group %d matching with %s index %d",
3434 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003435 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003436 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003437 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003438 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3439 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3440 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3441 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003442 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3443
3444 status = setVolumeCurveIndex(index, device, curves);
3445 if (status != NO_ERROR) {
3446 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3447 return status;
3448 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003449
jiabin9a3361e2019-10-01 09:38:30 -07003450 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003451 auto curCurvAttrs = curves.getAttributes();
3452 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3453 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003454 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003455 } else if (!curves.getStreamTypes().empty()) {
3456 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003457 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003458 } else {
3459 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3460 return BAD_VALUE;
3461 }
jiabin9a3361e2019-10-01 09:38:30 -07003462 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3463 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003464
François Gaffiecfe17322018-11-07 13:41:29 +01003465 // update volume on all outputs and streams matching the following:
3466 // - The requested stream (or a stream matching for volume control) is active on the output
3467 // - The device (or devices) selected by the engine for this stream includes
3468 // the requested device
3469 // - For non default requested device, currently selected device on the output is either the
3470 // requested device or one of the devices selected by the engine for this stream
3471 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3472 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003473 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003474 for (size_t i = 0; i < mOutputs.size(); i++) {
3475 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003476 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003477
jiabin9a3361e2019-10-01 09:38:30 -07003478 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3479 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003480 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003481
3482 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003483 continue;
3484 }
3485 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3486 curDevices.find(device) == curDevices.end()) {
3487 continue;
3488 }
3489 bool applyVolume = false;
3490 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3491 curSrcDevices.insert(device);
3492 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003493 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3494 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003495 } else {
3496 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3497 }
3498 if (!applyVolume) {
3499 continue; // next output
3500 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003501 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3502 // If a higher priority strategy is active, and the output is routed to a device with a
3503 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003504 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003505 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003506 // If the volume source is active with higher priority source, ensure at least Sw Muted
3507 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003508 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3509 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3510 false /*preferredDevice*/);
3511 if (activeClients.empty()) {
3512 continue;
3513 }
3514 bool isPreempted = false;
3515 bool isHigherPriority = productStrategy < strategy;
3516 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003517 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003518 ALOGV("%s: Strategy=%d (\nrequester:\n"
3519 " group %d, volumeGroup=%d attributes=%s)\n"
3520 " higher priority source active:\n"
3521 " volumeGroup=%d attributes=%s) \n"
3522 " on output %zu, bailing out", __func__, productStrategy,
3523 group, group, toString(attributes).c_str(),
3524 client->volumeSource(), toString(client->attributes()).c_str(), i);
3525 applyVolume = false;
3526 isPreempted = true;
3527 break;
3528 }
3529 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003530 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003531 applyVolume = true;
3532 }
3533 }
3534 if (isPreempted || applyVolume) {
3535 break;
3536 }
3537 }
3538 if (!applyVolume) {
3539 continue; // next output
3540 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003541 }
François Gaffieed91f582020-01-31 10:35:37 +01003542 //FIXME: workaround for truncated touch sounds
3543 // delayed volume change for system stream to be removed when the problem is
3544 // handled by system UI
3545 status_t volStatus = checkAndSetVolume(
3546 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003547 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003548 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3549 if (volStatus != NO_ERROR) {
3550 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003551 }
3552 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003553
3554 // update voice volume if the an active call route exists
3555 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3556 && (curSrcDevices.find(
3557 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3558 != curSrcDevices.end())) {
3559 bool isVoiceVolSrc;
3560 bool isBtScoVolSrc;
3561 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3562 isVoiceVolSrc, isBtScoVolSrc, __func__)
3563 && (isVoiceVolSrc || isBtScoVolSrc)) {
3564 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3565 }
3566 }
3567
François Gaffiecfe17322018-11-07 13:41:29 +01003568 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3569 return status;
3570}
3571
François Gaffieaaac0fd2018-11-22 17:56:39 +01003572status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003573 audio_devices_t device,
3574 IVolumeCurves &volumeCurves)
3575{
3576 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3577 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003578 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3579 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003580 (index > volumeCurves.getVolumeIndexMax())) {
3581 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3582 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3583 return BAD_VALUE;
3584 }
3585 if (!audio_is_output_device(device)) {
3586 return BAD_VALUE;
3587 }
3588
3589 // Force max volume if stream cannot be muted
3590 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3591
François Gaffieaaac0fd2018-11-22 17:56:39 +01003592 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003593 volumeCurves.addCurrentVolumeIndex(device, index);
3594 return NO_ERROR;
3595}
3596
3597status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3598 int &index,
3599 audio_devices_t device)
3600{
3601 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3602 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003603 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003604 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003605 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003606 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003607 }
jiabin9a3361e2019-10-01 09:38:30 -07003608 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003609}
3610
3611status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3612 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003613 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003614{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003615 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003616 return BAD_VALUE;
3617 }
jiabin9a3361e2019-10-01 09:38:30 -07003618 index = curves.getVolumeIndex(deviceTypes);
3619 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003620 return NO_ERROR;
3621}
3622
3623status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3624 int &index)
3625{
3626 index = getVolumeCurves(attr).getVolumeIndexMin();
3627 return NO_ERROR;
3628}
3629
3630status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3631 int &index)
3632{
3633 index = getVolumeCurves(attr).getVolumeIndexMax();
3634 return NO_ERROR;
3635}
3636
Eric Laurent36829f92017-04-07 19:04:42 -07003637audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003638{
3639 // select one output among several suitable for global effects.
3640 // The priority is as follows:
3641 // 1: An offloaded output. If the effect ends up not being offloadable,
3642 // AudioFlinger will invalidate the track and the offloaded output
3643 // will be closed causing the effect to be moved to a PCM output.
3644 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003645 // 3: The primary output
3646 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003647
François Gaffiec005e562018-11-06 15:04:49 +01003648 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3649 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003650 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003651
Eric Laurent36829f92017-04-07 19:04:42 -07003652 if (outputs.size() == 0) {
3653 return AUDIO_IO_HANDLE_NONE;
3654 }
Eric Laurente552edb2014-03-10 17:42:56 -07003655
Eric Laurent36829f92017-04-07 19:04:42 -07003656 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3657 bool activeOnly = true;
3658
3659 while (output == AUDIO_IO_HANDLE_NONE) {
3660 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3661 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3662 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3663
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003664 for (audio_io_handle_t output : outputs) {
3665 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003666 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003667 continue;
3668 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003669 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3670 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003671 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003672 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003673 }
3674 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003675 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003676 }
3677 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003678 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003679 }
3680 }
3681 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3682 output = outputOffloaded;
3683 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3684 output = outputDeepBuffer;
3685 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3686 output = outputPrimary;
3687 } else {
3688 output = outputs[0];
3689 }
3690 activeOnly = false;
3691 }
3692
3693 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003694 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3695 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003696 mMusicEffectOutput = output;
3697 }
3698
3699 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003700 return output;
3701}
3702
Eric Laurent36829f92017-04-07 19:04:42 -07003703audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3704{
3705 return selectOutputForMusicEffects();
3706}
3707
Eric Laurente0720872014-03-11 09:30:41 -07003708status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003709 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003710 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003711 int session,
3712 int id)
3713{
Shunkai Yao29d10572024-03-19 04:31:47 +00003714 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003715 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003716 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003717 index = mInputs.indexOfKey(io);
3718 if (index < 0) {
3719 ALOGW("registerEffect() unknown io %d", io);
3720 return INVALID_OPERATION;
3721 }
Eric Laurente552edb2014-03-10 17:42:56 -07003722 }
3723 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003724 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3725 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3726 || strategy == PRODUCT_STRATEGY_NONE));
3727 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003728}
3729
Eric Laurentc241b0d2018-11-28 09:08:49 -08003730status_t AudioPolicyManager::unregisterEffect(int id)
3731{
3732 if (mEffects.getEffect(id) == nullptr) {
3733 return INVALID_OPERATION;
3734 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003735 if (mEffects.isEffectEnabled(id)) {
3736 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3737 setEffectEnabled(id, false);
3738 }
3739 return mEffects.unregisterEffect(id);
3740}
3741
3742status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3743{
3744 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3745 if (effect == nullptr) {
3746 return INVALID_OPERATION;
3747 }
3748
3749 status_t status = mEffects.setEffectEnabled(id, enabled);
3750 if (status == NO_ERROR) {
3751 mInputs.trackEffectEnabled(effect, enabled);
3752 }
3753 return status;
3754}
3755
Eric Laurent6c796322019-04-09 14:13:17 -07003756
3757status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3758{
3759 mEffects.moveEffects(ids, io);
3760 return NO_ERROR;
3761}
3762
Eric Laurentc75307b2015-03-17 15:29:32 -07003763bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3764{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003765 auto vs = toVolumeSource(stream, false);
3766 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003767}
3768
3769bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3770{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003771 auto vs = toVolumeSource(stream, false);
3772 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003773}
3774
Eric Laurente0720872014-03-11 09:30:41 -07003775bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003776{
3777 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003778 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003779 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003780 return true;
3781 }
3782 }
3783 return false;
3784}
3785
Eric Laurent275e8e92014-11-30 15:14:47 -08003786// Register a list of custom mixes with their attributes and format.
3787// When a mix is registered, corresponding input and output profiles are
3788// added to the remote submix hw module. The profile contains only the
3789// parameters (sampling rate, format...) specified by the mix.
3790// The corresponding input remote submix device is also connected.
3791//
3792// When a remote submix device is connected, the address is checked to select the
3793// appropriate profile and the corresponding input or output stream is opened.
3794//
3795// When capture starts, getInputForAttr() will:
3796// - 1 look for a mix matching the address passed in attribtutes tags if any
3797// - 2 if none found, getDeviceForInputSource() will:
3798// - 2.1 look for a mix matching the attributes source
3799// - 2.2 if none found, default to device selection by policy rules
3800// At this time, the corresponding output remote submix device is also connected
3801// and active playback use cases can be transferred to this mix if needed when reconnecting
3802// after AudioTracks are invalidated
3803//
3804// When playback starts, getOutputForAttr() will:
3805// - 1 look for a mix matching the address passed in attribtutes tags if any
3806// - 2 if none found, look for a mix matching the attributes usage
3807// - 3 if none found, default to device and output selection by policy rules.
3808
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003809status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003810{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003811 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3812 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003813 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003814 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003815 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003816 // examine each mix's route type
3817 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003818 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003819 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3820 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3821 ALOGE("Unsupported Policy Mix %zu of %zu: "
3822 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3823 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003824 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003825 break;
3826 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003827 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3828 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003829 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003830 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3831 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003832 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003833 rSubmixModule = mHwModules.getModuleFromName(
3834 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3835 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003836 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003837 i);
3838 res = INVALID_OPERATION;
3839 break;
3840 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003841 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003842
Eric Laurent97ac8712018-07-27 18:59:02 -07003843 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003844 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003845 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003846 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003847 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3848 } else {
3849 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3850 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003851 }
François Gaffie036e1e92015-03-19 10:16:24 +01003852
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003853 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003854 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003855 res = INVALID_OPERATION;
3856 break;
3857 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003858 audio_config_t outputConfig = mix.mFormat;
3859 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003860 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3861 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003862 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3863 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003864 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003865 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3866 audio_is_linear_pcm(outputConfig.format)
3867 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003868 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003869 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3870 audio_is_linear_pcm(inputConfig.format)
3871 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003872
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003873 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003874 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003875 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003876 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003877 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003878 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003879 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003880 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3881 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003882 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003883 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003884 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003885
3886 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3887 mix.mDeviceType, mix.mDeviceAddress,
3888 String8(), AUDIO_FORMAT_DEFAULT);
3889 if (device == nullptr) {
3890 res = INVALID_OPERATION;
3891 break;
3892 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003893
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003894 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003895 // First try to find an already opened output supporting the device
3896 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003897 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003898
Eric Laurentc529cf62020-04-17 18:19:10 -07003899 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003900 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003901 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003902 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003903 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003904 } else {
3905 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003906 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003907 }
3908 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003909 // If no output found, try to find a direct output profile supporting the device
3910 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3911 sp<HwModule> module = mHwModules[i];
3912 for (size_t j = 0;
3913 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3914 j++) {
3915 sp<IOProfile> profile = module->getOutputProfiles()[j];
3916 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3917 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3918 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003919 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003920 res = INVALID_OPERATION;
3921 } else {
3922 foundOutput = true;
3923 }
3924 }
3925 }
3926 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003927 if (res != NO_ERROR) {
3928 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003929 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003930 res = INVALID_OPERATION;
3931 break;
3932 } else if (!foundOutput) {
3933 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003934 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003935 res = INVALID_OPERATION;
3936 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003937 } else {
3938 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003939 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003940 }
Eric Laurentc722f302014-12-10 11:21:49 -08003941 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003942 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003943 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003944 if (audio_flags::audio_mix_ownership()) {
3945 // Only unregister mixes that were actually registered to not accidentally unregister
3946 // mixes that already existed previously.
3947 unregisterPolicyMixes(registeredMixes);
3948 registeredMixes.clear();
3949 } else {
3950 unregisterPolicyMixes(mixes);
3951 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003952 } else if (checkOutputs) {
3953 checkForDeviceAndOutputChanges();
3954 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003955 }
3956 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003957}
3958
3959status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3960{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003961 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003962 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003963 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003964 sp<HwModule> rSubmixModule;
3965 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003966 for (const auto& mix : mixes) {
3967 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003968
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003969 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003970 rSubmixModule = mHwModules.getModuleFromName(
3971 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3972 if (rSubmixModule == 0) {
3973 res = INVALID_OPERATION;
3974 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003975 }
3976 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003977
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003978 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003979
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003980 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003981 res = INVALID_OPERATION;
3982 continue;
3983 }
3984
Marvin Ramin0783e202024-03-05 12:45:50 +01003985 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003986 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01003987 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3988 status_t currentRes =
3989 setDeviceConnectionStateInt(device,
3990 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3991 address.c_str(),
3992 "remote-submix",
3993 AUDIO_FORMAT_DEFAULT);
3994 if (!audio_flags::audio_mix_ownership()) {
3995 res = currentRes;
3996 }
3997 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003998 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003999 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004000 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004001 }
4002 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004003 }
jiabin5740f082019-08-19 15:08:30 -07004004 rSubmixModule->removeOutputProfile(address.c_str());
4005 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004006
Kevin Rocard153f92d2018-12-18 18:33:28 -08004007 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004008 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004009 res = INVALID_OPERATION;
4010 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004011 } else {
4012 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004013 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004014 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004015 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004016
4017 if (res == NO_ERROR && checkOutputs) {
4018 checkForDeviceAndOutputChanges();
4019 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004020 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004021 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004022}
4023
Marvin Raminbdefaf02023-11-01 09:10:32 +01004024status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4025 if (!audio_flags::audio_mix_test_api()) {
4026 return INVALID_OPERATION;
4027 }
4028
4029 _aidl_return.clear();
4030 _aidl_return.reserve(mPolicyMixes.size());
4031 for (const auto &policyMix: mPolicyMixes) {
4032 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4033 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4034 policyMix->mCbFlags);
4035 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004036 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004037 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004038 }
4039
Vlad Popaa5d73f32024-03-08 16:05:38 -08004040 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004041 return OK;
4042}
4043
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004044status_t AudioPolicyManager::updatePolicyMix(
4045 const AudioMix& mix,
4046 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4047 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4048 if (res == NO_ERROR) {
4049 checkForDeviceAndOutputChanges();
4050 updateCallAndOutputRouting();
4051 }
4052 return res;
4053}
4054
Mikhail Naganov100f0122018-11-29 11:22:16 -08004055void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4056{
4057 size_t i = 0;
4058 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4059 for (const auto& fmt : mManualSurroundFormats) {
4060 if (i++ != 0) dst->append(", ");
4061 std::string sfmt;
4062 FormatConverter::toString(fmt, sfmt);
4063 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4064 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4065 }
4066}
4067
Eric Laurentc529cf62020-04-17 18:19:10 -07004068// Returns true if all devices types match the predicate and are supported by one HW module
4069bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004070 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004071 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004072 const char *context,
4073 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004074 for (size_t i = 0; i < devices.size(); i++) {
4075 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004076 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004077 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004078 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004079 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004080 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004081 return false;
4082 }
4083 }
4084 return true;
4085}
4086
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004087void AudioPolicyManager::changeOutputDevicesMuteState(
4088 const AudioDeviceTypeAddrVector& devices) {
4089 ALOGVV("%s() num devices %zu", __func__, devices.size());
4090
4091 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4092 getSoftwareOutputsForDevices(devices);
4093
4094 for (size_t i = 0; i < outputs.size(); i++) {
4095 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4096 DeviceVector prevDevices = outputDesc->devices();
4097 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4098 }
4099}
4100
4101std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4102 const AudioDeviceTypeAddrVector& devices) const
4103{
4104 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4105 DeviceVector deviceDescriptors;
4106 for (size_t j = 0; j < devices.size(); j++) {
4107 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4108 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4109 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4110 ALOGE("%s: device type %#x address %s not supported or not an output device",
4111 __func__, devices[j].mType, devices[j].getAddress());
4112 continue;
4113 }
4114 deviceDescriptors.add(desc);
4115 }
4116 for (size_t i = 0; i < mOutputs.size(); i++) {
4117 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4118 continue;
4119 }
4120 outputs.push_back(mOutputs.valueAt(i));
4121 }
4122 return outputs;
4123}
4124
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004125status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004126 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004127 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004128 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4129 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004130 }
4131 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004132 if (res != NO_ERROR) {
4133 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4134 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004135 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004136
4137 checkForDeviceAndOutputChanges();
4138 updateCallAndOutputRouting();
4139
4140 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004141}
4142
4143status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4144 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004145 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4146 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004147 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004148 __FUNCTION__, uid);
4149 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004150 }
4151
Eric Laurentc529cf62020-04-17 18:19:10 -07004152 checkForDeviceAndOutputChanges();
4153 updateCallAndOutputRouting();
4154
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004155 return res;
4156}
4157
Eric Laurent2517af32020-11-25 15:31:27 +01004158
jiabin0a488932020-08-07 17:32:40 -07004159status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4160 device_role_t role,
4161 const AudioDeviceTypeAddrVector &devices) {
4162 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4163 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004164
Eric Laurentc529cf62020-04-17 18:19:10 -07004165 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004166 return BAD_VALUE;
4167 }
jiabin0a488932020-08-07 17:32:40 -07004168 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004169 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004170 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4171 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004172 return status;
4173 }
4174
4175 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004176
4177 bool forceVolumeReeval = false;
4178 // FIXME: workaround for truncated touch sounds
4179 // to be removed when the problem is handled by system UI
4180 uint32_t delayMs = 0;
4181 if (strategy == mCommunnicationStrategy) {
4182 forceVolumeReeval = true;
4183 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4184 updateInputRouting();
4185 }
4186 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004187
4188 return NO_ERROR;
4189}
4190
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004191void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4192 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004193{
4194 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004195 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004196 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004197 // Only apply special touch sound delay once
4198 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004199 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004200 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004201 for (size_t i = 0; i < mOutputs.size(); i++) {
4202 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4203 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004204 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4205 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004206 // As done in setDeviceConnectionState, we could also fix default device issue by
4207 // preventing the force re-routing in case of default dev that distinguishes on address.
4208 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004209 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004210 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004211 // If the device is using preferred mixer attributes, the output need to reopen
4212 // with default configuration when the new selected devices are different from
4213 // current routing devices.
4214 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4215 continue;
4216 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304217
4218 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4219 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004220 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004221 // Only apply special touch sound delay once
4222 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004223 }
4224 if (forceVolumeReeval && !newDevices.isEmpty()) {
4225 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4226 }
4227 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004228 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004229 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004230}
4231
Eric Laurent2517af32020-11-25 15:31:27 +01004232void AudioPolicyManager::updateInputRouting() {
4233 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304234 // Skip for hotword recording as the input device switch
4235 // is handled within sound trigger HAL
4236 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4237 continue;
4238 }
Eric Laurent2517af32020-11-25 15:31:27 +01004239 auto newDevice = getNewInputDevice(activeDesc);
4240 // Force new input selection if the new device can not be reached via current input
4241 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4242 setInputDevice(activeDesc->mIoHandle, newDevice);
4243 } else {
4244 closeInput(activeDesc->mIoHandle);
4245 }
4246 }
4247}
4248
Paul Wang5d7cdb52022-11-22 09:45:06 +00004249status_t
4250AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4251 device_role_t role,
4252 const AudioDeviceTypeAddrVector &devices) {
4253 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4254 dumpAudioDeviceTypeAddrVector(devices).c_str());
4255
Eric Laurent78fedbf2023-03-09 14:40:44 +01004256 if (!areAllDevicesSupported(
4257 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004258 return BAD_VALUE;
4259 }
4260 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4261 if (status != NO_ERROR) {
4262 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4263 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4264 return status;
4265 }
4266
4267 checkForDeviceAndOutputChanges();
4268
4269 bool forceVolumeReeval = false;
4270 // TODO(b/263479999): workaround for truncated touch sounds
4271 // to be removed when the problem is handled by system UI
4272 uint32_t delayMs = 0;
4273 if (strategy == mCommunnicationStrategy) {
4274 forceVolumeReeval = true;
4275 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4276 updateInputRouting();
4277 }
4278 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4279
4280 return NO_ERROR;
4281}
4282
4283status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4284 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004285{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004286 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004287
Paul Wang5d7cdb52022-11-22 09:45:06 +00004288 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004289 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004290 ALOGW_IF(status != NAME_NOT_FOUND,
4291 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004292 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004293 return status;
4294 }
4295
4296 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004297
4298 bool forceVolumeReeval = false;
4299 // FIXME: workaround for truncated touch sounds
4300 // to be removed when the problem is handled by system UI
4301 uint32_t delayMs = 0;
4302 if (strategy == mCommunnicationStrategy) {
4303 forceVolumeReeval = true;
4304 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4305 updateInputRouting();
4306 }
4307 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004308
4309 return NO_ERROR;
4310}
4311
jiabin0a488932020-08-07 17:32:40 -07004312status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4313 device_role_t role,
4314 AudioDeviceTypeAddrVector &devices) {
4315 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004316}
4317
Jiabin Huang3b98d322020-09-03 17:54:16 +00004318status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4319 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4320 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4321 dumpAudioDeviceTypeAddrVector(devices).c_str());
4322
Mikhail Naganov55773032020-10-01 15:08:13 -07004323 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004324 return BAD_VALUE;
4325 }
4326 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4327 ALOGW_IF(status != NO_ERROR,
4328 "Engine could not set preferred devices %s for audio source %d role %d",
4329 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4330
4331 return status;
4332}
4333
4334status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4335 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4336 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4337 dumpAudioDeviceTypeAddrVector(devices).c_str());
4338
Mikhail Naganov55773032020-10-01 15:08:13 -07004339 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004340 return BAD_VALUE;
4341 }
4342 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4343 ALOGW_IF(status != NO_ERROR,
4344 "Engine could not add preferred devices %s for audio source %d role %d",
4345 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4346
Eric Laurent2517af32020-11-25 15:31:27 +01004347 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004348 return status;
4349}
4350
4351status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4352 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4353{
4354 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4355 dumpAudioDeviceTypeAddrVector(devices).c_str());
4356
Eric Laurent78fedbf2023-03-09 14:40:44 +01004357 if (!areAllDevicesSupported(
4358 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004359 return BAD_VALUE;
4360 }
4361
4362 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4363 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004364 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004365 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004366 if (status == NO_ERROR) {
4367 updateInputRouting();
4368 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004369 return status;
4370}
4371
4372status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4373 device_role_t role) {
4374 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4375
4376 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004377 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004378 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004379 if (status == NO_ERROR) {
4380 updateInputRouting();
4381 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004382 return status;
4383}
4384
4385status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4386 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4387 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4388}
4389
Oscar Azucena90e77632019-11-27 17:12:28 -08004390status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004391 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004392 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004393 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4394 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004395 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004396 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4397 if (status != NO_ERROR) {
4398 ALOGE("%s() could not set device affinity for userId %d",
4399 __FUNCTION__, userId);
4400 return status;
4401 }
4402
4403 // reevaluate outputs for all devices
4404 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004405 changeOutputDevicesMuteState(devices);
4406 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4407 true /* skipDelays */);
4408 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004409
4410 return NO_ERROR;
4411}
4412
4413status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004414 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004415 AudioDeviceTypeAddrVector devices;
4416 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004417 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4418 if (status != NO_ERROR) {
4419 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4420 __FUNCTION__, userId);
4421 return status;
4422 }
4423
4424 // reevaluate outputs for all devices
4425 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004426 changeOutputDevicesMuteState(devices);
4427 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4428 true /* skipDelays */);
4429 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004430
4431 return NO_ERROR;
4432}
4433
Andy Hungc29d82b2018-10-05 12:23:17 -07004434void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004435{
Andy Hungc29d82b2018-10-05 12:23:17 -07004436 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004437 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004438 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004439 std::string stateLiteral;
4440 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004441 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004442 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4443 "communications", "media", "record", "dock", "system",
4444 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4445 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4446 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004447 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4448 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4449 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4450 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4451 dst->append(" (MANUAL: ");
4452 dumpManualSurroundFormats(dst);
4453 dst->append(")");
4454 }
4455 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004456 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004457 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4458 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004459 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004460 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004461
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004462 dst->append("\n");
4463 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4464 dst->append("\n");
4465 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004466 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004467 mOutputs.dump(dst);
4468 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004469 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004470 mAudioPatches.dump(dst);
4471 mPolicyMixes.dump(dst);
4472 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004473
Kevin Rocardb99cc752019-03-21 20:52:24 -07004474 dst->appendFormat(" AllowedCapturePolicies:\n");
4475 for (auto& policy : mAllowedCapturePolicies) {
4476 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4477 }
4478
jiabina84c3d32022-12-02 18:59:55 +00004479 dst->appendFormat(" Preferred mixer audio configuration:\n");
4480 for (const auto it : mPreferredMixerAttrInfos) {
4481 dst->appendFormat(" - device port id: %d\n", it.first);
4482 for (const auto preferredMixerInfoIt : it.second) {
4483 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4484 preferredMixerInfoIt.second->dump(dst);
4485 }
4486 }
4487
François Gaffiec005e562018-11-06 15:04:49 +01004488 dst->appendFormat("\nPolicy Engine dump:\n");
4489 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004490}
4491
4492status_t AudioPolicyManager::dump(int fd)
4493{
4494 String8 result;
4495 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004496 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004497 return NO_ERROR;
4498}
4499
Kevin Rocardb99cc752019-03-21 20:52:24 -07004500status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4501{
4502 mAllowedCapturePolicies[uid] = capturePolicy;
4503 return NO_ERROR;
4504}
4505
Eric Laurente552edb2014-03-10 17:42:56 -07004506// This function checks for the parameters which can be offloaded.
4507// This can be enhanced depending on the capability of the DSP and policy
4508// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004509audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004510{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004511 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004512 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004513 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004514 offloadInfo.format,
4515 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4516 offloadInfo.has_video);
4517
jiabin2b9d5a12021-12-10 01:06:29 +00004518 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004519 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004520 }
4521
4522 // See if there is a profile to support this.
4523 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004524 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004525 offloadInfo.sample_rate,
4526 offloadInfo.format,
4527 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004528 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4529 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004530 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4531 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4532 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004533 if (profile == nullptr) {
4534 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4535 }
4536 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4537 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4538 }
4539 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004540}
4541
Michael Chana94fbb22018-04-24 14:31:19 +10004542bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4543 const audio_attributes_t& attributes) {
4544 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004545 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004546 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4547 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004548 config.sample_rate,
4549 config.format,
4550 config.channel_mask,
4551 output_flags,
4552 true /* directOnly */);
4553 ALOGV("%s() profile %sfound with name: %s, "
4554 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4555 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004556 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004557 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004558
4559 // also try the MSD module if compatible profile not found
4560 if (profile == nullptr) {
4561 profile = getMsdProfileForOutput(outputDevices,
4562 config.sample_rate,
4563 config.format,
4564 config.channel_mask,
4565 output_flags,
4566 true /* directOnly */);
4567 ALOGV("%s() MSD profile %sfound with name: %s, "
4568 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4569 __FUNCTION__, profile != 0 ? "" : "NOT ",
4570 (profile != 0 ? profile->getTagName().c_str() : "null"),
4571 config.sample_rate, config.format, config.channel_mask, output_flags);
4572 }
4573 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004574}
4575
jiabin2b9d5a12021-12-10 01:06:29 +00004576bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4577 bool durationIgnored) {
4578 if (mMasterMono) {
4579 return false; // no offloading if mono is set.
4580 }
4581
4582 // Check if offload has been disabled
4583 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4584 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4585 return false;
4586 }
4587
4588 // Check if stream type is music, then only allow offload as of now.
4589 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4590 {
4591 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4592 return false;
4593 }
4594
4595 //TODO: enable audio offloading with video when ready
4596 const bool allowOffloadWithVideo =
4597 property_get_bool("audio.offload.video", false /* default_value */);
4598 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4599 ALOGV("%s: has_video == true, returning false", __func__);
4600 return false;
4601 }
4602
4603 //If duration is less than minimum value defined in property, return false
4604 const int min_duration_secs = property_get_int32(
4605 "audio.offload.min.duration.secs", -1 /* default_value */);
4606 if (!durationIgnored) {
4607 if (min_duration_secs >= 0) {
4608 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4609 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4610 __func__, min_duration_secs);
4611 return false;
4612 }
4613 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4614 ALOGV("%s: Offload denied by duration < default min(=%u)",
4615 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4616 return false;
4617 }
4618 }
4619
4620 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4621 // creating an offloaded track and tearing it down immediately after start when audioflinger
4622 // detects there is an active non offloadable effect.
4623 // FIXME: We should check the audio session here but we do not have it in this context.
4624 // This may prevent offloading in rare situations where effects are left active by apps
4625 // in the background.
4626 if (mEffects.isNonOffloadableEffectEnabled()) {
4627 return false;
4628 }
4629
4630 return true;
4631}
4632
4633audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4634 const audio_config_t *config) {
4635 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4636 offloadInfo.format = config->format;
4637 offloadInfo.sample_rate = config->sample_rate;
4638 offloadInfo.channel_mask = config->channel_mask;
4639 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4640 offloadInfo.has_video = false;
4641 offloadInfo.is_streaming = false;
4642 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4643
4644 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4645 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4646 audio_flags_to_audio_output_flags(attr->flags, &flags);
4647 // only retain flags that will drive compressed offload or passthrough
4648 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4649 if (offloadPossible) {
4650 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4651 }
4652 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4653
Dorin Drimusfae3c642022-03-17 18:36:30 +01004654 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004655 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004656 DeviceVector outputDevices = engineOutputDevices;
4657 // the MSD module checks for different conditions and output devices
4658 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4659 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4660 continue;
4661 }
4662 outputDevices = getMsdAudioOutDevices();
4663 }
jiabin2b9d5a12021-12-10 01:06:29 +00004664 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004665 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004666 config->sample_rate, nullptr /*updatedSamplingRate*/,
4667 config->format, nullptr /*updatedFormat*/,
4668 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004669 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004670 continue;
4671 }
4672 // reject profiles not corresponding to a device currently available
4673 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4674 continue;
4675 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004676 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4677 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004678 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004679 != AUDIO_DIRECT_NOT_SUPPORTED) {
4680 // Already reports offload gapless supported. No need to report offload support.
4681 continue;
4682 }
4683 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4684 != AUDIO_OUTPUT_FLAG_NONE) {
4685 // If offload gapless is reported, no need to report offload support.
4686 directMode = (audio_direct_mode_t) ((directMode &
4687 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4688 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4689 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004690 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004691 }
4692 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004693 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004694 }
4695 }
4696 }
4697 return directMode;
4698}
4699
Dorin Drimusf2196d82022-01-03 12:11:18 +01004700status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4701 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004702 if (mEffects.isNonOffloadableEffectEnabled()) {
4703 return OK;
4704 }
jiabinf1c73972022-04-14 16:28:52 -07004705 DeviceVector devices;
4706 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004707 if (status != OK) {
4708 return status;
4709 }
4710 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4711 if (devices.empty()) {
4712 return OK; // no output devices for the attributes
4713 }
jiabinf1c73972022-04-14 16:28:52 -07004714 return getProfilesForDevices(devices, audioProfilesVector,
4715 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004716}
4717
jiabina84c3d32022-12-02 18:59:55 +00004718status_t AudioPolicyManager::getSupportedMixerAttributes(
4719 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4720 ALOGV("%s, portId=%d", __func__, portId);
4721 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4722 if (deviceDescriptor == nullptr) {
4723 ALOGE("%s the requested device is currently unavailable", __func__);
4724 return BAD_VALUE;
4725 }
jiabin96daffc2023-05-11 17:51:55 +00004726 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4727 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4728 deviceDescriptor->type());
4729 return BAD_VALUE;
4730 }
jiabina84c3d32022-12-02 18:59:55 +00004731 for (const auto& hwModule : mHwModules) {
4732 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4733 if (curProfile->supportsDevice(deviceDescriptor)) {
4734 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4735 }
4736 }
4737 }
4738 return NO_ERROR;
4739}
4740
4741status_t AudioPolicyManager::setPreferredMixerAttributes(
4742 const audio_attributes_t *attr,
4743 audio_port_handle_t portId,
4744 uid_t uid,
4745 const audio_mixer_attributes_t *mixerAttributes) {
4746 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4747 "mixerBehavior=%d}, uid=%d, portId=%u",
4748 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4749 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4750 mixerAttributes->mixer_behavior, uid, portId);
4751 if (attr->usage != AUDIO_USAGE_MEDIA) {
4752 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4753 return BAD_VALUE;
4754 }
4755 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4756 if (deviceDescriptor == nullptr) {
4757 ALOGE("%s the requested device is currently unavailable", __func__);
4758 return BAD_VALUE;
4759 }
4760 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4761 ALOGE("%s(%d), type=%d, is not a usb output device",
4762 __func__, portId, deviceDescriptor->type());
4763 return BAD_VALUE;
4764 }
4765
4766 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4767 audio_flags_to_audio_output_flags(attr->flags, &flags);
4768 flags = (audio_output_flags_t) (flags |
4769 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4770 sp<IOProfile> profile = nullptr;
4771 DeviceVector devices(deviceDescriptor);
4772 for (const auto& hwModule : mHwModules) {
4773 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4774 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004775 && curProfile->getCompatibilityScore(
4776 devices,
4777 mixerAttributes->config.sample_rate,
4778 nullptr /*updatedSamplingRate*/,
4779 mixerAttributes->config.format,
4780 nullptr /*updatedFormat*/,
4781 mixerAttributes->config.channel_mask,
4782 nullptr /*updatedChannelMask*/,
4783 flags,
4784 false /*exactMatchRequiredForInputFlags*/)
4785 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004786 profile = curProfile;
4787 break;
4788 }
4789 }
4790 }
4791 if (profile == nullptr) {
4792 ALOGE("%s, there is no compatible profile found", __func__);
4793 return BAD_VALUE;
4794 }
4795
4796 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4797 sp<PreferredMixerAttributesInfo>::make(
4798 uid, portId, profile, flags, *mixerAttributes);
4799 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4800 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4801
4802 // If 1) there is any client from the preferred mixer configuration owner that is currently
4803 // active and matches the strategy and 2) current output is on the preferred device and the
4804 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4805 // configuration.
4806 std::vector<audio_io_handle_t> outputsToReopen;
4807 for (size_t i = 0; i < mOutputs.size(); i++) {
4808 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004809 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4810 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004811 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004812 } else {
4813 for (const auto &client: output->getActiveClients()) {
4814 if (client->uid() == uid && client->strategy() == strategy) {
4815 client->setIsInvalid();
4816 outputsToReopen.push_back(output->mIoHandle);
4817 }
jiabina84c3d32022-12-02 18:59:55 +00004818 }
4819 }
4820 }
4821 }
4822 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4823 config.sample_rate = mixerAttributes->config.sample_rate;
4824 config.channel_mask = mixerAttributes->config.channel_mask;
4825 config.format = mixerAttributes->config.format;
4826 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004827 sp<SwAudioOutputDescriptor> desc =
4828 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4829 if (desc == nullptr) {
4830 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4831 continue;
4832 }
jiabin220eea12024-05-17 17:55:20 +00004833 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004834 }
4835
4836 return NO_ERROR;
4837}
4838
4839sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004840 audio_port_handle_t devicePortId,
4841 product_strategy_t strategy,
4842 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004843 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4844 if (it == mPreferredMixerAttrInfos.end()) {
4845 return nullptr;
4846 }
jiabind9a58d32023-06-01 17:57:30 +00004847 if (activeBitPerfectPreferred) {
4848 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004849 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004850 return info;
4851 }
4852 }
jiabina84c3d32022-12-02 18:59:55 +00004853 }
jiabind9a58d32023-06-01 17:57:30 +00004854 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4855 return strategyMatchedMixerAttrInfoIt == it->second.end()
4856 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004857}
4858
4859status_t AudioPolicyManager::getPreferredMixerAttributes(
4860 const audio_attributes_t *attr,
4861 audio_port_handle_t portId,
4862 audio_mixer_attributes_t* mixerAttributes) {
4863 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4864 portId, mEngine->getProductStrategyForAttributes(*attr));
4865 if (info == nullptr) {
4866 return NAME_NOT_FOUND;
4867 }
4868 *mixerAttributes = info->getMixerAttributes();
4869 return NO_ERROR;
4870}
4871
4872status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4873 audio_port_handle_t portId,
4874 uid_t uid) {
4875 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4876 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4877 if (preferredMixerAttrInfo == nullptr) {
4878 return NAME_NOT_FOUND;
4879 }
4880 if (preferredMixerAttrInfo->getUid() != uid) {
4881 ALOGE("%s, requested uid=%d, owned uid=%d",
4882 __func__, uid, preferredMixerAttrInfo->getUid());
4883 return PERMISSION_DENIED;
4884 }
4885 mPreferredMixerAttrInfos[portId].erase(strategy);
4886 if (mPreferredMixerAttrInfos[portId].empty()) {
4887 mPreferredMixerAttrInfos.erase(portId);
4888 }
4889
4890 // Reconfig existing output
4891 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4892 for (size_t i = 0; i < mOutputs.size(); i++) {
4893 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4894 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4895 }
4896 }
4897 for (const auto output : potentialOutputsToReopen) {
4898 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4899 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4900 preferredMixerAttrInfo->getFlags())) {
4901 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4902 }
4903 }
4904 return NO_ERROR;
4905}
4906
Eric Laurent6a94d692014-05-20 11:18:06 -07004907status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4908 audio_port_type_t type,
4909 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004910 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 unsigned int *generation)
4912{
jiabin19cdba52020-11-24 11:28:58 -08004913 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4914 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004915 return BAD_VALUE;
4916 }
4917 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004918 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004919 *num_ports = 0;
4920 }
4921
4922 size_t portsWritten = 0;
4923 size_t portsMax = *num_ports;
4924 *num_ports = 0;
4925 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004926 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4927 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004928 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004929 for (const auto& dev : mAvailableOutputDevices) {
4930 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004931 continue;
4932 }
4933 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004934 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004935 }
4936 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004937 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004938 }
4939 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004940 for (const auto& dev : mAvailableInputDevices) {
4941 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004942 continue;
4943 }
4944 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004945 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004946 }
4947 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004948 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004949 }
4950 }
4951 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4952 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4953 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4954 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4955 }
4956 *num_ports += mInputs.size();
4957 }
4958 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004959 size_t numOutputs = 0;
4960 for (size_t i = 0; i < mOutputs.size(); i++) {
4961 if (!mOutputs[i]->isDuplicated()) {
4962 numOutputs++;
4963 if (portsWritten < portsMax) {
4964 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4965 }
4966 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004967 }
Eric Laurent84c70242014-06-23 08:46:27 -07004968 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004969 }
4970 }
jiabina84c3d32022-12-02 18:59:55 +00004971
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004973 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 return NO_ERROR;
4975}
4976
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004977status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4978 std::vector<media::AudioPortFw>* _aidl_return) {
4979 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4980 audio_port_v7 port;
4981 dev->toAudioPort(&port);
4982 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4983 _aidl_return->push_back(std::move(aidlPort));
4984 return OK;
4985 };
4986
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004987 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004988 for (const auto& dev : module->getDeclaredDevices()) {
4989 if (role == media::AudioPortRole::NONE ||
4990 ((role == media::AudioPortRole::SOURCE)
4991 == audio_is_input_device(dev->type()))) {
4992 RETURN_STATUS_IF_ERROR(pushPort(dev));
4993 }
4994 }
4995 }
4996 return OK;
4997}
4998
jiabin19cdba52020-11-24 11:28:58 -08004999status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005000{
Eric Laurent99fcae42018-05-17 16:59:18 -07005001 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5002 return BAD_VALUE;
5003 }
5004 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5005 if (dev != 0) {
5006 dev->toAudioPort(port);
5007 return NO_ERROR;
5008 }
5009 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5010 if (dev != 0) {
5011 dev->toAudioPort(port);
5012 return NO_ERROR;
5013 }
5014 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5015 if (out != 0) {
5016 out->toAudioPort(port);
5017 return NO_ERROR;
5018 }
5019 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5020 if (in != 0) {
5021 in->toAudioPort(port);
5022 return NO_ERROR;
5023 }
5024 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005025}
5026
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005027status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5028 audio_patch_handle_t *handle,
5029 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005030{
François Gaffieafd4cea2019-11-18 15:50:22 +01005031 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005032 if (handle == NULL || patch == NULL) {
5033 return BAD_VALUE;
5034 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005035 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005036 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005037 return BAD_VALUE;
5038 }
5039 // only one source per audio patch supported for now
5040 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005041 return INVALID_OPERATION;
5042 }
Eric Laurent874c42872014-08-08 15:13:39 -07005043 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005044 return INVALID_OPERATION;
5045 }
Eric Laurent874c42872014-08-08 15:13:39 -07005046 for (size_t i = 0; i < patch->num_sinks; i++) {
5047 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5048 return INVALID_OPERATION;
5049 }
5050 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005051
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005052 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5053 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5054 if (srcDevice == nullptr || sinkDevice == nullptr) {
5055 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5056 return BAD_VALUE;
5057 }
5058 ALOGV("%s between source %s and sink %s", __func__,
5059 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5060 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5061 // Default attributes, default volume priority, not to infer with non raw audio patches.
5062 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5063 const struct audio_port_config *source = &patch->sources[0];
5064 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005065 new SourceClientDescriptor(
5066 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5067 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
5068 true);
5069 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005070
5071 status_t status =
5072 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5073
5074 if (status != NO_ERROR) {
5075 return INVALID_OPERATION;
5076 }
5077 mAudioSources.add(portId, sourceDesc);
5078 return NO_ERROR;
5079}
5080
5081status_t AudioPolicyManager::connectAudioSourceToSink(
5082 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5083 const struct audio_patch *patch,
5084 audio_patch_handle_t &handle,
5085 uid_t uid, uint32_t delayMs)
5086{
5087 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5088 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5089 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5090 return INVALID_OPERATION;
5091 }
5092 sourceDesc->connect(handle, sinkDevice);
5093 if (isMsdPatch(handle)) {
5094 return NO_ERROR;
5095 }
5096 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5097 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5098 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5099 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5100 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5101 goto FailurePatchAdded;
5102 }
5103 status = swOutput->start();
5104 if (status != NO_ERROR) {
5105 goto FailureSourceAdded;
5106 }
5107 swOutput->addClient(sourceDesc);
5108 status = startSource(swOutput, sourceDesc, &delayMs);
5109 if (status != NO_ERROR) {
5110 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5111 goto FailureSourceActive;
5112 }
5113 if (delayMs != 0) {
5114 usleep(delayMs * 1000);
5115 }
5116 return NO_ERROR;
5117
5118FailureSourceActive:
5119 swOutput->stop();
5120 releaseOutput(sourceDesc->portId());
5121FailureSourceAdded:
5122 sourceDesc->setSwOutput(nullptr);
5123FailurePatchAdded:
5124 releaseAudioPatchInternal(handle);
5125 return INVALID_OPERATION;
5126}
5127
5128status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5129 audio_patch_handle_t *handle,
5130 uid_t uid, uint32_t delayMs,
5131 const sp<SourceClientDescriptor>& sourceDesc)
5132{
5133 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005134 sp<AudioPatch> patchDesc;
5135 ssize_t index = mAudioPatches.indexOfKey(*handle);
5136
François Gaffieafd4cea2019-11-18 15:50:22 +01005137 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5138 patch->sources[0].role,
5139 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005140#if LOG_NDEBUG == 0
5141 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005142 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5143 patch->sinks[i].role,
5144 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005145 }
5146#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005147
5148 if (index >= 0) {
5149 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005150 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5151 __func__, mUidCached, patchDesc->getUid(), uid);
5152 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005153 return INVALID_OPERATION;
5154 }
5155 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005156 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005157 }
5158
5159 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005160 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005161 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005162 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005163 return BAD_VALUE;
5164 }
Eric Laurent84c70242014-06-23 08:46:27 -07005165 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5166 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005167 if (patchDesc != 0) {
5168 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005169 ALOGV("%s source id differs for patch current id %d new id %d",
5170 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005171 return BAD_VALUE;
5172 }
5173 }
Eric Laurent874c42872014-08-08 15:13:39 -07005174 DeviceVector devices;
5175 for (size_t i = 0; i < patch->num_sinks; i++) {
5176 // Only support mix to devices connection
5177 // TODO add support for mix to mix connection
5178 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005179 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005180 return INVALID_OPERATION;
5181 }
5182 sp<DeviceDescriptor> devDesc =
5183 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5184 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005185 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005186 return BAD_VALUE;
5187 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005188
jiabin66acc432024-02-06 00:57:36 +00005189 if (outputDesc->mProfile->getCompatibilityScore(
5190 DeviceVector(devDesc),
5191 patch->sources[0].sample_rate,
5192 nullptr, // updatedSamplingRate
5193 patch->sources[0].format,
5194 nullptr, // updatedFormat
5195 patch->sources[0].channel_mask,
5196 nullptr, // updatedChannelMask
5197 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005198 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005199 return INVALID_OPERATION;
5200 }
5201 devices.add(devDesc);
5202 }
5203 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005204 return INVALID_OPERATION;
5205 }
Eric Laurent874c42872014-08-08 15:13:39 -07005206
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005208 ALOGV("%s setting device %s on output %d",
5209 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305210 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005211 index = mAudioPatches.indexOfKey(*handle);
5212 if (index >= 0) {
5213 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005214 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 }
5216 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005217 patchDesc->setUid(uid);
5218 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005219 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005220 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005221 return INVALID_OPERATION;
5222 }
5223 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5224 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5225 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005226 // only one sink supported when connecting an input device to a mix
5227 if (patch->num_sinks > 1) {
5228 return INVALID_OPERATION;
5229 }
François Gaffie53615e22015-03-19 09:24:12 +01005230 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 if (inputDesc == NULL) {
5232 return BAD_VALUE;
5233 }
5234 if (patchDesc != 0) {
5235 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5236 return BAD_VALUE;
5237 }
5238 }
François Gaffie11d30102018-11-02 16:09:09 +01005239 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005240 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005241 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005242 return BAD_VALUE;
5243 }
5244
jiabin66acc432024-02-06 00:57:36 +00005245 if (inputDesc->mProfile->getCompatibilityScore(
5246 DeviceVector(device),
5247 patch->sinks[0].sample_rate,
5248 nullptr, /*updatedSampleRate*/
5249 patch->sinks[0].format,
5250 nullptr, /*updatedFormat*/
5251 patch->sinks[0].channel_mask,
5252 nullptr, /*updatedChannelMask*/
5253 // FIXME for the parameter type,
5254 // and the NONE
5255 (audio_output_flags_t)
5256 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 return INVALID_OPERATION;
5258 }
5259 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005260 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005261 device->toString().c_str(), inputDesc->mIoHandle);
5262 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 index = mAudioPatches.indexOfKey(*handle);
5264 if (index >= 0) {
5265 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005266 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 }
5268 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005269 patchDesc->setUid(uid);
5270 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005272 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005273 return INVALID_OPERATION;
5274 }
5275 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5276 // device to device connection
5277 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005278 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 return BAD_VALUE;
5280 }
5281 }
François Gaffie11d30102018-11-02 16:09:09 +01005282 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005284 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005285 return BAD_VALUE;
5286 }
Eric Laurent874c42872014-08-08 15:13:39 -07005287
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 //update source and sink with our own data as the data passed in the patch may
5289 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005290 PatchBuilder patchBuilder;
5291 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005292
5293 // if first sink is to MSD, establish single MSD patch
5294 if (getMsdAudioOutDevices().contains(
5295 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5296 ALOGV("%s patching to MSD", __FUNCTION__);
5297 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5298 goto installPatch;
5299 }
5300
François Gaffieafd4cea2019-11-18 15:50:22 +01005301 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5302 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005303
Eric Laurent874c42872014-08-08 15:13:39 -07005304 for (size_t i = 0; i < patch->num_sinks; i++) {
5305 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005306 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005307 return INVALID_OPERATION;
5308 }
François Gaffie11d30102018-11-02 16:09:09 +01005309 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005310 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005311 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005312 return BAD_VALUE;
5313 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005314 audio_port_config sinkPortConfig = {};
5315 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5316 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005317
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005318 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5319 // volume management purpose (tracking activity)
5320 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5321 // in config XML to reach the sink so that is can be declared as available.
5322 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005323 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005324 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005325 // take care of dynamic routing for SwOutput selection,
5326 audio_attributes_t attributes = sourceDesc->attributes();
5327 audio_stream_type_t stream = sourceDesc->stream();
5328 audio_attributes_t resultAttr;
5329 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5330 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005331 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5332 config.channel_mask =
5333 (audio_channel_mask_get_representation(sourceMask)
5334 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5335 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005336 config.format = sourceDesc->config().format;
5337 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5338 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5339 bool isRequestedDeviceForExclusiveUse = false;
5340 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005341 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005342 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005343 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5344 &stream, sourceDesc->uid(), &config, &flags,
5345 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005346 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005347 if (output == AUDIO_IO_HANDLE_NONE) {
5348 ALOGV("%s no output for device %s",
5349 __FUNCTION__, sinkDevice->toString().c_str());
5350 return INVALID_OPERATION;
5351 }
5352 outputDesc = mOutputs.valueFor(output);
5353 if (outputDesc->isDuplicated()) {
5354 ALOGE("%s output is duplicated", __func__);
5355 return INVALID_OPERATION;
5356 }
François Gaffie7e39df22022-04-26 12:48:49 +02005357 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5358 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005359 } else {
5360 // Same for "raw patches" aka created from createAudioPatch API
5361 SortedVector<audio_io_handle_t> outputs =
5362 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5363 // if the sink device is reachable via an opened output stream, request to
5364 // go via this output stream by adding a second source to the patch
5365 // description
5366 output = selectOutput(outputs);
5367 if (output == AUDIO_IO_HANDLE_NONE) {
5368 ALOGE("%s no output available for internal patch sink", __func__);
5369 return INVALID_OPERATION;
5370 }
5371 outputDesc = mOutputs.valueFor(output);
5372 if (outputDesc->isDuplicated()) {
5373 ALOGV("%s output for device %s is duplicated",
5374 __func__, sinkDevice->toString().c_str());
5375 return INVALID_OPERATION;
5376 }
François Gaffie7e39df22022-04-26 12:48:49 +02005377 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005378 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005379 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005380 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005381 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005382 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005383 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5384 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005385 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5386 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005387 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005388 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005389 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005390 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005391 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005392 return INVALID_OPERATION;
5393 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005394 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005395 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005396 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005397 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005398 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005399 srcMixPortConfig.ext.mix.usecase.stream =
5400 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005401 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5402 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005403 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005404 }
Eric Laurent83b88082014-06-20 18:31:16 -07005405 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005406 }
5407 // TODO: check from routing capabilities in config file and other conflicting patches
5408
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005409installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005410 status_t status = installPatch(
5411 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005412 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005413 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005414 return INVALID_OPERATION;
5415 }
5416 } else {
5417 return BAD_VALUE;
5418 }
5419 } else {
5420 return BAD_VALUE;
5421 }
5422 return NO_ERROR;
5423}
5424
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005425status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005426{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005427 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005428 ssize_t index = mAudioPatches.indexOfKey(handle);
5429
5430 if (index < 0) {
5431 return BAD_VALUE;
5432 }
5433 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005434 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5435 __func__, mUidCached, patchDesc->getUid(), uid);
5436 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005437 return INVALID_OPERATION;
5438 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005439 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5440 for (size_t i = 0; i < mAudioSources.size(); i++) {
5441 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5442 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5443 portId = sourceDesc->portId();
5444 break;
5445 }
5446 }
5447 return portId != AUDIO_PORT_HANDLE_NONE ?
5448 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005449}
Eric Laurent6a94d692014-05-20 11:18:06 -07005450
François Gaffieafd4cea2019-11-18 15:50:22 +01005451status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005452 uint32_t delayMs,
5453 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005454{
5455 ALOGV("%s patch %d", __func__, handle);
5456 if (mAudioPatches.indexOfKey(handle) < 0) {
5457 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5458 return BAD_VALUE;
5459 }
5460 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005461 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005462 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005464 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005466 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005467 return BAD_VALUE;
5468 }
5469
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305470 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005471 getNewOutputDevices(outputDesc, true /*fromCache*/),
5472 true,
5473 0,
5474 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005475 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5476 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005477 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005478 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005479 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005480 return BAD_VALUE;
5481 }
5482 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005483 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005484 true,
5485 NULL);
5486 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005487 status_t status =
5488 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5489 ALOGV("%s patch panel returned %d patchHandle %d",
5490 __func__, status, patchDesc->getAfHandle());
5491 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005492 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005493 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005494 // SW or HW Bridge
5495 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5496 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005497 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005498 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5499 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5500 outputDesc = sourceDesc->swOutput().promote();
5501 }
5502 if (outputDesc == nullptr) {
5503 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5504 // releaseOutput has already called closeOutput in case of direct output
5505 return NO_ERROR;
5506 }
François Gaffie7e39df22022-04-26 12:48:49 +02005507 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005508 // While using a HwBridge, force reconsidering device only if not reusing an existing
5509 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005510 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005511 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5512 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5513 // Reconsider device only for cases:
5514 // 1 / Active Output
5515 // 2 / Inactive Output previously hosting HwBridge
5516 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5517 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5518 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305519 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005520 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5521 outputDesc->devices(),
5522 force,
5523 0,
5524 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005525 } else {
5526 return BAD_VALUE;
5527 }
5528 } else {
5529 return BAD_VALUE;
5530 }
5531 return NO_ERROR;
5532}
5533
5534status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5535 struct audio_patch *patches,
5536 unsigned int *generation)
5537{
François Gaffie53615e22015-03-19 09:24:12 +01005538 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005539 return BAD_VALUE;
5540 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005541 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005542 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005543}
5544
Eric Laurente1715a42014-05-20 11:30:42 -07005545status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005546{
Eric Laurente1715a42014-05-20 11:30:42 -07005547 ALOGV("setAudioPortConfig()");
5548
5549 if (config == NULL) {
5550 return BAD_VALUE;
5551 }
5552 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5553 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005554 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5555 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005556 }
5557
Eric Laurenta121f902014-06-03 13:32:54 -07005558 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005559 if (config->type == AUDIO_PORT_TYPE_MIX) {
5560 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005561 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005562 if (outputDesc == NULL) {
5563 return BAD_VALUE;
5564 }
Eric Laurent84c70242014-06-23 08:46:27 -07005565 ALOG_ASSERT(!outputDesc->isDuplicated(),
5566 "setAudioPortConfig() called on duplicated output %d",
5567 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005568 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005569 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005570 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005571 if (inputDesc == NULL) {
5572 return BAD_VALUE;
5573 }
Eric Laurenta121f902014-06-03 13:32:54 -07005574 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005575 } else {
5576 return BAD_VALUE;
5577 }
5578 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5579 sp<DeviceDescriptor> deviceDesc;
5580 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5581 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5582 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5583 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5584 } else {
5585 return BAD_VALUE;
5586 }
5587 if (deviceDesc == NULL) {
5588 return BAD_VALUE;
5589 }
Eric Laurenta121f902014-06-03 13:32:54 -07005590 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005591 } else {
5592 return BAD_VALUE;
5593 }
5594
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005595 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005596 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5597 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005598 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005599 audioPortConfig->toAudioPortConfig(&newConfig, config);
5600 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005601 }
Eric Laurenta121f902014-06-03 13:32:54 -07005602 if (status != NO_ERROR) {
5603 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005604 }
Eric Laurente1715a42014-05-20 11:30:42 -07005605
5606 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005607}
5608
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005609void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5610{
Eric Laurentd60560a2015-04-10 11:31:20 -07005611 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005612 clearAudioPatches(uid);
5613 clearSessionRoutes(uid);
5614}
5615
Eric Laurent6a94d692014-05-20 11:18:06 -07005616void AudioPolicyManager::clearAudioPatches(uid_t uid)
5617{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005618 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005619 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005620 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005621 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005622 }
5623 }
5624}
5625
François Gaffiec005e562018-11-06 15:04:49 +01005626void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005627{
François Gaffiec005e562018-11-06 15:04:49 +01005628 // Take the first attributes following the product strategy as it is used to retrieve the routed
5629 // device. All attributes wihin a strategy follows the same "routing strategy"
5630 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5631 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005632 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005633 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005634 for (size_t j = 0; j < mOutputs.size(); j++) {
5635 if (mOutputs.keyAt(j) == ouptutToSkip) {
5636 continue;
5637 }
5638 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005639 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005640 continue;
5641 }
5642 // If the default device for this strategy is on another output mix,
5643 // invalidate all tracks in this strategy to force re connection.
5644 // Otherwise select new device on the output mix.
5645 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005646 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005647 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005648 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005649 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005650 // If the device is using preferred mixer attributes, the output need to reopen
5651 // with default configuration when the new selected devices are different from
5652 // current routing devices.
5653 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5654 continue;
5655 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305656 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005657 }
5658 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005659 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005660}
5661
5662void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5663{
5664 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005665 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005666 for (size_t i = 0; i < mOutputs.size(); i++) {
5667 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005668 for (const auto& client : outputDesc->getClientIterable()) {
5669 if (client->hasPreferredDevice() && client->uid() == uid) {
5670 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005671 auto clientStrategy = client->strategy();
5672 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5673 end(affectedStrategies)) {
5674 continue;
5675 }
5676 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005677 }
5678 }
5679 }
5680 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005681 for (const auto& strategy : affectedStrategies) {
5682 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005683 }
5684
5685 // remove input routes associated with this uid
5686 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005687 for (size_t i = 0; i < mInputs.size(); i++) {
5688 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005689 for (const auto& client : inputDesc->getClientIterable()) {
5690 if (client->hasPreferredDevice() && client->uid() == uid) {
5691 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5692 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005693 }
5694 }
5695 }
5696 // reroute inputs if necessary
5697 SortedVector<audio_io_handle_t> inputsToClose;
5698 for (size_t i = 0; i < mInputs.size(); i++) {
5699 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005700 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005701 inputsToClose.add(inputDesc->mIoHandle);
5702 }
5703 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005704 for (const auto& input : inputsToClose) {
5705 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005706 }
5707}
5708
Eric Laurentd60560a2015-04-10 11:31:20 -07005709void AudioPolicyManager::clearAudioSources(uid_t uid)
5710{
5711 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005712 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5713 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005714 stopAudioSource(mAudioSources.keyAt(i));
5715 }
5716 }
5717}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005718
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005719status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5720 audio_io_handle_t *ioHandle,
5721 audio_devices_t *device)
5722{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005723 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5724 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005725 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005726 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5727 if (deviceDesc == nullptr) {
5728 return INVALID_OPERATION;
5729 }
5730 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005731
François Gaffiedf372692015-03-19 10:43:27 +01005732 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005733}
5734
Eric Laurentd60560a2015-04-10 11:31:20 -07005735status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005736 const audio_attributes_t *attributes,
5737 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005738 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005739{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005740 ALOGV("%s", __FUNCTION__);
5741 *portId = AUDIO_PORT_HANDLE_NONE;
5742
5743 if (source == NULL || attributes == NULL || portId == NULL) {
5744 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5745 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005746 return BAD_VALUE;
5747 }
5748
Eric Laurentd60560a2015-04-10 11:31:20 -07005749 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5750 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005751 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5752 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005753 return INVALID_OPERATION;
5754 }
5755
François Gaffie11d30102018-11-02 16:09:09 +01005756 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005757 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005758 String8(source->ext.device.address),
5759 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005760 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005761 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005762 return BAD_VALUE;
5763 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005764
jiabin4ef93452019-09-10 14:29:54 -07005765 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005766
François Gaffieaaac0fd2018-11-22 17:56:39 +01005767 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005768 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005769 mEngine->getStreamTypeForAttributes(*attributes),
5770 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005771 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005772
5773 status_t status = connectAudioSource(sourceDesc);
5774 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005775 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005776 }
5777 return status;
5778}
5779
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005780status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005781{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005782 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005783
5784 // make sure we only have one patch per source.
5785 disconnectAudioSource(sourceDesc);
5786
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005787 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005788 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5789 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5790 sourceDesc->srcDevice()->type(),
5791 String8(sourceDesc->srcDevice()->address().c_str()),
5792 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005793 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005794 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005795 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005796 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005797 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5798 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5799 return INVALID_OPERATION;
5800 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005801 PatchBuilder patchBuilder;
5802 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5803 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005804
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005805 return connectAudioSourceToSink(
5806 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005807}
5808
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005809status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005810{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005811 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5812 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005813 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005814 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005815 return BAD_VALUE;
5816 }
5817 status_t status = disconnectAudioSource(sourceDesc);
5818
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005819 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005820 return status;
5821}
5822
Andy Hung2ddee192015-12-18 17:34:44 -08005823status_t AudioPolicyManager::setMasterMono(bool mono)
5824{
5825 if (mMasterMono == mono) {
5826 return NO_ERROR;
5827 }
5828 mMasterMono = mono;
5829 // if enabling mono we close all offloaded devices, which will invalidate the
5830 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5831 // for recreating the new AudioTrack as non-offloaded PCM.
5832 //
5833 // If disabling mono, we leave all tracks as is: we don't know which clients
5834 // and tracks are able to be recreated as offloaded. The next "song" should
5835 // play back offloaded.
5836 if (mMasterMono) {
5837 Vector<audio_io_handle_t> offloaded;
5838 for (size_t i = 0; i < mOutputs.size(); ++i) {
5839 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5840 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5841 offloaded.push(desc->mIoHandle);
5842 }
5843 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005844 for (const auto& handle : offloaded) {
5845 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005846 }
5847 }
5848 // update master mono for all remaining outputs
5849 for (size_t i = 0; i < mOutputs.size(); ++i) {
5850 updateMono(mOutputs.keyAt(i));
5851 }
5852 return NO_ERROR;
5853}
5854
5855status_t AudioPolicyManager::getMasterMono(bool *mono)
5856{
5857 *mono = mMasterMono;
5858 return NO_ERROR;
5859}
5860
Eric Laurentac9cef52017-06-09 15:46:26 -07005861float AudioPolicyManager::getStreamVolumeDB(
5862 audio_stream_type_t stream, int index, audio_devices_t device)
5863{
jiabin9a3361e2019-10-01 09:38:30 -07005864 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005865}
5866
jiabin81772902018-04-02 17:52:27 -07005867status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5868 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005869 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005870{
Kriti Dang6537def2021-03-02 13:46:59 +01005871 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5872 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005873 return BAD_VALUE;
5874 }
Kriti Dang6537def2021-03-02 13:46:59 +01005875 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5876 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005877
5878 size_t formatsWritten = 0;
5879 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005880
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005881 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005882 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5883 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005884 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005885 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005886 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005887 bool formatEnabled = true;
5888 switch (forceUse) {
5889 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005890 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005891 break;
5892 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5893 formatEnabled = false;
5894 break;
5895 default: // AUTO or ALWAYS => true
5896 break;
jiabin81772902018-04-02 17:52:27 -07005897 }
5898 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5899 }
jiabin81772902018-04-02 17:52:27 -07005900 }
5901 return NO_ERROR;
5902}
5903
Kriti Dang6537def2021-03-02 13:46:59 +01005904status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5905 audio_format_t *surroundFormats) {
5906 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5907 return BAD_VALUE;
5908 }
5909 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5910 __func__, *numSurroundFormats, surroundFormats);
5911
5912 size_t formatsWritten = 0;
5913 size_t formatsMax = *numSurroundFormats;
5914 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5915
5916 // Return formats from all device profiles that have already been resolved by
5917 // checkOutputsForDevice().
5918 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5919 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5920 audio_devices_t deviceType = device->type();
5921 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5922 // returns formats reported by HDMI devices.
5923 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5924 continue;
5925 }
5926 // Formats reported by sink devices
5927 std::unordered_set<audio_format_t> formatset;
5928 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5929 formatset.insert(it->second.begin(), it->second.end());
5930 }
5931
5932 // Formats hard-coded in the in policy configuration file (if any).
5933 FormatVector encodedFormats = device->encodedFormats();
5934 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5935 // Filter the formats which are supported by the vendor hardware.
5936 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005937 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005938 formats.insert(*it);
5939 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005940 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005941 if (pair.second.count(*it) != 0) {
5942 formats.insert(pair.first);
5943 break;
5944 }
5945 }
5946 }
5947 }
5948 }
5949 *numSurroundFormats = formats.size();
5950 for (const auto& format: formats) {
5951 if (formatsWritten < formatsMax) {
5952 surroundFormats[formatsWritten++] = format;
5953 }
5954 }
5955 return NO_ERROR;
5956}
5957
jiabin81772902018-04-02 17:52:27 -07005958status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5959{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005960 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005961 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5962 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005963 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005964 return BAD_VALUE;
5965 }
5966
Mikhail Naganov100f0122018-11-29 11:22:16 -08005967 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5968 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005969 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005970 return INVALID_OPERATION;
5971 }
5972
Mikhail Naganov100f0122018-11-29 11:22:16 -08005973 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005974 return NO_ERROR;
5975 }
5976
Mikhail Naganov100f0122018-11-29 11:22:16 -08005977 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005978 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005979 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005980 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005981 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005982 }
5983 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005984 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005985 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005986 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005987 }
5988 }
5989
5990 sp<SwAudioOutputDescriptor> outputDesc;
5991 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005992 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5993 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005994 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5995 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005996 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005997 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005998 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5999 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6000 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006001 name.c_str(),
6002 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006003 if (status != NO_ERROR) {
6004 continue;
6005 }
6006 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6007 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6008 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006009 name.c_str(),
6010 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006011 profileUpdated |= (status == NO_ERROR);
6012 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006013 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006014 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006015 AUDIO_DEVICE_IN_HDMI);
6016 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6017 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006018 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006019 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006020 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6021 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6022 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006023 name.c_str(),
6024 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006025 if (status != NO_ERROR) {
6026 continue;
6027 }
6028 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6029 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6030 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006031 name.c_str(),
6032 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006033 profileUpdated |= (status == NO_ERROR);
6034 }
6035
jiabin81772902018-04-02 17:52:27 -07006036 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006037 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006038 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006039 }
6040
6041 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6042}
6043
Eric Laurent5ada82e2019-08-29 17:53:54 -07006044void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006045{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006046 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006047 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006048 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006049 }
6050}
6051
jiabin6012f912018-11-02 17:06:30 -07006052bool AudioPolicyManager::isHapticPlaybackSupported()
6053{
6054 for (const auto& hwModule : mHwModules) {
6055 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6056 for (const auto &outProfile : outputProfiles) {
6057 struct audio_port audioPort;
6058 outProfile->toAudioPort(&audioPort);
6059 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6060 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6061 return true;
6062 }
6063 }
6064 }
6065 }
6066 return false;
6067}
6068
Carter Hsu325a8eb2022-01-19 19:56:51 +08006069bool AudioPolicyManager::isUltrasoundSupported()
6070{
6071 bool hasUltrasoundOutput = false;
6072 bool hasUltrasoundInput = false;
6073 for (const auto& hwModule : mHwModules) {
6074 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6075 if (!hasUltrasoundOutput) {
6076 for (const auto &outProfile : outputProfiles) {
6077 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6078 hasUltrasoundOutput = true;
6079 break;
6080 }
6081 }
6082 }
6083
6084 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6085 if (!hasUltrasoundInput) {
6086 for (const auto &inputProfile : inputProfiles) {
6087 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6088 hasUltrasoundInput = true;
6089 break;
6090 }
6091 }
6092 }
6093
6094 if (hasUltrasoundOutput && hasUltrasoundInput)
6095 return true;
6096 }
6097 return false;
6098}
6099
Atneya Nair698f5ef2022-12-15 16:15:09 -08006100bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6101{
6102 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6103 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6104 for (const auto& hwModule : mHwModules) {
6105 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6106 for (const auto &inputProfile : inputProfiles) {
6107 if ((inputProfile->getFlags() & mask) == mask) {
6108 return true;
6109 }
6110 }
6111 }
6112 return false;
6113}
6114
Eric Laurent8340e672019-11-06 11:01:08 -08006115bool AudioPolicyManager::isCallScreenModeSupported()
6116{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006117 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006118}
6119
6120
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006121status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006122{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006123 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006124 if (!sourceDesc->isConnected()) {
6125 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6126 return NO_ERROR;
6127 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006128 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6129 if (swOutput != 0) {
6130 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006131 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006132 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006133 }
jiabinbce0c1d2020-10-05 11:20:18 -07006134 if (releaseOutput(sourceDesc->portId())) {
6135 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6136 // no need to release audio patch here but just return NO_ERROR.
6137 return NO_ERROR;
6138 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006139 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006140 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006141 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006142 // close Hwoutput and remove from mHwOutputs
6143 } else {
6144 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6145 }
6146 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006147 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006148 sourceDesc->disconnect();
6149 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006150}
6151
François Gaffiec005e562018-11-06 15:04:49 +01006152sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6153 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006154{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006155 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006156 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006157 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006158 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006159 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6160 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006161 source = sourceDesc;
6162 break;
6163 }
6164 }
6165 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006166}
6167
Eric Laurentb4f42a92022-01-17 17:37:31 +01006168bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006169 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006170 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006171{
6172 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6173 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006174 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006175 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006176 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6177 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6178 return false;
6179 }
6180 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6181 return false;
6182 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006183 }
6184
Eric Laurentd332bc82023-08-04 11:45:23 +02006185 // The caller can have the audio config criteria ignored by either passing a null ptr or
6186 // the AUDIO_CONFIG_INITIALIZER value.
6187 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006188 // some positional channel masks and PCM format and for stereo if low latency performance
6189 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006190
6191 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006192 static const bool stereo_spatialization_enabled =
6193 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006194 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006195 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006196 ? audio_channel_mask_contains_stereo(config->channel_mask)
6197 : audio_is_channel_mask_spatialized(config->channel_mask);
6198 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006199 return false;
6200 }
6201 if (!audio_is_linear_pcm(config->format)) {
6202 return false;
6203 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006204 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6205 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6206 return false;
6207 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006208 }
6209
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006210 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006211 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006212 if (profile == nullptr) {
6213 return false;
6214 }
6215
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006216 return true;
6217}
6218
Shunkai Yao4c3af932024-04-26 04:12:21 +00006219// The Spatializer output is compatible with Haptic use cases if:
6220// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6221// with client if client haptic channel bits were set, or
6222// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6223// including the haptic bits or creating the HapticGenerator effect for same session.
6224bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6225 const audio_config_t* config, audio_session_t sessionId) const {
6226 const auto clientHapticChannel =
6227 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6228 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6229 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6230
6231 if (threadOutputHapticChannel) {
6232 // check format and sampleRate match if client haptic channel mask exist
6233 if (clientHapticChannel) {
6234 return mSpatializerOutput->getFormat() == config->format &&
6235 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6236 }
6237 return true;
6238 } else {
6239 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6240 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6241 // HapticGenerator effect for this session) are not supported.
6242 return clientHapticChannel == 0 &&
6243 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6244 }
6245}
6246
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006247void AudioPolicyManager::checkVirtualizerClientRoutes() {
6248 std::set<audio_stream_type_t> streamsToInvalidate;
6249 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006250 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6251 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006252 audio_attributes_t attr = client->attributes();
6253 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6254 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6255 audio_config_base_t clientConfig = client->config();
6256 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006257 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006258 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006259 streamsToInvalidate.insert(client->stream());
6260 }
6261 }
6262 }
6263
jiabinc44b3462022-12-08 12:52:31 -08006264 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006265}
6266
Eric Laurente191d1b2022-04-15 11:59:25 +02006267
6268bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6269 const sp<SwAudioOutputDescriptor>& outputDesc) {
6270 if (outputDesc->isDuplicated()) {
6271 return false;
6272 }
6273 DeviceVector devices = outputDesc->supportedDevices();
6274 for (size_t i = 0; i < mOutputs.size(); i++) {
6275 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6276 if (desc == outputDesc || desc->isDuplicated()) {
6277 continue;
6278 }
6279 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6280 if (!sharedDevices.isEmpty()
6281 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6282 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6283 return false;
6284 }
6285 }
6286 return true;
6287}
6288
6289
Eric Laurentfa0f6742021-08-17 18:39:44 +02006290status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006291 const audio_attributes_t *attr,
6292 audio_io_handle_t *output) {
6293 *output = AUDIO_IO_HANDLE_NONE;
6294
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006295 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6296 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6297 audio_config_t *configPtr = nullptr;
6298 audio_config_t config;
6299 if (mixerConfig != nullptr) {
6300 config = audio_config_initializer(mixerConfig);
6301 configPtr = &config;
6302 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006303 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006304 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006305 return BAD_VALUE;
6306 }
6307
6308 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006309 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006310 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006311 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006312 return BAD_VALUE;
6313 }
6314
Eric Laurente191d1b2022-04-15 11:59:25 +02006315 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006316 for (size_t i = 0; i < mOutputs.size(); i++) {
6317 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006318 if (!desc->isDuplicated()
6319 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6320 spatializerOutputs.push_back(desc);
6321 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006322 }
6323 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006324 mSpatializerOutput.clear();
6325 bool outputsChanged = false;
6326 for (const auto& desc : spatializerOutputs) {
6327 if (desc->mProfile == profile
6328 && (configPtr == nullptr
6329 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6330 mSpatializerOutput = desc;
6331 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6332 } else {
6333 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6334 " and devices %s", __func__, desc->mIoHandle,
6335 configPtr != nullptr ? configPtr->channel_mask : 0,
6336 devices.toString().c_str());
6337 closeOutput(desc->mIoHandle);
6338 outputsChanged = true;
6339 }
Eric Laurent39095982021-08-24 18:29:27 +02006340 }
6341
Eric Laurente191d1b2022-04-15 11:59:25 +02006342 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006343 sp<SwAudioOutputDescriptor> desc =
6344 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006345 if (desc != nullptr) {
6346 mSpatializerOutput = desc;
6347 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006348 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006349 }
6350
6351 checkVirtualizerClientRoutes();
6352
Eric Laurente191d1b2022-04-15 11:59:25 +02006353 if (outputsChanged) {
6354 mPreviousOutputs = mOutputs;
6355 mpClientInterface->onAudioPortListUpdate();
6356 }
6357
6358 if (mSpatializerOutput == nullptr) {
6359 ALOGV("%s could not open spatializer output with requested config", __func__);
6360 return BAD_VALUE;
6361 }
Eric Laurent39095982021-08-24 18:29:27 +02006362 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006363 ALOGV("%s returning new spatializer output %d", __func__, *output);
6364 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006365}
6366
Eric Laurentfa0f6742021-08-17 18:39:44 +02006367status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6368 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006369 return INVALID_OPERATION;
6370 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006371 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006372 return BAD_VALUE;
6373 }
Eric Laurent39095982021-08-24 18:29:27 +02006374
Eric Laurente191d1b2022-04-15 11:59:25 +02006375 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6376 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6377 closeOutput(mSpatializerOutput->mIoHandle);
6378 //from now on mSpatializerOutput is null
6379 checkVirtualizerClientRoutes();
6380 }
Eric Laurent39095982021-08-24 18:29:27 +02006381
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006382 return NO_ERROR;
6383}
6384
Eric Laurente552edb2014-03-10 17:42:56 -07006385// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006386// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006387// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006388uint32_t AudioPolicyManager::nextAudioPortGeneration()
6389{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006390 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006391}
6392
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006393AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006394 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006395 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006396 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006397 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006398 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006399 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006400 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006401 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006402 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006403 mAudioPortGeneration(1),
6404 mBeaconMuteRefCount(0),
6405 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006406 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006407 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006408 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006409 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006410{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006411}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006412
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006413status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006414 if (mEngine == nullptr) {
6415 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006416 }
6417 mEngine->setObserver(this);
6418 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006419 if (status != NO_ERROR) {
6420 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6421 return status;
6422 }
François Gaffie2110e042015-03-24 08:41:51 +01006423
jiabin29230182023-04-04 21:02:36 +00006424 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6425 // at the end of this function.
6426 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006427 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6428 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6429
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006430 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006431 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006432 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006433
Eric Laurent3a4311c2014-03-17 12:00:47 -07006434 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006435 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6436 defaultOutputDevice == nullptr ||
6437 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6438 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6439 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006440 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006441 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006442 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006443
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006444 // Silence ALOGV statements
6445 property_set("log.tag." LOG_TAG, "D");
6446
Eric Laurente552edb2014-03-10 17:42:56 -07006447 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006448 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006449}
6450
Eric Laurente0720872014-03-11 09:30:41 -07006451AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006452{
Eric Laurente552edb2014-03-10 17:42:56 -07006453 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006454 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006455 }
6456 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006457 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006458 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006459 mAvailableOutputDevices.clear();
6460 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006461 mOutputs.clear();
6462 mInputs.clear();
6463 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006464 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006465 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006466}
6467
Eric Laurente0720872014-03-11 09:30:41 -07006468status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006469{
Eric Laurent87ffa392015-05-22 10:32:38 -07006470 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006471}
6472
Eric Laurente552edb2014-03-10 17:42:56 -07006473// ---
6474
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006475void AudioPolicyManager::onNewAudioModulesAvailable()
6476{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006477 DeviceVector newDevices;
6478 onNewAudioModulesAvailableInt(&newDevices);
6479 if (!newDevices.empty()) {
6480 nextAudioPortGeneration();
6481 mpClientInterface->onAudioPortListUpdate();
6482 }
6483}
6484
6485void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6486{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006487 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006488 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6489 continue;
6490 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006491 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006492 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6493 handle != AUDIO_MODULE_HANDLE_NONE) {
6494 hwModule->setHandle(handle);
6495 } else {
6496 ALOGW("could not load HW module %s", hwModule->getName());
6497 continue;
6498 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006499 }
6500 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006501 // open all output streams needed to access attached devices.
6502 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006503 // This also validates mAvailableOutputDevices list
6504 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6505 if (!outProfile->canOpenNewIo()) {
6506 ALOGE("Invalid Output profile max open count %u for profile %s",
6507 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6508 continue;
6509 }
6510 if (!outProfile->hasSupportedDevices()) {
6511 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6512 continue;
6513 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006514 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6515 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006516 mTtsOutputAvailable = true;
6517 }
6518
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006519 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006520 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006521 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006522 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6523 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006524 } else {
6525 // choose first device present in profile's SupportedDevices also part of
6526 // mAvailableOutputDevices.
6527 if (availProfileDevices.isEmpty()) {
6528 continue;
6529 }
6530 supportedDevice = availProfileDevices.itemAt(0);
6531 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006532 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006533 continue;
6534 }
6535 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6536 mpClientInterface);
6537 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006538 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6539 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006540 AUDIO_STREAM_DEFAULT,
6541 AUDIO_OUTPUT_FLAG_NONE, &output);
6542 if (status != NO_ERROR) {
6543 ALOGW("Cannot open output stream for devices %s on hw module %s",
6544 supportedDevice->toString().c_str(), hwModule->getName());
6545 continue;
6546 }
6547 for (const auto &device : availProfileDevices) {
6548 // give a valid ID to an attached device once confirmed it is reachable
6549 if (!device->isAttached()) {
6550 device->attach(hwModule);
6551 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006552 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006553 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006554 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6555 }
6556 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006557 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006558 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6559 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006560 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006561 }
Eric Laurent39095982021-08-24 18:29:27 +02006562 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006563 outputDesc->close();
6564 } else {
6565 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306566 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006567 DeviceVector(supportedDevice),
6568 true,
6569 0,
6570 NULL);
6571 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006572 }
6573 // open input streams needed to access attached devices to validate
6574 // mAvailableInputDevices list
6575 for (const auto& inProfile : hwModule->getInputProfiles()) {
6576 if (!inProfile->canOpenNewIo()) {
6577 ALOGE("Invalid Input profile max open count %u for profile %s",
6578 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6579 continue;
6580 }
6581 if (!inProfile->hasSupportedDevices()) {
6582 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6583 continue;
6584 }
6585 // chose first device present in profile's SupportedDevices also part of
6586 // available input devices
6587 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006588 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006589 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006590 ALOGV("%s: Input device list is empty! for profile %s",
6591 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006592 continue;
6593 }
6594 sp<AudioInputDescriptor> inputDesc =
6595 new AudioInputDescriptor(inProfile, mpClientInterface);
6596
6597 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6598 status_t status = inputDesc->open(nullptr,
6599 availProfileDevices.itemAt(0),
6600 AUDIO_SOURCE_MIC,
6601 AUDIO_INPUT_FLAG_NONE,
6602 &input);
6603 if (status != NO_ERROR) {
6604 ALOGW("Cannot open input stream for device %s on hw module %s",
6605 availProfileDevices.toString().c_str(),
6606 hwModule->getName());
6607 continue;
6608 }
6609 for (const auto &device : availProfileDevices) {
6610 // give a valid ID to an attached device once confirmed it is reachable
6611 if (!device->isAttached()) {
6612 device->attach(hwModule);
6613 device->importAudioPortAndPickAudioProfile(inProfile, true);
6614 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006615 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006616 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6617 }
6618 }
6619 inputDesc->close();
6620 }
6621 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006622
6623 // Check if spatializer outputs can be closed until used.
6624 // mOutputs vector never contains duplicated outputs at this point.
6625 std::vector<audio_io_handle_t> outputsClosed;
6626 for (size_t i = 0; i < mOutputs.size(); i++) {
6627 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6628 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6629 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6630 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006631 nextAudioPortGeneration();
6632 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6633 if (index >= 0) {
6634 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6635 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6636 patchDesc->getAfHandle(), 0);
6637 mAudioPatches.removeItemsAt(index);
6638 mpClientInterface->onAudioPatchListUpdate();
6639 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006640 desc->close();
6641 }
6642 }
6643 for (auto output : outputsClosed) {
6644 removeOutput(output);
6645 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006646}
6647
Eric Laurent98e38192018-02-15 18:31:53 -08006648void AudioPolicyManager::addOutput(audio_io_handle_t output,
6649 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006650{
Eric Laurent1c333e22014-05-20 10:48:17 -07006651 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006652 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006653 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006654 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006655 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006656}
6657
François Gaffie53615e22015-03-19 09:24:12 +01006658void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6659{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006660 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6661 ALOGV("%s: removing primary output", __func__);
6662 mPrimaryOutput = nullptr;
6663 }
François Gaffie53615e22015-03-19 09:24:12 +01006664 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006665 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006666}
6667
Eric Laurent98e38192018-02-15 18:31:53 -08006668void AudioPolicyManager::addInput(audio_io_handle_t input,
6669 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006670{
Eric Laurent1c333e22014-05-20 10:48:17 -07006671 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006672 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006673}
Eric Laurente552edb2014-03-10 17:42:56 -07006674
François Gaffie11d30102018-11-02 16:09:09 +01006675status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006676 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006677 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006678{
François Gaffie11d30102018-11-02 16:09:09 +01006679 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006680 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006681 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006682
François Gaffie11d30102018-11-02 16:09:09 +01006683 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006684 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006685 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006686 }
Eric Laurente552edb2014-03-10 17:42:56 -07006687
Eric Laurent3b73df72014-03-11 09:06:29 -07006688 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006689 // first call getAudioPort to get the supported attributes from the HAL
6690 struct audio_port_v7 port = {};
6691 device->toAudioPort(&port);
6692 status_t status = mpClientInterface->getAudioPort(&port);
6693 if (status == NO_ERROR) {
6694 device->importAudioPort(port);
6695 }
6696
6697 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006698 for (size_t i = 0; i < mOutputs.size(); i++) {
6699 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006700 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006701 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006702 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6703 mOutputs.keyAt(i), device->toString().c_str());
6704 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006705 }
6706 }
6707 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006708 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006709 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006710 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6711 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006712 if (profile->supportsDevice(device)) {
6713 profiles.add(profile);
6714 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6715 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006716 }
6717 }
6718 }
6719
Eric Laurent7b279bb2015-12-14 10:18:23 -08006720 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006721
Eric Laurente552edb2014-03-10 17:42:56 -07006722 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006723 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006724 return BAD_VALUE;
6725 }
6726
6727 // open outputs for matching profiles if needed. Direct outputs are also opened to
6728 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6729 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006730 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006731
6732 // nothing to do if one output is already opened for this profile
6733 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006734 for (j = 0; j < outputs.size(); j++) {
6735 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006736 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006737 // matching profile: save the sample rates, format and channel masks supported
6738 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006739 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006740 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006741 }
Eric Laurente552edb2014-03-10 17:42:56 -07006742 break;
6743 }
6744 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006745 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006746 continue;
6747 }
6748
Eric Laurent3974e3b2017-12-07 17:58:43 -08006749 if (!profile->canOpenNewIo()) {
6750 ALOGW("Max Output number %u already opened for this profile %s",
6751 profile->maxOpenCount, profile->getTagName().c_str());
6752 continue;
6753 }
6754
Eric Laurent83efe1c2017-07-09 16:51:08 -07006755 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006756 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006757 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6758 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006759 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006760 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006761 profiles.removeAt(profile_index);
6762 profile_index--;
6763 } else {
6764 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006765 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006766 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006767 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6768 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006769 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006770 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006771
François Gaffie11d30102018-11-02 16:09:09 +01006772 if (device_distinguishes_on_address(deviceType)) {
6773 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6774 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306775 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6776 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006777 }
Eric Laurente552edb2014-03-10 17:42:56 -07006778 ALOGV("checkOutputsForDevice(): adding output %d", output);
6779 }
6780 }
6781
6782 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006783 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006784 return BAD_VALUE;
6785 }
Eric Laurentd4692962014-05-05 18:13:44 -07006786 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006787 // check if one opened output is not needed any more after disconnecting one device
6788 for (size_t i = 0; i < mOutputs.size(); i++) {
6789 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006790 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006791 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006792 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006793 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006794 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006795 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006796 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6797 mOutputs.keyAt(i));
6798 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006799 }
Eric Laurente552edb2014-03-10 17:42:56 -07006800 }
6801 }
Eric Laurentd4692962014-05-05 18:13:44 -07006802 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006803 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006804 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6805 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006806 if (!profile->supportsDevice(device)) {
6807 continue;
6808 }
6809 ALOGV("checkOutputsForDevice(): "
6810 "clearing direct output profile %zu on module %s",
6811 j, hwModule->getName());
6812 profile->clearAudioProfiles();
6813 if (!profile->hasDynamicAudioProfile()) {
6814 continue;
6815 }
6816 // When a device is disconnected, if there is an IOProfile that contains dynamic
6817 // profiles and supports the disconnected device, call getAudioPort to repopulate
6818 // the capabilities of the devices that is supported by the IOProfile.
6819 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6820 if (supportedDevice == device ||
6821 !mAvailableOutputDevices.contains(supportedDevice)) {
6822 continue;
6823 }
6824 struct audio_port_v7 port;
6825 supportedDevice->toAudioPort(&port);
6826 status_t status = mpClientInterface->getAudioPort(&port);
6827 if (status == NO_ERROR) {
6828 supportedDevice->importAudioPort(port);
6829 }
Eric Laurente552edb2014-03-10 17:42:56 -07006830 }
6831 }
6832 }
6833 }
6834 return NO_ERROR;
6835}
6836
François Gaffie11d30102018-11-02 16:09:09 +01006837status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006838 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006839{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006840 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006841
François Gaffie11d30102018-11-02 16:09:09 +01006842 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006843 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006844 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006845 }
6846
Eric Laurentd4692962014-05-05 18:13:44 -07006847 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006848 // first call getAudioPort to get the supported attributes from the HAL
6849 struct audio_port_v7 port = {};
6850 device->toAudioPort(&port);
6851 status_t status = mpClientInterface->getAudioPort(&port);
6852 if (status == NO_ERROR) {
6853 device->importAudioPort(port);
6854 }
6855
Eric Laurent0dd51852019-04-19 18:18:58 -07006856 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006857 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006858 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006859 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006860 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006861 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006862 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006863
François Gaffie11d30102018-11-02 16:09:09 +01006864 if (profile->supportsDevice(device)) {
6865 profiles.add(profile);
6866 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6867 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006868 }
6869 }
6870 }
6871
Eric Laurent0dd51852019-04-19 18:18:58 -07006872 if (profiles.isEmpty()) {
6873 ALOGW("%s: No input profile available for device %s",
6874 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006875 return BAD_VALUE;
6876 }
6877
6878 // open inputs for matching profiles if needed. Direct inputs are also opened to
6879 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6880 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6881
Eric Laurent1c333e22014-05-20 10:48:17 -07006882 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006883
Eric Laurentd4692962014-05-05 18:13:44 -07006884 // nothing to do if one input is already opened for this profile
6885 size_t input_index;
6886 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6887 desc = mInputs.valueAt(input_index);
6888 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006889 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006890 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006891 }
Eric Laurentd4692962014-05-05 18:13:44 -07006892 break;
6893 }
6894 }
6895 if (input_index != mInputs.size()) {
6896 continue;
6897 }
6898
Eric Laurent3974e3b2017-12-07 17:58:43 -08006899 if (!profile->canOpenNewIo()) {
6900 ALOGW("Max Input number %u already opened for this profile %s",
6901 profile->maxOpenCount, profile->getTagName().c_str());
6902 continue;
6903 }
6904
Eric Laurentfe231122017-11-17 17:48:06 -08006905 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006906 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006907 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006908
Eric Laurentcf2c0212014-07-25 16:20:43 -07006909 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006910 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006911 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006912 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006913 mpClientInterface->setParameters(input, String8(param));
6914 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006915 }
jiabin12537fc2023-10-12 17:56:08 +00006916 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006917 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006918 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006919 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006920 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006921 }
6922
Eric Laurent0dd51852019-04-19 18:18:58 -07006923 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006924 addInput(input, desc);
6925 }
6926 } // endif input != 0
6927
Eric Laurentcf2c0212014-07-25 16:20:43 -07006928 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006929 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006930 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006931 profiles.removeAt(profile_index);
6932 profile_index--;
6933 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006934 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006935 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006936 }
Eric Laurentd4692962014-05-05 18:13:44 -07006937 ALOGV("checkInputsForDevice(): adding input %d", input);
6938 }
6939 } // end scan profiles
6940
6941 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006942 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006943 return BAD_VALUE;
6944 }
6945 } else {
6946 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006947 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006948 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006949 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006950 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006951 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006952 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006953 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006954 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6955 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006956 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006957 }
6958 }
6959 }
6960 } // end disconnect
6961
6962 return NO_ERROR;
6963}
6964
6965
Eric Laurente0720872014-03-11 09:30:41 -07006966void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006967{
6968 ALOGV("closeOutput(%d)", output);
6969
François Gaffie1c878552018-11-22 16:53:21 +01006970 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6971 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006972 ALOGW("closeOutput() unknown output %d", output);
6973 return;
6974 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006975 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006976 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006977
Eric Laurente552edb2014-03-10 17:42:56 -07006978 // look for duplicated outputs connected to the output being removed.
6979 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006980 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6981 if (dupOutput->isDuplicated() &&
6982 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6983 sp<SwAudioOutputDescriptor> remainingOutput =
6984 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006985 // As all active tracks on duplicated output will be deleted,
6986 // and as they were also referenced on the other output, the reference
6987 // count for their stream type must be adjusted accordingly on
6988 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006989 const bool wasActive = remainingOutput->isActive();
6990 // Note: no-op on the closing output where all clients has already been set inactive
6991 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006992 // stop() will be a no op if the output is still active but is needed in case all
6993 // active streams refcounts where cleared above
6994 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006995 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006996 }
Eric Laurente552edb2014-03-10 17:42:56 -07006997 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6998 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6999
7000 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007001 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007002 }
7003 }
7004
Eric Laurent05b90f82014-08-27 15:32:29 -07007005 nextAudioPortGeneration();
7006
François Gaffie1c878552018-11-22 16:53:21 +01007007 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007008 if (index >= 0) {
7009 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007010 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7011 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007012 mAudioPatches.removeItemsAt(index);
7013 mpClientInterface->onAudioPatchListUpdate();
7014 }
7015
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007016 if (closingOutputWasActive) {
7017 closingOutput->stop();
7018 }
François Gaffie1c878552018-11-22 16:53:21 +01007019 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007020 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007021 for (const auto device : closingOutput->devices()) {
7022 device->setPreferredConfig(nullptr);
7023 }
7024 }
Eric Laurente552edb2014-03-10 17:42:56 -07007025
François Gaffie53615e22015-03-19 09:24:12 +01007026 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007027 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007028 if (closingOutput == mSpatializerOutput) {
7029 mSpatializerOutput.clear();
7030 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007031
7032 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7033 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007034 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007035 bool directOutputOpen = false;
7036 for (size_t i = 0; i < mOutputs.size(); i++) {
7037 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7038 directOutputOpen = true;
7039 break;
7040 }
7041 }
7042 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007043 ALOGV("no direct outputs open, reset MSD patches");
7044 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7045 // how output devices for patching are resolved. Avoid by caching and reusing the
7046 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7047 // devices to patch to. This may be complicated by the fact that devices may become
7048 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007049 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007050 }
7051 }
jiabin220eea12024-05-17 17:55:20 +00007052
7053 if (closingOutput->mPreferredAttrInfo != nullptr) {
7054 closingOutput->mPreferredAttrInfo->resetActiveClient();
7055 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007056}
7057
7058void AudioPolicyManager::closeInput(audio_io_handle_t input)
7059{
7060 ALOGV("closeInput(%d)", input);
7061
7062 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7063 if (inputDesc == NULL) {
7064 ALOGW("closeInput() unknown input %d", input);
7065 return;
7066 }
7067
Eric Laurent6a94d692014-05-20 11:18:06 -07007068 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007069
François Gaffie11d30102018-11-02 16:09:09 +01007070 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007071 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007072 if (index >= 0) {
7073 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007074 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7075 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007076 mAudioPatches.removeItemsAt(index);
7077 mpClientInterface->onAudioPatchListUpdate();
7078 }
7079
François Gaffie6ebbce02023-07-19 13:27:53 +02007080 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007081 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007082 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007083
François Gaffie11d30102018-11-02 16:09:09 +01007084 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7085 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007086 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007087 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007088 }
Eric Laurente552edb2014-03-10 17:42:56 -07007089}
7090
François Gaffie11d30102018-11-02 16:09:09 +01007091SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7092 const DeviceVector &devices,
7093 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007094{
7095 SortedVector<audio_io_handle_t> outputs;
7096
François Gaffie11d30102018-11-02 16:09:09 +01007097 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007098 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007099 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007100 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007101 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007102 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007103 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007104 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007105 outputs.add(openOutputs.keyAt(i));
7106 }
7107 }
7108 return outputs;
7109}
7110
Mikhail Naganov37977152018-07-11 15:54:44 -07007111void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7112{
7113 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7114 // output is suspended before any tracks are moved to it
7115 checkA2dpSuspend();
7116 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007117 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007118 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007119 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007120 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007121 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7122 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7123 // configuration changes will ultimately be rerouted correctly. We can still avoid
7124 // unnecessary rerouting by caching and reusing the arguments to
7125 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7126 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007127 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007128 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007129 // an event that changed routing likely occurred, inform upper layers
7130 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007131}
7132
François Gaffiec005e562018-11-06 15:04:49 +01007133bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7134 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007135{
François Gaffiec005e562018-11-06 15:04:49 +01007136 return mEngine->getProductStrategyForAttributes(lAttr) ==
7137 mEngine->getProductStrategyForAttributes(rAttr);
7138}
7139
Francois Gaffieff1eb522020-05-06 18:37:04 +02007140void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7141{
7142 for (size_t i = 0; i < mAudioSources.size(); i++) {
7143 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7144 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007145 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007146 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007147 connectAudioSource(sourceDesc);
7148 }
7149 }
7150}
7151
7152void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7153{
7154 for (size_t i = 0; i < mAudioSources.size(); i++) {
7155 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7156 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7157 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7158 disconnectAudioSource(sourceDesc);
7159 }
7160 }
7161}
7162
François Gaffiec005e562018-11-06 15:04:49 +01007163void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7164{
7165 auto psId = mEngine->getProductStrategyForAttributes(attr);
7166
7167 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7168 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007169
François Gaffie11d30102018-11-02 16:09:09 +01007170 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7171 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007172
Eric Laurentc209fe42020-06-05 18:11:23 -07007173 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007174 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007175 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007176 // take into account dynamic audio policies related changes: if a client is now associated
7177 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007178 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007179 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7180 if (desc->isDuplicated()) {
7181 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007182 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007183 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7184 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7185 continue;
7186 }
7187 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007188 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007189 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7190 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7191 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007192 if (status != OK) {
7193 continue;
7194 }
yucliuf4de36d2020-09-14 14:57:56 -07007195 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007196 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007197 maxLatency = desc->latency();
7198 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007199 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007200 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007201 }
7202 }
7203
Eric Laurent56ed8842022-11-15 16:04:41 +01007204 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007205 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7206 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007207 for (audio_io_handle_t srcOut : srcOutputs) {
7208 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007209 if (desc == nullptr) continue;
7210
7211 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007212 maxLatency = desc->latency();
7213 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007214
Eric Laurent56ed8842022-11-15 16:04:41 +01007215 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007216 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007217 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007218 // a client on a non direct outputs has necessarily a linear PCM format
7219 // so we can call selectOutput() safely
7220 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7221 client->flags(),
7222 client->config().format,
7223 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007224 client->config().sample_rate,
7225 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007226 if (newOutput != srcOut) {
7227 invalidate = true;
7228 break;
7229 }
7230 } else {
7231 sp<IOProfile> profile = getProfileForOutput(newDevices,
7232 client->config().sample_rate,
7233 client->config().format,
7234 client->config().channel_mask,
7235 client->flags(),
7236 true /* directOnly */);
7237 if (profile != desc->mProfile) {
7238 invalidate = true;
7239 break;
7240 }
7241 }
7242 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007243 // mute strategy while moving tracks from one output to another
7244 if (invalidate) {
7245 invalidatedOutputs.push_back(desc);
7246 if (desc->isStrategyActive(psId)) {
7247 setStrategyMute(psId, true, desc);
7248 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7249 newDevices.types());
7250 }
Eric Laurente552edb2014-03-10 17:42:56 -07007251 }
François Gaffiec005e562018-11-06 15:04:49 +01007252 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007253 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007254 connectAudioSource(source);
7255 }
Eric Laurente552edb2014-03-10 17:42:56 -07007256 }
7257
Eric Laurent56ed8842022-11-15 16:04:41 +01007258 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7259 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7260 std::to_string(srcOutputs[0]).c_str(),
7261 std::to_string(dstOutputs[0]).c_str());
7262
François Gaffiec005e562018-11-06 15:04:49 +01007263 // Move effects associated to this stream from previous output to new output
7264 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007265 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007266 }
François Gaffiec005e562018-11-06 15:04:49 +01007267 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007268 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007269 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007270 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007271 desc->setTracksInvalidatedStatusByStrategy(psId);
7272 }
Eric Laurente552edb2014-03-10 17:42:56 -07007273 }
7274 }
7275}
7276
Eric Laurente0720872014-03-11 09:30:41 -07007277void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007278{
François Gaffiec005e562018-11-06 15:04:49 +01007279 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7280 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7281 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007282 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007283 }
Eric Laurente552edb2014-03-10 17:42:56 -07007284}
7285
Kevin Rocard153f92d2018-12-18 18:33:28 -08007286void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007287 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007288 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007289 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007290 for (size_t i = 0; i < mOutputs.size(); i++) {
7291 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7292 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007293 sp<AudioPolicyMix> primaryMix;
7294 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007295 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007296 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7297 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7298 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007299 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7300 for (auto &secondaryMix : secondaryMixes) {
7301 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7302 if (outputDesc != nullptr &&
7303 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7304 secondaryDescs.push_back(outputDesc);
7305 }
7306 }
7307
jiabinc44b3462022-12-08 12:52:31 -08007308 if (status != OK &&
7309 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7310 // When it failed to query secondary output, only invalidate the client that is not
7311 // MMAP. The reason is that MMAP stream will not support secondary output.
7312 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007313 } else if (!std::equal(
7314 client->getSecondaryOutputs().begin(),
7315 client->getSecondaryOutputs().end(),
7316 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007317 if (!audio_is_linear_pcm(client->config().format)) {
7318 // If the format is not PCM, the tracks should be invalidated to get correct
7319 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007320 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007321 } else {
7322 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7323 std::vector<audio_io_handle_t> secondaryOutputIds;
7324 for (const auto &secondaryDesc: secondaryDescs) {
7325 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7326 weakSecondaryDescs.push_back(secondaryDesc);
7327 }
7328 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7329 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007330 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007331 }
7332 }
7333 }
jiabin10a03f12021-05-07 23:46:28 +00007334 if (!trackSecondaryOutputs.empty()) {
7335 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7336 }
jiabinc44b3462022-12-08 12:52:31 -08007337 if (!clientsToInvalidate.empty()) {
7338 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7339 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007340 }
7341}
7342
Eric Laurent2517af32020-11-25 15:31:27 +01007343bool AudioPolicyManager::isScoRequestedForComm() const {
7344 AudioDeviceTypeAddrVector devices;
7345 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7346 for (const auto &device : devices) {
7347 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7348 return true;
7349 }
7350 }
7351 return false;
7352}
7353
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007354bool AudioPolicyManager::isHearingAidUsedForComm() const {
7355 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7356 true /*fromCache*/);
7357 for (const auto &device : devices) {
7358 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7359 return true;
7360 }
7361 }
7362 return false;
7363}
7364
7365
Eric Laurente0720872014-03-11 09:30:41 -07007366void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007367{
François Gaffie53615e22015-03-19 09:24:12 +01007368 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007369 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007370 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007371 return;
7372 }
7373
Eric Laurent3a4311c2014-03-17 12:00:47 -07007374 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007375 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7376 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007377 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007378
7379 // if suspended, restore A2DP output if:
7380 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007381 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007382 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007383 //
Eric Laurentf732e072016-08-03 19:30:28 -07007384 // if not suspended, suspend A2DP output if:
7385 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007386 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007387 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007388 //
7389 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007390 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007391 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007392 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007393 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007394
7395 mpClientInterface->restoreOutput(a2dpOutput);
7396 mA2dpSuspended = false;
7397 }
7398 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007399 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007400 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007401 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007402 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007403
7404 mpClientInterface->suspendOutput(a2dpOutput);
7405 mA2dpSuspended = true;
7406 }
7407 }
7408}
7409
François Gaffie11d30102018-11-02 16:09:09 +01007410DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7411 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007412{
François Gaffiedb1755b2023-09-01 11:50:35 +02007413 if (outputDesc == nullptr) {
7414 return DeviceVector{};
7415 }
François Gaffie11d30102018-11-02 16:09:09 +01007416
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007417 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007418 if (index >= 0) {
7419 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007420 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007421 ALOGV("%s device %s forced by patch %d", __func__,
7422 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7423 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007424 }
7425 }
7426
Dean Wheatley514b4312020-06-17 21:45:00 +10007427 // Do not retrieve engine device for outputs through MSD
7428 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7429 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7430 return outputDesc->devices();
7431 }
7432
Eric Laurent97ac8712018-07-27 18:59:02 -07007433 // Honor explicit routing requests only if no client using default routing is active on this
7434 // input: a specific app can not force routing for other apps by setting a preferred device.
7435 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007436 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007437 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007438 if (device != nullptr) {
7439 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007440 }
7441
François Gaffiea807ef92018-11-05 10:44:33 +01007442 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7443 // of setForceUse / Default Bus device here
7444 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7445 if (device != nullptr) {
7446 return DeviceVector(device);
7447 }
7448
François Gaffiedb1755b2023-09-01 11:50:35 +02007449 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007450 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7451 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307452 auto hasStreamActive = [&](auto stream) {
7453 return hasStream(streams, stream) && isStreamActive(stream, 0);
7454 };
Eric Laurent484e9272018-06-07 17:29:23 -07007455
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307456 auto doGetOutputDevicesForVoice = [&]() {
7457 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007458 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307459 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007460 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7461 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307462 };
7463
7464 // With low-latency playing on speaker, music on WFD, when the first low-latency
7465 // output is stopped, getNewOutputDevices checks for a product strategy
7466 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007467 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307468 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7469 // stream is associated to the output descriptor.
7470 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7471 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7472 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7473 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007474 // Retrieval of devices for voice DL is done on primary output profile, cannot
7475 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007476 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007477 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7478 break;
7479 }
Eric Laurente552edb2014-03-10 17:42:56 -07007480 }
François Gaffiec005e562018-11-06 15:04:49 +01007481 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007482 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007483}
7484
François Gaffie11d30102018-11-02 16:09:09 +01007485sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7486 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007487{
François Gaffie11d30102018-11-02 16:09:09 +01007488 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007489
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007490 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007491 if (index >= 0) {
7492 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007493 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007494 ALOGV("getNewInputDevice() device %s forced by patch %d",
7495 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7496 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007497 }
7498 }
7499
Eric Laurent97ac8712018-07-27 18:59:02 -07007500 // Honor explicit routing requests only if no client using default routing is active on this
7501 // input: a specific app can not force routing for other apps by setting a preferred device.
7502 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007503 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7504 if (device != nullptr) {
7505 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007506 }
7507
Eric Laurentdc95a252018-04-12 12:46:56 -07007508 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007509 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007510 audio_attributes_t attributes;
7511 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007512 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007513 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7514 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007515 attributes = topClient->attributes();
7516 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007517 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007518 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007519 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7520 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007521 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007522 }
7523
Francois Gaffie716e1432019-01-14 16:58:59 +01007524 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7525 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007526 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007527 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007528 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007529 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007530
Eric Laurente552edb2014-03-10 17:42:56 -07007531 return device;
7532}
7533
Eric Laurent794fde22016-03-11 09:50:45 -08007534bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7535 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007536 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007537}
7538
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007539status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007540 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007541 if (devices == nullptr) {
7542 return BAD_VALUE;
7543 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007544
Andy Hung6d23c0f2022-02-16 09:37:15 -08007545 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007546 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7547 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007548 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007549 for (const auto& device : curDevices) {
7550 devices->push_back(device->getDeviceTypeAddr());
7551 }
7552 return NO_ERROR;
7553}
7554
Eric Laurente0720872014-03-11 09:30:41 -07007555void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007556 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007557 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007558 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007559 updateDevicesAndOutputs();
7560 break;
7561 default:
7562 break;
7563 }
7564}
7565
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007566uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007567
7568 // skip beacon mute management if a dedicated TTS output is available
7569 if (mTtsOutputAvailable) {
7570 return 0;
7571 }
7572
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007573 switch(event) {
7574 case STARTING_OUTPUT:
7575 mBeaconMuteRefCount++;
7576 break;
7577 case STOPPING_OUTPUT:
7578 if (mBeaconMuteRefCount > 0) {
7579 mBeaconMuteRefCount--;
7580 }
7581 break;
7582 case STARTING_BEACON:
7583 mBeaconPlayingRefCount++;
7584 break;
7585 case STOPPING_BEACON:
7586 if (mBeaconPlayingRefCount > 0) {
7587 mBeaconPlayingRefCount--;
7588 }
7589 break;
7590 }
7591
7592 if (mBeaconMuteRefCount > 0) {
7593 // any playback causes beacon to be muted
7594 return setBeaconMute(true);
7595 } else {
7596 // no other playback: unmute when beacon starts playing, mute when it stops
7597 return setBeaconMute(mBeaconPlayingRefCount == 0);
7598 }
7599}
7600
7601uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7602 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7603 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7604 // keep track of muted state to avoid repeating mute/unmute operations
7605 if (mBeaconMuted != mute) {
7606 // mute/unmute AUDIO_STREAM_TTS on all outputs
7607 ALOGV("\t muting %d", mute);
7608 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007609 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7610 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7611 ALOGV("\t no tts volume source available");
7612 return 0;
7613 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007614 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007615 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007616 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007617 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007618 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007619 maxLatency = latency;
7620 }
7621 }
7622 mBeaconMuted = mute;
7623 return maxLatency;
7624 }
7625 return 0;
7626}
7627
Eric Laurente0720872014-03-11 09:30:41 -07007628void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007629{
François Gaffiec005e562018-11-06 15:04:49 +01007630 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007631 mPreviousOutputs = mOutputs;
7632}
7633
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007634uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007635 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007636 uint32_t delayMs)
7637{
7638 // mute/unmute strategies using an incompatible device combination
7639 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7640 // if unmuting, unmute only after the specified delay
7641 if (outputDesc->isDuplicated()) {
7642 return 0;
7643 }
7644
7645 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007646 DeviceVector devices = outputDesc->devices();
7647 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007648
François Gaffiec005e562018-11-06 15:04:49 +01007649 auto productStrategies = mEngine->getOrderedProductStrategies();
7650 for (const auto &productStrategy : productStrategies) {
7651 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7652 DeviceVector curDevices =
7653 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7654 curDevices = curDevices.filter(outputDesc->supportedDevices());
7655 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007656 bool doMute = false;
7657
François Gaffiec005e562018-11-06 15:04:49 +01007658 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007659 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007660 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7661 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007662 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007663 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007664 }
Eric Laurent99401132014-05-07 19:48:15 -07007665 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007666 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007667 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007668 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007669 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007670 continue;
7671 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307672 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007673 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7674 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7675 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007676 if (mute) {
7677 // FIXME: should not need to double latency if volume could be applied
7678 // immediately by the audioflinger mixer. We must account for the delay
7679 // between now and the next time the audioflinger thread for this output
7680 // will process a buffer (which corresponds to one buffer size,
7681 // usually 1/2 or 1/4 of the latency).
7682 if (muteWaitMs < desc->latency() * 2) {
7683 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007684 }
7685 }
7686 }
7687 }
7688 }
7689 }
7690
Eric Laurent99401132014-05-07 19:48:15 -07007691 // temporary mute output if device selection changes to avoid volume bursts due to
7692 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007693 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007694 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007695
Eric Laurentdc462862016-07-19 12:29:53 -07007696 if (muteWaitMs < tempMuteWaitMs) {
7697 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007698 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007699
7700 // If recommended duration is defined, replace temporary mute duration to avoid
7701 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7702 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7703 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7704 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7705 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7706
François Gaffieaaac0fd2018-11-22 17:56:39 +01007707 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7708 // make sure that we do not start the temporary mute period too early in case of
7709 // delayed device change
7710 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7711 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007712 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007713 }
7714 }
7715
Eric Laurente552edb2014-03-10 17:42:56 -07007716 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7717 if (muteWaitMs > delayMs) {
7718 muteWaitMs -= delayMs;
7719 usleep(muteWaitMs * 1000);
7720 return muteWaitMs;
7721 }
7722 return 0;
7723}
7724
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307725uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7726 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007727 const DeviceVector &devices,
7728 bool force,
7729 int delayMs,
7730 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007731 bool requiresMuteCheck, bool requiresVolumeCheck,
7732 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007733{
jiabin3ff8d7d2022-12-13 06:27:44 +00007734 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307735 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7736 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7737 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007738 uint32_t muteWaitMs;
7739
7740 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307741 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007742 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307743 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007744 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007745 return muteWaitMs;
7746 }
Eric Laurente552edb2014-03-10 17:42:56 -07007747
7748 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007749 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007750 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007751 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007752
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307753 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7754 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007755
7756 if (!filteredDevices.isEmpty()) {
7757 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007758 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007759
7760 // if the outputs are not materially active, there is no need to mute.
7761 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007762 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007763 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307764 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7765 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007766 muteWaitMs = 0;
7767 }
Eric Laurente552edb2014-03-10 17:42:56 -07007768
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007769 bool outputRouted = outputDesc->isRouted();
7770
Eric Laurent79ea9582020-06-11 18:49:24 -07007771 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7772 // output profile or if new device is not supported AND previous device(s) is(are) still
7773 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007774 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307775 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7776 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007777 // restore previous device after evaluating strategy mute state
7778 outputDesc->setDevices(prevDevices);
7779 return muteWaitMs;
7780 }
7781
Eric Laurente552edb2014-03-10 17:42:56 -07007782 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007783 // the requested device is AUDIO_DEVICE_NONE
7784 // OR the requested device is the same as current device
7785 // AND force is not specified
7786 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007787 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007788 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307789 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7790 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7791 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007792 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307793 ALOGV("%s %s setting same device on routed output, force apply volumes",
7794 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007795 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7796 }
Eric Laurente552edb2014-03-10 17:42:56 -07007797 return muteWaitMs;
7798 }
7799
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307800 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7801 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007802
Eric Laurente552edb2014-03-10 17:42:56 -07007803 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007804 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007805 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007806 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007807 PatchBuilder patchBuilder;
7808 patchBuilder.addSource(outputDesc);
7809 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7810 for (const auto &filteredDevice : filteredDevices) {
7811 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007812 }
7813
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007814 // Add half reported latency to delayMs when muteWaitMs is null in order
7815 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007816 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7817 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7818 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007819 }
Eric Laurente552edb2014-03-10 17:42:56 -07007820
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007821 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7822 if (!skipMuteDelay) {
7823 // update stream volumes according to new device
7824 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7825 }
Eric Laurente552edb2014-03-10 17:42:56 -07007826
7827 return muteWaitMs;
7828}
7829
Eric Laurentc75307b2015-03-17 15:29:32 -07007830status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007831 int delayMs,
7832 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007833{
Eric Laurent6a94d692014-05-20 11:18:06 -07007834 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007835 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7836 return INVALID_OPERATION;
7837 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007838 if (patchHandle) {
7839 index = mAudioPatches.indexOfKey(*patchHandle);
7840 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007841 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007842 }
7843 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007844 return INVALID_OPERATION;
7845 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007846 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007847 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007848 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007849 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007850 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007851 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007852 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007853 return status;
7854}
7855
7856status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007857 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007858 bool force,
7859 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007860{
7861 status_t status = NO_ERROR;
7862
Eric Laurent1f2f2232014-06-02 12:01:23 -07007863 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007864 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7865 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007866
François Gaffie11d30102018-11-02 16:09:09 +01007867 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007868 PatchBuilder patchBuilder;
7869 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007870 // AUDIO_SOURCE_HOTWORD is for internal use only:
7871 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007872 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7873 auto result = usecase;
7874 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7875 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7876 }
7877 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007878 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007879 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007880 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007881 }
7882 }
7883 return status;
7884}
7885
Eric Laurent6a94d692014-05-20 11:18:06 -07007886status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7887 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007888{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007889 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007890 ssize_t index;
7891 if (patchHandle) {
7892 index = mAudioPatches.indexOfKey(*patchHandle);
7893 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007894 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007895 }
7896 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007897 return INVALID_OPERATION;
7898 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007899 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007900 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007901 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007902 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007903 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007904 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007905 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007906 return status;
7907}
7908
François Gaffie11d30102018-11-02 16:09:09 +01007909sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007910 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007911 audio_format_t& format,
7912 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007913 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007914{
7915 // Choose an input profile based on the requested capture parameters: select the first available
7916 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007917 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007918
Atneya Nair0f0a8032022-12-12 16:20:12 -08007919 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7920 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7921 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7922
7923 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007924
jiabin2fd710d2022-05-02 23:20:22 +00007925 for (;;) {
7926 sp<IOProfile> firstInexact = nullptr;
7927 uint32_t updatedSamplingRate = 0;
7928 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7929 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7930 for (const auto& hwModule : mHwModules) {
7931 for (const auto& profile : hwModule->getInputProfiles()) {
7932 // profile->log();
7933 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007934 if (profile->getCompatibilityScore(
7935 DeviceVector(device),
7936 samplingRate,
7937 &updatedSamplingRate,
7938 format,
7939 &updatedFormat,
7940 channelMask,
7941 &updatedChannelMask,
7942 // FIXME ugly cast
7943 (audio_output_flags_t) flags,
7944 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7945 samplingRate = updatedSamplingRate;
7946 format = updatedFormat;
7947 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007948 return profile;
7949 }
jiabin66acc432024-02-06 00:57:36 +00007950 if (firstInexact == nullptr
7951 && profile->getCompatibilityScore(
7952 DeviceVector(device),
7953 samplingRate,
7954 &updatedSamplingRate,
7955 format,
7956 &updatedFormat,
7957 channelMask,
7958 &updatedChannelMask,
7959 // FIXME ugly cast
7960 (audio_output_flags_t) flags,
7961 false /*exactMatchRequiredForInputFlags*/)
7962 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007963 firstInexact = profile;
7964 }
7965 }
7966 }
7967
7968 if (firstInexact != nullptr) {
7969 samplingRate = updatedSamplingRate;
7970 format = updatedFormat;
7971 channelMask = updatedChannelMask;
7972 return firstInexact;
7973 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7974 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7975 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7976 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7977 flags = AUDIO_INPUT_FLAG_NONE;
7978 } else { // fail
7979 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7980 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7981 samplingRate, format, channelMask, oriFlags);
7982 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007983 }
7984 }
jiabin2fd710d2022-05-02 23:20:22 +00007985
7986 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007987}
7988
François Gaffieaaac0fd2018-11-22 17:56:39 +01007989float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7990 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007991 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007992 const DeviceTypeSet& deviceTypes,
7993 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07007994{
jiabin9a3361e2019-10-01 09:38:30 -07007995 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007996
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007997 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
7998 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
7999
8000 if (!computeInternalInteraction) {
8001 return volumeDb;
8002 }
8003
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008004 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8005 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8006 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8007 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008008 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8009 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8010 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8011 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8012 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008013 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008014 mOutputs.isActive(ringVolumeSrc, 0)) {
8015 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008016 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8017 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008018 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008019 }
8020
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008021 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008022 if ((volumeSource != callVolumeSrc && (isInCall() ||
8023 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008024 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008025 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8026 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008027 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8028 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8029 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008030 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008031 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008032 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008033 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008034 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8035 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008036 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008037 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8038 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8039 // programmatically muted.
8040 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8041 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8042 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008043 bool exemptFromCapping =
8044 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8045 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008046 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8047 volumeSource, volumeDb);
8048 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008049 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8050 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8051 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008052 }
8053 }
Eric Laurente552edb2014-03-10 17:42:56 -07008054 // if a headset is connected, apply the following rules to ring tones and notifications
8055 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008056 // - always attenuate notifications volume by 6dB
8057 // - attenuate ring tones volume by 6dB unless music is not playing and
8058 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008059 // - if music is playing, always limit the volume to current music volume,
8060 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008061 if (!Intersection(deviceTypes,
8062 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8063 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008064 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8065 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008066 ((volumeSource == alarmVolumeSrc ||
8067 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008068 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8069 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8070 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008071 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8072 curves.canBeMuted()) {
8073
Eric Laurente552edb2014-03-10 17:42:56 -07008074 // when the phone is ringing we must consider that music could have been paused just before
8075 // by the music application and behave as if music was active if the last music track was
8076 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008077 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8078 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008079 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008080 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008081 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8082 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008083 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008084 float musicVolDb = computeVolume(musicCurves,
8085 musicVolumeSrc,
8086 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008087 musicDevice,
8088 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008089 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8090 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8091 if (volumeDb > minVolDb) {
8092 volumeDb = minVolDb;
8093 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008094 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008095 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8096 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
8097 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008098 // on A2DP, also ensure notification volume is not too low compared to media when
8099 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01008100 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008101 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008102 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8103 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008104 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8105 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008106 }
8107 }
jiabin9a3361e2019-10-01 09:38:30 -07008108 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008109 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008110 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008111 }
8112 }
8113
François Gaffie43c73442018-11-08 08:21:55 +01008114 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008115}
8116
Eric Laurent3839bc02018-07-10 18:33:34 -07008117int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008118 VolumeSource fromVolumeSource,
8119 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008120{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008121 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008122 return srcIndex;
8123 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008124 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8125 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008126 float minSrc = (float)srcCurves.getVolumeIndexMin();
8127 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8128 float minDst = (float)dstCurves.getVolumeIndexMin();
8129 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008130
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008131 // preserve mute request or correct range
8132 if (srcIndex < minSrc) {
8133 if (srcIndex == 0) {
8134 return 0;
8135 }
8136 srcIndex = minSrc;
8137 } else if (srcIndex > maxSrc) {
8138 srcIndex = maxSrc;
8139 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008140 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8141}
8142
François Gaffieaaac0fd2018-11-22 17:56:39 +01008143status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8144 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008145 int index,
8146 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008147 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008148 int delayMs,
8149 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008150{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008151 // do not change actual attributes volume if the attributes is muted
8152 if (outputDesc->isMuted(volumeSource)) {
8153 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8154 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008155 return NO_ERROR;
8156 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008157
Eric Laurentae6e88c2024-01-10 14:42:57 +01008158 bool isVoiceVolSrc;
8159 bool isBtScoVolSrc;
8160 if (!isVolumeConsistentForCalls(
8161 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008162 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008163 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008164 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008165 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008166
jiabin9a3361e2019-10-01 09:38:30 -07008167 if (deviceTypes.empty()) {
8168 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008169 index = curves.getVolumeIndex(deviceTypes);
8170 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
8171 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008172 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008173
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008174 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8175 ALOGE("invalid volume index range");
8176 return BAD_VALUE;
8177 }
8178
jiabin9a3361e2019-10-01 09:38:30 -07008179 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8180 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008181 // Force VoIP volume to max for bluetooth SCO device except if muted
8182 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008183 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008184 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008185 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008186 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008187 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8188 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008189
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008190 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008191 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008192 }
Eric Laurente552edb2014-03-10 17:42:56 -07008193 return NO_ERROR;
8194}
8195
Eric Laurentae6e88c2024-01-10 14:42:57 +01008196void AudioPolicyManager::setVoiceVolume(
8197 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8198 float voiceVolume;
8199 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8200 // by the headset
8201 if (isVoiceVolSrc) {
8202 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8203 } else {
8204 voiceVolume = index == 0 ? 0.0 : 1.0;
8205 }
8206 if (voiceVolume != mLastVoiceVolume) {
8207 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8208 mLastVoiceVolume = voiceVolume;
8209 }
8210}
8211
8212bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8213 const DeviceTypeSet& deviceTypes,
8214 bool& isVoiceVolSrc,
8215 bool& isBtScoVolSrc,
8216 const char* caller) {
8217 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8218 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8219 const bool isScoRequested = isScoRequestedForComm();
8220 const bool isHAUsed = isHearingAidUsedForComm();
8221
8222 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8223 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8224
8225 if ((callVolSrc != btScoVolSrc) &&
8226 ((isVoiceVolSrc && isScoRequested) ||
8227 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8228 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8229 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8230 volumeSource, isScoRequested ? " " : " not ");
8231 return false;
8232 }
8233 return true;
8234}
8235
Eric Laurentc75307b2015-03-17 15:29:32 -07008236void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008237 const DeviceTypeSet& deviceTypes,
8238 int delayMs,
8239 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008240{
jiabincd510522020-01-22 09:40:55 -08008241 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008242 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8243 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8244 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008245 curves.getVolumeIndex(deviceTypes),
8246 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008247 }
8248}
8249
François Gaffiec005e562018-11-06 15:04:49 +01008250void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8251 bool on,
8252 const sp<AudioOutputDescriptor>& outputDesc,
8253 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008254 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008255{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008256 std::vector<VolumeSource> sourcesToMute;
8257 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8258 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8259 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008260 VolumeSource source = toVolumeSource(attributes, false);
8261 if ((source != VOLUME_SOURCE_NONE) &&
8262 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8263 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008264 sourcesToMute.push_back(source);
8265 }
Eric Laurente552edb2014-03-10 17:42:56 -07008266 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008267 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008268 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008269 }
8270
Eric Laurente552edb2014-03-10 17:42:56 -07008271}
8272
François Gaffieaaac0fd2018-11-22 17:56:39 +01008273void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8274 bool on,
8275 const sp<AudioOutputDescriptor>& outputDesc,
8276 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008277 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008278{
jiabin9a3361e2019-10-01 09:38:30 -07008279 if (deviceTypes.empty()) {
8280 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008281 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008282 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008283 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008284 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008285 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008286 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008287 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8288 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008289 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008290 }
8291 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008292 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8293 // ignored
8294 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008295 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008296 if (!outputDesc->isMuted(volumeSource)) {
8297 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008298 return;
8299 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008300 if (outputDesc->decMuteCount(volumeSource) == 0) {
8301 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008302 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008303 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008304 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008305 delayMs);
8306 }
8307 }
8308}
8309
François Gaffie53615e22015-03-19 09:24:12 +01008310bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8311{
François Gaffiec005e562018-11-06 15:04:49 +01008312 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008313 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8314 return true;
8315 }
8316
8317 // has known usage?
8318 switch (paa->usage) {
8319 case AUDIO_USAGE_UNKNOWN:
8320 case AUDIO_USAGE_MEDIA:
8321 case AUDIO_USAGE_VOICE_COMMUNICATION:
8322 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8323 case AUDIO_USAGE_ALARM:
8324 case AUDIO_USAGE_NOTIFICATION:
8325 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8326 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8327 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8328 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8329 case AUDIO_USAGE_NOTIFICATION_EVENT:
8330 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8331 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8332 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8333 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008334 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008335 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008336 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008337 case AUDIO_USAGE_EMERGENCY:
8338 case AUDIO_USAGE_SAFETY:
8339 case AUDIO_USAGE_VEHICLE_STATUS:
8340 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008341 break;
8342 default:
8343 return false;
8344 }
8345 return true;
8346}
8347
François Gaffie2110e042015-03-24 08:41:51 +01008348audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8349{
8350 return mEngine->getForceUse(usage);
8351}
8352
Eric Laurent96d1dda2022-03-14 17:14:19 +01008353bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008354 return isStateInCall(mEngine->getPhoneState());
8355}
8356
Eric Laurent96d1dda2022-03-14 17:14:19 +01008357bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008358 return is_state_in_call(state);
8359}
8360
Eric Laurentf9cccec2022-11-16 19:12:00 +01008361bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008362 audio_mode_t mode = mEngine->getPhoneState();
8363 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008364 || (mode == AUDIO_MODE_CALL_SCREEN)
8365 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008366}
8367
Eric Laurentf9cccec2022-11-16 19:12:00 +01008368bool AudioPolicyManager::isInCallOrScreening() const {
8369 audio_mode_t mode = mEngine->getPhoneState();
8370 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8371}
8372
Eric Laurentd60560a2015-04-10 11:31:20 -07008373void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8374{
8375 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008376 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008377 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008378 sourceDesc->sinkDevice()->equals(deviceDesc))
8379 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008380 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008381 }
8382 }
8383
8384 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8385 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8386 bool release = false;
8387 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8388 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8389 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8390 source->ext.device.type == deviceDesc->type()) {
8391 release = true;
8392 }
8393 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008394 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008395 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8396 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8397 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008398 sink->ext.device.type == deviceDesc->type() &&
8399 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8400 || strncmp(sink->ext.device.address, address,
8401 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008402 release = true;
8403 }
8404 }
8405 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008406 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8407 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008408 }
8409 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008410
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008411 mInputs.clearSessionRoutesForDevice(deviceDesc);
8412
Francois Gaffie716e1432019-01-14 16:58:59 +01008413 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008414}
8415
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008416void AudioPolicyManager::modifySurroundFormats(
8417 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008418 std::unordered_set<audio_format_t> enforcedSurround(
8419 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008420 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008421 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008422 allSurround.insert(pair.first);
8423 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8424 }
Phil Burk09bc4612016-02-24 15:58:15 -08008425
8426 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8427 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008428 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008429 // This is the resulting set of formats depending on the surround mode:
8430 // 'all surround' = allSurround
8431 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8432 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8433 // 'manual surround' = mManualSurroundFormats
8434 // AUTO: formats v 'enforced surround'
8435 // ALWAYS: formats v 'all surround' v 'enforced surround'
8436 // NEVER: formats ^ 'non-surround'
8437 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008438
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008439 std::unordered_set<audio_format_t> formatSet;
8440 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8441 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008442 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008443 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008444 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008445 formatSet.insert(*formatIter);
8446 }
8447 }
8448 } else {
8449 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8450 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008451 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008452
jiabin81772902018-04-02 17:52:27 -07008453 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008454 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008455 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8456 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8457 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008458 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008459 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8460 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8461 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008462 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008463 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008464 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008465 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008466 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008467 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008468}
8469
jiabin06e4bab2019-07-29 10:13:34 -07008470void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8471 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008472 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8473 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8474
8475 // If NEVER, then remove support for channelMasks > stereo.
8476 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008477 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8478 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008479 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008480 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008481 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008482 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008483 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008484 }
8485 }
jiabin81772902018-04-02 17:52:27 -07008486 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8487 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8488 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008489 bool supports5dot1 = false;
8490 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008491 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008492 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8493 supports5dot1 = true;
8494 break;
8495 }
8496 }
8497 // If not then add 5.1 support.
8498 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008499 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008500 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008501 }
Phil Burk09bc4612016-02-24 15:58:15 -08008502 }
8503}
8504
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008505void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008506 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008507 const sp<IOProfile>& profile) {
8508 if (!profile->hasDynamicAudioProfile()) {
8509 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008510 }
François Gaffie112b0af2015-11-19 16:13:25 +01008511
jiabin12537fc2023-10-12 17:56:08 +00008512 audio_port_v7 devicePort;
8513 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008514
jiabin12537fc2023-10-12 17:56:08 +00008515 audio_port_v7 mixPort;
8516 profile->toAudioPort(&mixPort);
8517 mixPort.ext.mix.handle = ioHandle;
8518
8519 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8520 if (status != NO_ERROR) {
8521 ALOGE("%s failed to query the attributes of the mix port", __func__);
8522 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008523 }
jiabin12537fc2023-10-12 17:56:08 +00008524
8525 std::set<audio_format_t> supportedFormats;
8526 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8527 supportedFormats.insert(mixPort.audio_profiles[i].format);
8528 }
8529 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8530 mReportedFormatsMap[devDesc] = formats;
8531
8532 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8533 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8534 modifySurroundFormats(devDesc, &formats);
8535 size_t modifiedNumProfiles = 0;
8536 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8537 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8538 formats.end()) {
8539 // Skip the format that is not present after modifying surround formats.
8540 continue;
8541 }
8542 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8543 sizeof(struct audio_profile));
8544 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8545 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8546 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8547 modifySurroundChannelMasks(&channels);
8548 std::copy(channels.begin(), channels.end(),
8549 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8550 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8551 }
8552 mixPort.num_audio_profiles = modifiedNumProfiles;
8553 }
8554 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008555}
Eric Laurentd60560a2015-04-10 11:31:20 -07008556
Mikhail Naganovdc769682018-05-04 15:34:08 -07008557status_t AudioPolicyManager::installPatch(const char *caller,
8558 audio_patch_handle_t *patchHandle,
8559 AudioIODescriptorInterface *ioDescriptor,
8560 const struct audio_patch *patch,
8561 int delayMs)
8562{
8563 ssize_t index = mAudioPatches.indexOfKey(
8564 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8565 *patchHandle : ioDescriptor->getPatchHandle());
8566 sp<AudioPatch> patchDesc;
8567 status_t status = installPatch(
8568 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8569 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008570 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008571 }
8572 return status;
8573}
8574
8575status_t AudioPolicyManager::installPatch(const char *caller,
8576 ssize_t index,
8577 audio_patch_handle_t *patchHandle,
8578 const struct audio_patch *patch,
8579 int delayMs,
8580 uid_t uid,
8581 sp<AudioPatch> *patchDescPtr)
8582{
8583 sp<AudioPatch> patchDesc;
8584 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8585 if (index >= 0) {
8586 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008587 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008588 }
8589
8590 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8591 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8592 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8593 if (status == NO_ERROR) {
8594 if (index < 0) {
8595 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008596 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008597 } else {
8598 patchDesc->mPatch = *patch;
8599 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008600 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008601 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008602 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008603 }
8604 nextAudioPortGeneration();
8605 mpClientInterface->onAudioPatchListUpdate();
8606 }
8607 if (patchDescPtr) *patchDescPtr = patchDesc;
8608 return status;
8609}
8610
jiabinbce0c1d2020-10-05 11:20:18 -07008611bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8612{
8613 const TrackClientVector activeClients = output->getActiveClients();
8614 if (activeClients.empty()) {
8615 return true;
8616 }
8617 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8618 if (index < 0) {
8619 ALOGE("%s, no audio patch found while there are active clients on output %d",
8620 __func__, output->getId());
8621 return false;
8622 }
8623 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8624 DeviceVector routedDevices;
8625 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8626 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8627 patchDesc->mPatch.sinks[i].id);
8628 if (device == nullptr) {
8629 ALOGE("%s, no audio device found with id(%d)",
8630 __func__, patchDesc->mPatch.sinks[i].id);
8631 return false;
8632 }
8633 routedDevices.add(device);
8634 }
8635 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008636 if (client->isInvalid()) {
8637 // No need to take care about invalidated clients.
8638 continue;
8639 }
jiabinbce0c1d2020-10-05 11:20:18 -07008640 sp<DeviceDescriptor> preferredDevice =
8641 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8642 if (mEngine->getOutputDevicesForAttributes(
8643 client->attributes(), preferredDevice, false) == routedDevices) {
8644 return false;
8645 }
8646 }
8647 return true;
8648}
8649
8650sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008651 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008652 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8653 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008654{
8655 for (const auto& device : devices) {
8656 // TODO: This should be checking if the profile supports the device combo.
8657 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008658 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8659 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008660 return nullptr;
8661 }
8662 }
8663 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8664 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008665 status_t status = desc->open(halConfig, mixerConfig, devices,
8666 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008667 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008668 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008669 return nullptr;
8670 }
jiabin14b50cc2023-12-13 19:01:52 +00008671 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8672 auto portConfig = desc->getConfig();
8673 for (const auto& device : devices) {
8674 device->setPreferredConfig(&portConfig);
8675 }
8676 }
jiabinbce0c1d2020-10-05 11:20:18 -07008677
8678 // Here is where the out_set_parameters() for card & device gets called
8679 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8680 const audio_devices_t deviceType = device->type();
8681 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008682 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008683 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8684 mpClientInterface->setParameters(output, String8(param));
8685 free(param);
8686 }
jiabin12537fc2023-10-12 17:56:08 +00008687 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008688 if (!profile->hasValidAudioProfile()) {
8689 ALOGW("%s() missing param", __func__);
8690 desc->close();
8691 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008692 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8693 // Reopen the output with the best audio profile picked by APM when the profile supports
8694 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008695 desc->close();
8696 output = AUDIO_IO_HANDLE_NONE;
8697 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8698 profile->pickAudioProfile(
8699 config.sample_rate, config.channel_mask, config.format);
8700 config.offload_info.sample_rate = config.sample_rate;
8701 config.offload_info.channel_mask = config.channel_mask;
8702 config.offload_info.format = config.format;
8703
jiabina84c3d32022-12-02 18:59:55 +00008704 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008705 if (status != NO_ERROR) {
8706 return nullptr;
8707 }
8708 }
8709
8710 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008711 setOutputDevices(__func__, desc,
8712 devices,
8713 true,
8714 0,
8715 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008716 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8717 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8718
jiabinbce0c1d2020-10-05 11:20:18 -07008719 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8720 sp<AudioPolicyMix> policyMix;
8721 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8722 policyMix->setOutput(desc);
8723 desc->mPolicyMix = policyMix;
8724 } else {
8725 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008726 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008727 }
8728
baek.kim -61c20122022-07-27 10:05:32 +00008729 } else if (hasPrimaryOutput() && speaker != nullptr
8730 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008731 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8732 // no duplicated output for:
8733 // - direct outputs
8734 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008735 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008736 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8737
8738 //TODO: configure audio effect output stage here
8739
8740 // open a duplicating output thread for the new output and the primary output
8741 sp<SwAudioOutputDescriptor> dupOutputDesc =
8742 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8743 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8744 if (status == NO_ERROR) {
8745 // add duplicated output descriptor
8746 addOutput(duplicatedOutput, dupOutputDesc);
8747 } else {
8748 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8749 mPrimaryOutput->mIoHandle, output);
8750 desc->close();
8751 removeOutput(output);
8752 nextAudioPortGeneration();
8753 return nullptr;
8754 }
8755 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008756 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8757 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8758 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008759 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008760 }
jiabinbce0c1d2020-10-05 11:20:18 -07008761 return desc;
8762}
8763
jiabinf1c73972022-04-14 16:28:52 -07008764status_t AudioPolicyManager::getDevicesForAttributes(
8765 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8766 // Devices are determined in the following precedence:
8767 //
8768 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8769 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8770 //
8771 // If no such dynamic policy then
8772 // 2) Devices containing an active client using setPreferredDevice
8773 // with same strategy as the attributes.
8774 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8775 //
8776 // If no corresponding active client with setPreferredDevice then
8777 // 3) Devices associated with the strategy determined by the attributes
8778 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8779 //
8780 // See related getOutputForAttrInt().
8781
8782 // check dynamic policies but only for primary descriptors (secondary not used for audible
8783 // audio routing, only used for duplication for playback capture)
8784 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008785 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008786 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008787 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8788 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8789 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008790 if (status != OK) {
8791 return status;
8792 }
8793
8794 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8795 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8796 // as they are unaffected by device/stream volume
8797 // (per SwAudioOutputDescriptor::isFixedVolume()).
8798 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8799 ) {
8800 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8801 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8802 devices.add(deviceDesc);
8803 } else {
8804 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8805 // which selects setPreferredDevice if active. This means forVolume call
8806 // will take an active setPreferredDevice, if such exists.
8807
8808 devices = mEngine->getOutputDevicesForAttributes(
8809 attr, nullptr /* preferredDevice */, false /* fromCache */);
8810 }
8811
8812 if (forVolume) {
8813 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8814 // for single volume control in AudioService (such relationship should exist if
8815 // SPEAKER_SAFE is present).
8816 //
8817 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8818 DeviceVector speakerSafeDevices =
8819 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8820 if (!speakerSafeDevices.isEmpty()) {
8821 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8822 devices.remove(speakerSafeDevices);
8823 }
8824 }
8825
8826 return NO_ERROR;
8827}
8828
8829status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8830 AudioProfileVector& audioProfiles,
8831 uint32_t flags,
8832 bool isInput) {
8833 for (const auto& hwModule : mHwModules) {
8834 // the MSD module checks for different conditions
8835 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8836 continue;
8837 }
8838 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8839 : hwModule->getOutputProfiles();
8840 for (const auto& profile : ioProfiles) {
8841 if (!profile->areAllDevicesSupported(devices) ||
8842 !profile->isCompatibleProfileForFlags(
8843 flags, false /*exactMatchRequiredForInputFlags*/)) {
8844 continue;
8845 }
8846 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8847 }
8848 }
8849
8850 if (!isInput) {
8851 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8852 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8853 if (msdModule != nullptr) {
8854 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8855 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8856 for (const auto &profile: msdModule->getOutputProfiles()) {
8857 if (!profile->asAudioPort()->isDirectOutput()) {
8858 continue;
8859 }
8860 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8861 }
8862 } else {
8863 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8864 }
8865 }
8866 }
8867
8868 return NO_ERROR;
8869}
8870
jiabin3ff8d7d2022-12-13 06:27:44 +00008871sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8872 const audio_config_t *config,
8873 audio_output_flags_t flags,
8874 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008875 closeOutput(outputDesc->mIoHandle);
8876 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8877 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8878 if (preferredOutput == nullptr) {
8879 ALOGE("%s failed to reopen output device=%d, caller=%s",
8880 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008881 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008882 return preferredOutput;
8883}
8884
8885void AudioPolicyManager::reopenOutputsWithDevices(
8886 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8887 for (const auto& [output, devices] : outputsToReopen) {
8888 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8889 closeOutput(output);
8890 openOutputWithProfileAndDevice(desc->mProfile, devices);
8891 }
jiabina84c3d32022-12-02 18:59:55 +00008892}
8893
jiabinc44b3462022-12-08 12:52:31 -08008894PortHandleVector AudioPolicyManager::getClientsForStream(
8895 audio_stream_type_t streamType) const {
8896 PortHandleVector clients;
8897 for (size_t i = 0; i < mOutputs.size(); ++i) {
8898 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8899 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8900 }
8901 return clients;
8902}
8903
8904void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8905 PortHandleVector clients;
8906 for (auto stream : streams) {
8907 PortHandleVector clientsForStream = getClientsForStream(stream);
8908 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8909 }
8910 mpClientInterface->invalidateTracks(clients);
8911}
8912
jiabin220eea12024-05-17 17:55:20 +00008913void AudioPolicyManager::updateClientsInternalMute(
8914 const sp<android::SwAudioOutputDescriptor> &desc) {
8915 if (!desc->isBitPerfect() ||
8916 !com::android::media::audioserver::
8917 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
8918 // This is only used for bit perfect output now.
8919 return;
8920 }
8921 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
8922 bool bitPerfectClientInternalMute = false;
8923 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
8924 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
8925 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
8926 bitPerfectClient = client;
8927 continue;
8928 }
8929 bool muted = false;
8930 if (client->stream() == AUDIO_STREAM_SYSTEM) {
8931 // System sound is muted.
8932 muted = true;
8933 } else {
8934 bitPerfectClientInternalMute = true;
8935 }
8936 if (client->setInternalMute(muted)) {
8937 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
8938 if (!result.ok()) {
8939 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
8940 continue;
8941 }
8942 media::TrackInternalMuteInfo info;
8943 info.portId = result.value();
8944 info.muted = client->getInternalMute();
8945 clientsInternalMute.push_back(std::move(info));
8946 }
8947 }
8948 if (bitPerfectClient != nullptr &&
8949 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
8950 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
8951 if (result.ok()) {
8952 media::TrackInternalMuteInfo info;
8953 info.portId = result.value();
8954 info.muted = bitPerfectClient->getInternalMute();
8955 clientsInternalMute.push_back(std::move(info));
8956 } else {
8957 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
8958 __func__, bitPerfectClient->portId());
8959 }
8960 }
8961 if (!clientsInternalMute.empty()) {
8962 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
8963 status != NO_ERROR) {
8964 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
8965 }
8966 }
8967}
8968
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008969} // namespace android