blob: aae248b6982e219e9551cb8799a808591fefd58a [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
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 Naganov3754b642024-04-17 18:31:04 +0000132 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 Naganov3754b642024-04-17 18:31:04 +0000222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000341 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530377 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700378 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } // end if is output device
380
Eric Laurente552edb2014-03-10 17:42:56 -0700381 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700382 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700384 switch (state)
385 {
386 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700390 return INVALID_OPERATION;
391 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700392
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530393 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (mAvailableInputDevices.add(device) < 0) {
396 return NO_MEMORY;
397 }
398
François Gaffie44481e72016-04-20 07:49:57 +0200399 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
400 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000401 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700402 // Propagate device availability to Engine
403 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200404
Eric Laurent0dd51852019-04-19 18:18:58 -0700405 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700406 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
407
Eric Laurent0dd51852019-04-19 18:18:58 -0700408 mAvailableInputDevices.remove(device);
409
jiabinc0048632023-04-27 22:04:31 +0000410 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100411
412 mHwModules.cleanUpForDevice(device);
413
Eric Laurentd4692962014-05-05 18:13:44 -0700414 return INVALID_OPERATION;
415 }
416
Eric Laurentd4692962014-05-05 18:13:44 -0700417 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700418
419 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700420 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700421 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return INVALID_OPERATION;
424 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700425
François Gaffie11d30102018-11-02 16:09:09 +0100426 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700427
jiabinc0048632023-04-27 22:04:31 +0000428 // Notify the HAL to prepare to disconnect device
429 broadcastDeviceConnectionState(
430 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700431
François Gaffie11d30102018-11-02 16:09:09 +0100432 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700433
434 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100435
jiabinc0048632023-04-27 22:04:31 +0000436 // Set Disconnect to HALs
437 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
438
Kriti Dangef6be8f2020-11-05 11:58:19 +0100439 // remove device from mReportedFormatsMap cache
440 mReportedFormatsMap.erase(device);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700441
442 // Propagate device availability to Engine
443 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700444 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700445
446 default:
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449 }
450
Eric Laurent0dd51852019-04-19 18:18:58 -0700451 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700452 // As the input device list can impact the output device selection, update
453 // getDeviceForStrategy() cache
454 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700455
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100456 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200457 // Reconnect Audio Source
458 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
459 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
460 checkAudioSourceForAttributes(attributes);
461 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700462 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100463 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700464 }
465
Eric Laurentb52c1522014-05-20 11:27:36 -0700466 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530467 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700468 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700469 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700470
François Gaffie11d30102018-11-02 16:09:09 +0100471 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700472 return BAD_VALUE;
473}
474
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100475status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
476 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800477 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000478 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
479 devDescr->setName(device_name);
480 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100481}
482
Eric Laurent736a1022019-03-27 18:28:46 -0700483void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
484 audio_policy_dev_state_t state) {
485
486 // the Engine does not have to know about remote submix devices used by dynamic audio policies
487 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
488 return;
489 }
490 mEngine->setDeviceConnectionState(device, state);
491}
492
493
Eric Laurente0720872014-03-11 09:30:41 -0700494audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100495 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700496{
Eric Laurent634b7142016-04-20 13:48:02 -0700497 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800498 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
499 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700500 (strlen(device_address) != 0)/*matchAddress*/);
501
502 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100503 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700504 device, device_address);
505 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
506 }
François Gaffie53615e22015-03-19 09:24:12 +0100507
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 DeviceVector *deviceVector;
509
Eric Laurente552edb2014-03-10 17:42:56 -0700510 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700511 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700512 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700513 deviceVector = &mAvailableInputDevices;
514 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100515 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700516 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700517 }
Eric Laurent634b7142016-04-20 13:48:02 -0700518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 return (deviceVector->getDevice(
520 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800522}
523
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
525 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 const char *device_name,
527 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
530 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800532 // connect/disconnect only 1 device at a time
533 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
534
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800535 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700536 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538 // Nothing to do: device is not connected
539 return NO_ERROR;
540 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800542
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700543 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 // configure codecs.
545 // Handle two specific cases by sending a set parameter to
546 // configure A2DP codecs. No need to toggle device state.
547 // Case 1: A2DP active device switches from primary to primary
548 // module
549 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100550 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700551 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800552 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
553 if (availablePrimaryOutputDevices().contains(devDesc) &&
554 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100555 bool isA2dp = audio_is_a2dp_out_device(device);
556 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
557 : String8(AudioParameter::keyReconfigLeSupported);
558 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800559 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100560 int isReconfigSupported;
561 repliedParameters.getInt(supportKey, isReconfigSupported);
562 if (isReconfigSupported) {
563 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
564 : String8(AudioParameter::keyReconfigLe);
565 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 param.add(key, String8("true"));
567 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
568 devDesc->setEncodedFormat(encodedFormat);
569 return NO_ERROR;
570 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700571 }
572 }
cnx421bd2dcc42020-07-11 14:58:44 +0800573 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
574 for (size_t i = 0; i < mOutputs.size(); i++) {
575 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
576 // mute media strategies and delay device switch by the largest
577 // This avoid sending the music tail into the earpiece or headset.
578 setStrategyMute(musicStrategy, true, desc);
579 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
580 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
581 nullptr, true /*fromCache*/).types());
582 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800583 // Toggle the device state: UNAVAILABLE -> AVAILABLE
584 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100585 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800586 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800587 device_address, device_name,
588 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800589 if (status != NO_ERROR) {
590 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
591 status);
592 return status;
593 }
594
595 status = setDeviceConnectionState(device,
596 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800597 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800598 if (status != NO_ERROR) {
599 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
600 status);
601 return status;
602 }
603
604 return NO_ERROR;
605}
606
Pattydd807582021-11-04 21:01:03 +0800607status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
608 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800609{
Pattydd807582021-11-04 21:01:03 +0800610 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800611 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800612 std::unordered_set<audio_format_t> formatSet;
613 sp<HwModule> primaryModule =
614 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700615 if (primaryModule == nullptr) {
616 ALOGE("%s() unable to get primary module", __func__);
617 return NO_INIT;
618 }
Pattydd807582021-11-04 21:01:03 +0800619
620 DeviceTypeSet audioDeviceSet;
621
622 switch(device) {
623 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
624 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
625 break;
626 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800627 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
628 break;
629 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
630 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800631 break;
632 default:
633 ALOGE("%s() device type 0x%08x not supported", __func__, device);
634 return BAD_VALUE;
635 }
636
jiabin9a3361e2019-10-01 09:38:30 -0700637 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800638 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800639 for (const auto& device : declaredDevices) {
640 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800641 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800642 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800643 return status;
644}
645
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100646DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
647{
648 DeviceVector rxSinkdevices{};
649 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
650 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
651 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
652 auto rxSinkDevice = rxSinkdevices.itemAt(0);
653 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
654 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
655 // retrieve Rx Source device descriptor
656 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
657 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
658
659 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
660 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
661 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
662 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
663 return DeviceVector(rxSinkDevice);
664 }
665 }
666 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
667 // the device returned is not necessarily reachable via this output
668 // (filter later by setOutputDevices())
669 return getNewOutputDevices(mPrimaryOutput, fromCache);
670}
671
672status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
673{
François Gaffiedb1755b2023-09-01 11:50:35 +0200674 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100675 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
676 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
677 }
678 return INVALID_OPERATION;
679}
680
681status_t AudioPolicyManager::updateCallRoutingInternal(
682 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700683{
684 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100685 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700686 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200687 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700688 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100689 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700690 }
François Gaffie11d30102018-11-02 16:09:09 +0100691
Francois Gaffie716e1432019-01-14 16:58:59 +0100692 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100693 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200694
695 disconnectTelephonyAudioSource(mCallRxSourceClient);
696 disconnectTelephonyAudioSource(mCallTxSourceClient);
697
698 if (rxDevices.isEmpty()) {
699 ALOGW("%s() no selected output device", __func__);
700 return INVALID_OPERATION;
701 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000702 if (txSourceDevice == nullptr) {
703 ALOGE("%s() selected input device not available", __func__);
704 return INVALID_OPERATION;
705 }
François Gaffiec005e562018-11-06 15:04:49 +0100706
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100707 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100708 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700709
François Gaffie9eb18552018-11-05 10:33:26 +0100710 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700711 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100712 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700713 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100714 // retrieve Rx Source and Tx Sink device descriptors
715 sp<DeviceDescriptor> rxSourceDevice =
716 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
717 String8(),
718 AUDIO_FORMAT_DEFAULT);
719 sp<DeviceDescriptor> txSinkDevice =
720 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
721 String8(),
722 AUDIO_FORMAT_DEFAULT);
723
724 // RX and TX Telephony device are declared by Primary Audio HAL
725 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
726 (telephonyRxModule->getHalVersionMajor() >= 3)) {
727 if (rxSourceDevice == 0 || txSinkDevice == 0) {
728 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100729 ALOGE("%s() no telephony Tx and/or RX device", __func__);
730 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100731 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100732 // createAudioPatchInternal now supports both HW / SW bridging
733 createRxPatch = true;
734 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100735 } else {
736 // If the RX device is on the primary HW module, then use legacy routing method for
737 // voice calls via setOutputDevice() on primary output.
738 // Otherwise, create two audio patches for TX and RX path.
739 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
740 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741 // If the TX device is also on the primary HW module, setOutputDevice() will take care
742 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100743 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
744 (txSinkDevice != 0);
745 }
746 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
747 // Otherwise, create two audio patches for TX and RX path.
748 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200749 if (!hasPrimaryOutput()) {
750 ALOGW("%s() no primary output available", __func__);
751 return INVALID_OPERATION;
752 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530753 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700754 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200755 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800756 // If the TX device is on the primary HW module but RX device is
757 // on other HW module, SinkMetaData of telephony input should handle it
758 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700759 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700760 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100761 // terminate active capture if on the same HW module as the call TX source device
762 // FIXME: would be better to refine to only inputs whose profile connects to the
763 // call TX device but this information is not in the audio patch and logic here must be
764 // symmetric to the one in startInput()
765 for (const auto& activeDesc : mInputs.getActiveInputs()) {
766 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
767 closeActiveClients(activeDesc);
768 }
769 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200770 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800771 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100772 if (waitMs != nullptr) {
773 *waitMs = muteWaitMs;
774 }
775 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800776}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700777
Mikhail Naganov100f0122018-11-29 11:22:16 -0800778bool AudioPolicyManager::isDeviceOfModule(
779 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
780 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
781 if (module != 0) {
782 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
783 .indexOf(devDesc) != NAME_NOT_FOUND
784 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
785 .indexOf(devDesc) != NAME_NOT_FOUND;
786 }
787 return false;
788}
789
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200790void AudioPolicyManager::connectTelephonyRxAudioSource()
791{
Francois Gaffie601801d2021-06-22 13:27:39 +0200792 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200793 const struct audio_port_config source = {
794 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
795 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
796 };
797 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100798
799 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
800 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
801 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
802 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200803 ALOGE_IF(mCallRxSourceClient == nullptr,
804 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200805}
806
Francois Gaffie601801d2021-06-22 13:27:39 +0200807void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200808{
Francois Gaffie601801d2021-06-22 13:27:39 +0200809 if (clientDesc == nullptr) {
810 return;
811 }
812 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
813 "%s error stopping audio source", __func__);
814 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200815}
816
817void AudioPolicyManager::connectTelephonyTxAudioSource(
818 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
819 uint32_t delayMs)
820{
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200822 if (srcDevice == nullptr || sinkDevice == nullptr) {
823 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
824 return;
825 }
826 PatchBuilder patchBuilder;
827 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
828 ALOGV("%s between source %s and sink %s", __func__,
829 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200830 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200831 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
832
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200833 struct audio_port_config source = {};
834 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100835 mCallTxSourceClient = new SourceClientDescriptor(
836 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
837 mCommunnicationStrategy, toVolumeSource(aa), true);
838 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
839
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200840 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
841 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200842 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
843 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200844 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
845 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200846 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200847 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200848}
849
Eric Laurente0720872014-03-11 09:30:41 -0700850void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700851{
852 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100853 // store previous phone state for management of sonification strategy below
854 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100855 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100856
857 if (mEngine->setPhoneState(state) != NO_ERROR) {
858 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700859 return;
860 }
François Gaffie2110e042015-03-24 08:41:51 +0100861 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700862 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700863 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700864 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800865 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700866 }
867
François Gaffie2110e042015-03-24 08:41:51 +0100868 /**
869 * Switching to or from incall state or switching between telephony and VoIP lead to force
870 * routing command.
871 */
Eric Laurent74b71512019-11-06 17:21:57 -0800872 bool force = ((isStateInCall(oldState) != isStateInCall(state))
873 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700874
875 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700876 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700877
Eric Laurente552edb2014-03-10 17:42:56 -0700878 int delayMs = 0;
879 if (isStateInCall(state)) {
880 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100881 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
882 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700883 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700884 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700885 // mute media and sonification strategies and delay device switch by the largest
886 // latency of any output where either strategy is active.
887 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100888 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
889 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
890 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700891 (delayMs < (int)desc->latency()*2)) {
892 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700893 }
François Gaffiec005e562018-11-06 15:04:49 +0100894 setStrategyMute(musicStrategy, true, desc);
895 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
896 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
897 nullptr, true /*fromCache*/).types());
898 setStrategyMute(sonificationStrategy, true, desc);
899 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
900 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
901 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700902 }
903 }
904
François Gaffiedb1755b2023-09-01 11:50:35 +0200905 if (state == AUDIO_MODE_IN_CALL) {
906 (void)updateCallRouting(false /*fromCache*/, delayMs);
907 } else {
908 if (oldState == AUDIO_MODE_IN_CALL) {
909 disconnectTelephonyAudioSource(mCallRxSourceClient);
910 disconnectTelephonyAudioSource(mCallTxSourceClient);
911 }
912 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100913 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
914 // force routing command to audio hardware when ending call
915 // even if no device change is needed
916 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
917 rxDevices = mPrimaryOutput->devices();
918 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530919 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700920 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700921 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700922
jiabin3ff8d7d2022-12-13 06:27:44 +0000923 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700924 // reevaluate routing on all outputs in case tracks have been started during the call
925 for (size_t i = 0; i < mOutputs.size(); i++) {
926 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100927 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200928 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
929 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000930 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
931 // If the device is using preferred mixer attributes, the output need to reopen
932 // with default configuration when the new selected devices are different from
933 // current routing devices.
934 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
935 continue;
936 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530937 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200938 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700939 }
940 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000941 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700942
Eric Laurent96d1dda2022-03-14 17:14:19 +0100943 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
944
Eric Laurente552edb2014-03-10 17:42:56 -0700945 if (isStateInCall(state)) {
946 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700947 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800948 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700949 }
950
951 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100952 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
953 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700954}
955
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700956audio_mode_t AudioPolicyManager::getPhoneState() {
957 return mEngine->getPhoneState();
958}
959
Eric Laurente0720872014-03-11 09:30:41 -0700960void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100961 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700962{
François Gaffie2110e042015-03-24 08:41:51 +0100963 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700964 if (config == mEngine->getForceUse(usage)) {
965 return;
966 }
Eric Laurente552edb2014-03-10 17:42:56 -0700967
François Gaffie2110e042015-03-24 08:41:51 +0100968 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
969 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
970 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700971 }
François Gaffie2110e042015-03-24 08:41:51 +0100972 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
973 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
974 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700975
976 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700977 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800978
Eric Laurent22fcda22019-05-17 16:28:47 -0700979 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
980 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800981 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700982 }
983
Eric Laurentdc462862016-07-19 12:29:53 -0700984 //FIXME: workaround for truncated touch sounds
985 // to be removed when the problem is handled by system UI
986 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700987 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
988 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
989 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700990
991 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100992 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700993}
994
Eric Laurente0720872014-03-11 09:30:41 -0700995void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700996{
997 ALOGV("setSystemProperty() property %s, value %s", property, value);
998}
999
Dorin Drimusecc9f422022-03-09 17:57:40 +01001000// Find an MSD output profile compatible with the parameters passed.
1001// When "directOnly" is set, restrict search to profiles for direct outputs.
1002sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1003 const DeviceVector& devices,
1004 uint32_t samplingRate,
1005 audio_format_t format,
1006 audio_channel_mask_t channelMask,
1007 audio_output_flags_t flags,
1008 bool directOnly)
1009{
1010 flags = getRelevantFlags(flags, directOnly);
1011
1012 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1013 if (msdModule != nullptr) {
1014 // for the msd module check if there are patches to the output devices
1015 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1016 HwModuleCollection modules;
1017 modules.add(msdModule);
1018 return searchCompatibleProfileHwModules(
1019 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1020 flags, directOnly);
1021 }
1022 }
1023 return nullptr;
1024}
1025
Michael Chana94fbb22018-04-24 14:31:19 +10001026// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1027// search to profiles for direct outputs.
1028sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001029 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001030 uint32_t samplingRate,
1031 audio_format_t format,
1032 audio_channel_mask_t channelMask,
1033 audio_output_flags_t flags,
1034 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001035{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 flags = getRelevantFlags(flags, directOnly);
1037
1038 return searchCompatibleProfileHwModules(
1039 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1040}
1041
1042audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1043 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001044 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 // only retain flags that will drive the direct output profile selection
1046 // if explicitly requested
1047 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001048 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001049 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1050 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001051 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001052 return flags;
1053}
Eric Laurent861a6282015-05-18 15:40:16 -07001054
Dorin Drimusecc9f422022-03-09 17:57:40 +01001055sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1056 const HwModuleCollection& hwModules,
1057 const DeviceVector& devices,
1058 uint32_t samplingRate,
1059 audio_format_t format,
1060 audio_channel_mask_t channelMask,
1061 audio_output_flags_t flags,
1062 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001063 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001064 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001065 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001066 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 samplingRate, NULL /*updatedSamplingRate*/,
1068 format, NULL /*updatedFormat*/,
1069 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001070 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001071 continue;
1072 }
1073 // reject profiles not corresponding to a device currently available
1074 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1075 continue;
1076 }
1077 // reject profiles if connected device does not support codec
1078 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1079 continue;
1080 }
1081 if (!directOnly) {
1082 return curProfile;
1083 }
1084
1085 // when searching for direct outputs, if several profiles are compatible, give priority
1086 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001087 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001088 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001089 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001090 }
1091 profile = curProfile;
1092 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1093 break;
1094 }
Eric Laurente552edb2014-03-10 17:42:56 -07001095 }
1096 }
Eric Laurent861a6282015-05-18 15:40:16 -07001097 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001098}
1099
Eric Laurentfa0f6742021-08-17 18:39:44 +02001100sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001101 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001102{
1103 for (const auto& hwModule : mHwModules) {
1104 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001105 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001106 continue;
1107 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001108 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001109 // reject profiles not corresponding to a device currently available
1110 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1111 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1112 continue;
1113 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001114 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1115 != devices.size()) {
1116 continue;
1117 }
1118 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001119 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1120 return curProfile;
1121 }
1122 }
1123 return nullptr;
1124}
1125
Eric Laurentf4e63452017-11-06 19:31:46 +00001126audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001127{
François Gaffiec005e562018-11-06 15:04:49 +01001128 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001129
1130 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1131 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1132 // format, flags, etc. This may result in some discrepancy for functions that utilize
1133 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1134 // and AudioSystem::getOutputSamplingRate().
1135
François Gaffie11d30102018-11-02 16:09:09 +01001136 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001137 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1138 if (stream == AUDIO_STREAM_MUSIC &&
1139 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1140 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1141 }
1142 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001143
François Gaffie11d30102018-11-02 16:09:09 +01001144 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1145 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001146 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001147}
1148
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1150 const audio_attributes_t *srcAttr,
1151 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001152{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001153 if (srcAttr != NULL) {
1154 if (!isValidAttributes(srcAttr)) {
1155 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1156 __func__,
1157 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1158 srcAttr->tags);
1159 return BAD_VALUE;
1160 }
1161 *dstAttr = *srcAttr;
1162 } else {
1163 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1164 ALOGE("%s: invalid stream type", __func__);
1165 return BAD_VALUE;
1166 }
François Gaffiec005e562018-11-06 15:04:49 +01001167 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001168 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001169
1170 // Only honor audibility enforced when required. The client will be
1171 // forced to reconnect if the forced usage changes.
1172 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001173 dstAttr->flags = static_cast<audio_flags_mask_t>(
1174 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001175 }
1176
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001177 return NO_ERROR;
1178}
1179
Kevin Rocard153f92d2018-12-18 18:33:28 -08001180status_t AudioPolicyManager::getOutputForAttrInt(
1181 audio_attributes_t *resultAttr,
1182 audio_io_handle_t *output,
1183 audio_session_t session,
1184 const audio_attributes_t *attr,
1185 audio_stream_type_t *stream,
1186 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001187 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001188 audio_output_flags_t *flags,
1189 audio_port_handle_t *selectedDeviceId,
1190 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001191 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001192 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001193 bool *isSpatialized,
1194 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001195{
François Gaffiec005e562018-11-06 15:04:49 +01001196 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001197 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001198 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001199 const sp<DeviceDescriptor> requestedDevice =
1200 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1201
Eric Laurent8a1095a2019-11-08 14:44:16 -08001202 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001203 *isSpatialized = false;
1204
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001205 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1206 if (status != NO_ERROR) {
1207 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001208 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001209 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001210 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001211 }
François Gaffiec005e562018-11-06 15:04:49 +01001212 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001213
François Gaffiec005e562018-11-06 15:04:49 +01001214 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1215 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001216
Oscar Azucena873d10f2023-01-12 18:34:42 -08001217 bool usePrimaryOutputFromPolicyMixes = false;
1218
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1220 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1221 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001222 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001223 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1224 .channel_mask = config->channel_mask,
1225 .format = config->format,
1226 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001227 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001228 mAvailableOutputDevices, requestedDevice, primaryMix,
1229 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001230 if (status != OK) {
1231 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001232 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001233
Kevin Rocard153f92d2018-12-18 18:33:28 -08001234 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001235 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1236 && !audio_is_linear_pcm(config->format)) {
1237 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001238 return BAD_VALUE;
1239 }
1240 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001241 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001242 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1243 primaryMix->mDeviceAddress,
1244 AUDIO_FORMAT_DEFAULT);
1245 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001246 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001247 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1248 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001249 // if a direct output can be opened to deliver the track's multi-channel content to the
1250 // output rather than being downmixed by the primary output, then use this direct
1251 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1252 // mix.
1253 bool tryDirectForChannelMask = policyDesc != nullptr
1254 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1255 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001256 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001257 audio_io_handle_t newOutput;
1258 status = openDirectOutput(
1259 *stream, session, config,
1260 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001261 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001262 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001263 policyDesc = mOutputs.valueFor(newOutput);
1264 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001265 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001266 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001267 policyDesc = nullptr;
1268 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001269 }
1270 if (policyDesc != nullptr) {
1271 policyDesc->mPolicyMix = primaryMix;
1272 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001273 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1274 : AUDIO_PORT_HANDLE_NONE;
1275 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1276 // Remove direct flag as it is not on a direct output.
1277 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1278 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001279
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001280 ALOGV("getOutputForAttr() returns output %d", *output);
1281 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1282 *outputType = API_OUT_MIX_PLAYBACK;
1283 } else {
1284 *outputType = API_OUTPUT_LEGACY;
1285 }
1286 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001287 } else {
1288 if (policyMixDevice != nullptr) {
1289 ALOGE("%s, try to use primary mix but no output found", __func__);
1290 return INVALID_OPERATION;
1291 }
1292 // Fallback to default engine selection as the selected primary mix device is not
1293 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001294 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001295 }
François Gaffiec005e562018-11-06 15:04:49 +01001296 // Virtual sources must always be dynamicaly or explicitly routed
1297 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1298 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1299 return BAD_VALUE;
1300 }
1301 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1302 // in order to let the choice of the order to future vendor engine
1303 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001304
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001305 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001306 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001307 }
1308
Nadav Barb2f18162018-07-18 13:01:53 +03001309 // Set incall music only if device was explicitly set, and fallback to the device which is
1310 // chosen by the engine if not.
1311 // FIXME: provide a more generic approach which is not device specific and move this back
1312 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001313 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001314 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001315 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001316 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001317 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001318 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001319 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001320 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001321 }
1322 }
1323
François Gaffiec005e562018-11-06 15:04:49 +01001324 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1325 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1326 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001327
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001328 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001329 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001330 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001331 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001332 ALOGV("%s() Using MSD devices %s instead of devices %s",
1333 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001334 } else {
1335 *output = AUDIO_IO_HANDLE_NONE;
1336 }
1337 }
1338 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001339 sp<PreferredMixerAttributesInfo> info = nullptr;
1340 if (outputDevices.size() == 1) {
1341 info = getPreferredMixerAttributesInfo(
1342 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001343 mEngine->getProductStrategyForAttributes(*resultAttr),
1344 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001345 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1346 // and it is currently active.
1347 if (info != nullptr && info->getUid() != uid &&
1348 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1349 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001350 info = nullptr;
1351 }
1352 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001353 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001354 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001355 // The client will be active if the client is currently preferred mixer owner and the
1356 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001357 *isBitPerfect = (info != nullptr
1358 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001359 && info->getUid() == uid
1360 && *output != AUDIO_IO_HANDLE_NONE
1361 // When bit-perfect output is selected for the preferred mixer attributes owner,
1362 // only need to consider the config matches.
1363 && mOutputs.valueFor(*output)->isConfigurationMatched(
1364 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001365 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001366 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001367 AudioProfileVector profiles;
1368 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1369 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001370 const auto channels = profiles[0]->getChannels();
1371 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1372 config->channel_mask = *channels.begin();
1373 }
1374 const auto sampleRates = profiles[0]->getSampleRates();
1375 if (!sampleRates.empty() &&
1376 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1377 config->sample_rate = *sampleRates.begin();
1378 }
jiabinf1c73972022-04-14 16:28:52 -07001379 config->format = profiles[0]->getFormat();
1380 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001381 return INVALID_OPERATION;
1382 }
Paul McLeanaa981192015-03-21 09:55:15 -07001383
François Gaffiec005e562018-11-06 15:04:49 +01001384 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001385 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001386 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001387 *selectedDeviceId = outputDevice->getId();
1388 break;
1389 }
1390 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001391
Eric Laurent8a1095a2019-11-08 14:44:16 -08001392 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1393 *outputType = API_OUTPUT_TELEPHONY_TX;
1394 } else {
1395 *outputType = API_OUTPUT_LEGACY;
1396 }
1397
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001398 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1399
1400 return NO_ERROR;
1401}
1402
1403status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1404 audio_io_handle_t *output,
1405 audio_session_t session,
1406 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001407 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001408 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001409 audio_output_flags_t *flags,
1410 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001411 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001412 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001413 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001414 bool *isSpatialized,
1415 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001416{
1417 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1418 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1419 return INVALID_OPERATION;
1420 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001421 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001422 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001423 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001424 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001425 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001426 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001427 const sp<DeviceDescriptor> requestedDevice =
1428 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1429
1430 // Prevent from storing invalid requested device id in clients
1431 const audio_port_handle_t sanitizedRequestedPortId =
1432 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1433 *selectedDeviceId = sanitizedRequestedPortId;
1434
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001435 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001436 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001437 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1438 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001439 if (status != NO_ERROR) {
1440 return status;
1441 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001442 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001443 if (secondaryOutputs != nullptr) {
1444 for (auto &secondaryMix : secondaryMixes) {
1445 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1446 if (outputDesc != nullptr &&
1447 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1448 secondaryOutputs->push_back(outputDesc->mIoHandle);
1449 weakSecondaryOutputDescs.push_back(outputDesc);
1450 }
1451 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001452 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001453
Eric Laurent8fc147b2018-07-22 19:13:55 -07001454 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001455 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001456 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001457 };
jiabin4ef93452019-09-10 14:29:54 -07001458 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001459
Eric Laurentc209fe42020-06-05 18:11:23 -07001460 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001461 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001462 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001463 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001464 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001465 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001466 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001467 std::move(weakSecondaryOutputDescs),
1468 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001469 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001470
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001471 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1472 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001473
Eric Laurente83b55d2014-11-14 10:06:21 -08001474 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001475}
1476
Eric Laurentc529cf62020-04-17 18:19:10 -07001477status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1478 audio_session_t session,
1479 const audio_config_t *config,
1480 audio_output_flags_t flags,
1481 const DeviceVector &devices,
1482 audio_io_handle_t *output) {
1483
1484 *output = AUDIO_IO_HANDLE_NONE;
1485
1486 // skip direct output selection if the request can obviously be attached to a mixed output
1487 // and not explicitly requested
1488 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1489 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1490 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1491 return NAME_NOT_FOUND;
1492 }
1493
1494 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1495 // This prevents creating an offloaded track and tearing it down immediately after start
1496 // when audioflinger detects there is an active non offloadable effect.
1497 // FIXME: We should check the audio session here but we do not have it in this context.
1498 // This may prevent offloading in rare situations where effects are left active by apps
1499 // in the background.
1500 sp<IOProfile> profile;
1501 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1502 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1503 profile = getProfileForOutput(
1504 devices, config->sample_rate, config->format, config->channel_mask,
1505 flags, true /* directOnly */);
1506 }
1507
1508 if (profile == nullptr) {
1509 return NAME_NOT_FOUND;
1510 }
1511
1512 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1513 for (size_t i = 0; i < mOutputs.size(); i++) {
1514 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1515 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1516 // reuse direct output if currently open by the same client
1517 // and configured with same parameters
1518 if ((config->sample_rate == desc->getSamplingRate()) &&
1519 (config->format == desc->getFormat()) &&
1520 (config->channel_mask == desc->getChannelMask()) &&
1521 (session == desc->mDirectClientSession)) {
1522 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301523 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001524 mOutputs.keyAt(i), session);
1525 *output = mOutputs.keyAt(i);
1526 return NO_ERROR;
1527 }
1528 }
1529 }
1530
1531 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001532 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301533 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1534 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001535 return NAME_NOT_FOUND;
1536 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1537 // MMAP gracefully handles lack of an exclusive track resource by mixing
1538 // above the audio framework. For AAudio to know that the limit is reached,
1539 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301540 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1541 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001542 return NAME_NOT_FOUND;
1543 } else {
1544 // Close outputs on this profile, if available, to free resources for this request
1545 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1546 const auto desc = mOutputs.valueAt(i);
1547 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301548 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1549 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001550 closeOutput(desc->mIoHandle);
1551 }
1552 }
1553 }
1554 }
1555
1556 // Unable to close streams to find free resources for this request
1557 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301558 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1559 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001560 return NAME_NOT_FOUND;
1561 }
1562
Atneya Nairb16666a2023-12-11 20:18:33 -08001563 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001564
Michael Chan6fb34492020-12-08 15:44:49 +11001565 // An MSD patch may be using the only output stream that can service this request. Release
1566 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001567 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001568
Eric Laurentf1f22e72021-07-13 14:04:14 +02001569 status_t status =
1570 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001571
1572 // only accept an output with the requested parameters
1573 if (status != NO_ERROR ||
1574 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1575 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1576 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1577 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1578 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1579 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1580 config->channel_mask, outputDesc->getChannelMask());
1581 if (*output != AUDIO_IO_HANDLE_NONE) {
1582 outputDesc->close();
1583 }
1584 // fall back to mixer output if possible when the direct output could not be open
1585 if (audio_is_linear_pcm(config->format) &&
1586 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1587 return NAME_NOT_FOUND;
1588 }
1589 *output = AUDIO_IO_HANDLE_NONE;
1590 return BAD_VALUE;
1591 }
1592 outputDesc->mDirectOpenCount = 1;
1593 outputDesc->mDirectClientSession = session;
1594
1595 addOutput(*output, outputDesc);
1596 mPreviousOutputs = mOutputs;
1597 ALOGV("%s returns new direct output %d", __func__, *output);
1598 mpClientInterface->onAudioPortListUpdate();
1599 return NO_ERROR;
1600}
1601
François Gaffie11d30102018-11-02 16:09:09 +01001602audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1603 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001604 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001605 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001606 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001607 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001608 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001609 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001610 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001611{
Andy Hungc88b0642018-04-27 15:42:35 -07001612 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001613
jiabine375d412019-02-26 12:54:53 -08001614 // Discard haptic channel mask when forcing muting haptic channels.
1615 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001616 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1617 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001618
Eric Laurente552edb2014-03-10 17:42:56 -07001619 // open a direct output if required by specified parameters
1620 //force direct flag if offload flag is set: offloading implies a direct output stream
1621 // and all common behaviors are driven by checking only the direct flag
1622 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001623 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1624 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001625 }
Nadav Bar766fb022018-01-07 12:18:03 +02001626 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1627 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001628 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001629
1630 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1631
Eric Laurente83b55d2014-11-14 10:06:21 -08001632 // only allow deep buffering for music stream type
1633 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001634 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001635 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001636 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001637 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1638 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001639 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001640 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001641 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001642 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001643 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001644 audio_is_linear_pcm(config->format) &&
1645 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001646 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001647 AUDIO_OUTPUT_FLAG_DIRECT);
1648 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001649 }
Eric Laurente552edb2014-03-10 17:42:56 -07001650
Carter Hsua3abb402021-10-26 11:11:20 +08001651 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1652 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1653 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1654 }
1655
Eric Laurentf9230d52024-01-26 18:49:09 +01001656 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001657 // was specified and offload or direct playback is not explicitly requested, and there is no
1658 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001659 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001660 if (mSpatializerOutput != nullptr &&
1661 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1662 prefMixerConfigInfo == nullptr &&
1663 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1664 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001665 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001666 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001667 }
1668
Eric Laurentc529cf62020-04-17 18:19:10 -07001669 audio_config_t directConfig = *config;
1670 directConfig.channel_mask = channelMask;
1671 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1672 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001673 return output;
1674 }
1675
Eric Laurent14cbfca2016-03-17 09:42:16 -07001676 // A request for HW A/V sync cannot fallback to a mixed output because time
1677 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001678 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001679 return AUDIO_IO_HANDLE_NONE;
1680 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001681 // A request for Tuner cannot fallback to a mixed output
1682 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1683 return AUDIO_IO_HANDLE_NONE;
1684 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001685
Eric Laurente552edb2014-03-10 17:42:56 -07001686 // ignoring channel mask due to downmix capability in mixer
1687
1688 // open a non direct output
1689
1690 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001691 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001692 // get which output is suitable for the specified stream. The actual
1693 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001694 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001695 if (prefMixerConfigInfo != nullptr) {
1696 for (audio_io_handle_t outputHandle : outputs) {
1697 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1698 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1699 output = outputHandle;
1700 break;
1701 }
1702 }
1703 if (output == AUDIO_IO_HANDLE_NONE) {
1704 // No output open with the preferred profile. Open a new one.
1705 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1706 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1707 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1708 config.format = prefMixerConfigInfo->getConfigBase().format;
1709 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1710 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1711 &config, prefMixerConfigInfo->getFlags());
1712 if (preferredOutput == nullptr) {
1713 ALOGE("%s failed to open output with preferred mixer config", __func__);
1714 } else {
1715 output = preferredOutput->mIoHandle;
1716 }
1717 }
1718 } else {
1719 // at this stage we should ignore the DIRECT flag as no direct output could be
1720 // found earlier
1721 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1722 output = selectOutput(
1723 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1724 }
Eric Laurente552edb2014-03-10 17:42:56 -07001725 }
François Gaffie11d30102018-11-02 16:09:09 +01001726 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001727 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001728 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001729
Eric Laurente552edb2014-03-10 17:42:56 -07001730 return output;
1731}
1732
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001733sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001734 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1735 mAvailableInputDevices);
1736 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1737}
1738
1739DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1740 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1741 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742}
1743
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001745 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001746 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1747 if (msdModule != 0) {
1748 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1749 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1750 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1751 const struct audio_port_config *source = &patch->mPatch.sources[j];
1752 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1753 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001754 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001755 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001756 }
1757 }
1758 }
1759 return msdPatches;
1760}
1761
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001762bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1763 ssize_t index = mAudioPatches.indexOfKey(handle);
1764 if (index < 0) {
1765 return false;
1766 }
1767 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1768 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1769 if (msdModule == nullptr) {
1770 return false;
1771 }
1772 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1773 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1774 return true;
1775 }
1776 index = getMsdOutputPatches().indexOfKey(handle);
1777 if (index < 0) {
1778 return false;
1779 }
1780 return true;
1781}
1782
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001783status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1784 const InputProfileCollection &inputProfiles,
1785 const OutputProfileCollection &outputProfiles,
1786 const sp<DeviceDescriptor> &sourceDevice,
1787 const sp<DeviceDescriptor> &sinkDevice,
1788 AudioProfileVector& sourceProfiles,
1789 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001791 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001792 return NO_INIT;
1793 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001794 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001795 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001796 return NO_INIT;
1797 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001798 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001799 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1800 inProfile->supportsDevice(sourceDevice)) {
1801 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001802 }
1803 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001804 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001805 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001806 outProfile->supportsDevice(sinkDevice)) {
1807 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001808 }
1809 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001810 return NO_ERROR;
1811}
1812
1813status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1814 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1815 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1816{
Dean Wheatley16809da2022-12-09 14:55:46 +11001817 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1818 static const std::vector<audio_format_t> formatsOrder = {{
1819 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001820 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1821 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001822 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1823 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1824 // preferred).
1825 std::vector<audio_channel_mask_t> masks = {{
1826 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1827 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1828 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1829 // insert index masks (higher counts most preferred) as preferred over position masks
1830 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1831 masks.insert(
1832 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1833 }
1834 return masks;
1835 }();
1836
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001837 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001838 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1839 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001841 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1842 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001843 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 }
1845 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1846 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1847 sinkConfig->format = bestSinkConfig.format;
1848 // For encoded streams force direct flag to prevent downstream mixing.
1849 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1850 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001851 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1852 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001854 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1855 // raw and IEC61937 framed streams.
1856 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1857 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1858 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001859 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1860 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001861 sourceConfig->channel_mask =
1862 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1863 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1864 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001865 sourceConfig->format = bestSinkConfig.format;
1866 // Copy input stream directly without any processing (e.g. resampling).
1867 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1868 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1869 if (hwAvSync) {
1870 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1871 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1872 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1873 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1874 }
1875 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1876 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1877 sinkConfig->config_mask |= config_mask;
1878 sourceConfig->config_mask |= config_mask;
1879 return NO_ERROR;
1880}
1881
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1883 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884{
1885 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1887 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1888 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1889 if (deviceModule == nullptr) {
1890 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1891 return patchBuilder;
1892 }
1893 const InputProfileCollection inputProfiles = msdIsSource ?
1894 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1895 const OutputProfileCollection outputProfiles = msdIsSource ?
1896 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1897
1898 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1899 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1900 device : getMsdAudioOutDevices().itemAt(0);
1901 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1902
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1904 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001905 AudioProfileVector sourceProfiles;
1906 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1908 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001909 for (auto hwAvSync : { true, false }) {
1910 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1911 sourceProfiles, sinkProfiles) != NO_ERROR) {
1912 continue;
1913 }
1914 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1915 &sinkConfig) == NO_ERROR) {
1916 // Found a matching config. Re-create PatchBuilder with this config.
1917 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1918 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001919 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001920 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001921 " supporting PCM format conversion.", __func__);
1922 return patchBuilder;
1923}
1924
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001925status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001926 DeviceVector devices;
1927 if (outputDevices != nullptr && outputDevices->size() > 0) {
1928 devices.add(*outputDevices);
1929 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001930 // Use media strategy for unspecified output device. This should only
1931 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1932 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001933 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001934 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001935 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001936 }
Michael Chan6fb34492020-12-08 15:44:49 +11001937 std::vector<PatchBuilder> patchesToCreate;
1938 for (auto i = 0u; i < devices.size(); ++i) {
1939 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001940 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001941 }
1942 // Retain only the MSD patches associated with outputDevices request.
1943 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001944 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001945 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1946 auto retainedPatch = false;
1947 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1948 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1949 patchesToRemove.removeItemsAt(i);
1950 retainedPatch = true;
1951 break;
1952 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001953 }
Michael Chan6fb34492020-12-08 15:44:49 +11001954 if (retainedPatch) {
1955 it = patchesToCreate.erase(it);
1956 continue;
1957 }
1958 ++it;
1959 }
1960 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1961 return NO_ERROR;
1962 }
1963 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1964 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001965 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001966 }
Michael Chan6fb34492020-12-08 15:44:49 +11001967 status_t status = NO_ERROR;
1968 for (const auto &p : patchesToCreate) {
1969 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1970 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1971 char message[256];
1972 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1973 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1974 currStatus == NO_ERROR ? "Success" : "Error",
1975 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1976 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1977 if (currStatus == NO_ERROR) {
1978 ALOGD("%s", message);
1979 } else {
1980 ALOGE("%s", message);
1981 if (status == NO_ERROR) {
1982 status = currStatus;
1983 }
1984 }
1985 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001986 return status;
1987}
1988
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001989void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1990 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001991 for (size_t i = 0; i < msdPatches.size(); i++) {
1992 const auto& patch = msdPatches[i];
1993 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1994 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1995 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1996 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1997 releaseAudioPatch(patch->getHandle(), mUidCached);
1998 break;
1999 }
2000 }
2001 }
2002}
2003
Dorin Drimus94d94412022-02-02 09:05:02 +01002004bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002005 DeviceVector devicesToCheck =
2006 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002007 AudioPatchCollection msdPatches = getMsdOutputPatches();
2008 for (size_t i = 0; i < msdPatches.size(); i++) {
2009 const auto& patch = msdPatches[i];
2010 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2011 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2012 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2013 const auto& foundDevice = devicesToCheck.getDevice(
2014 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2015 if (foundDevice != nullptr) {
2016 devicesToCheck.remove(foundDevice);
2017 if (devicesToCheck.isEmpty()) {
2018 return true;
2019 }
2020 }
2021 }
2022 }
2023 }
2024 return false;
2025}
2026
Eric Laurente0720872014-03-11 09:30:41 -07002027audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002028 audio_output_flags_t flags,
2029 audio_format_t format,
2030 audio_channel_mask_t channelMask,
2031 uint32_t samplingRate,
2032 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002033{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002034 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2035 "%s called with format %#x", __func__, format);
2036
jiabinebb6af42020-06-09 17:31:17 -07002037 // Return the output that haptic-generating attached to when 1) session id is specified,
2038 // 2) haptic-generating effect exists for given session id and 3) the output that
2039 // haptic-generating effect attached to is in given outputs.
2040 if (sessionId != AUDIO_SESSION_NONE) {
2041 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2042 sessionId, FX_IID_HAPTICGENERATOR);
2043 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2044 return hapticGeneratingOutput;
2045 }
2046 }
2047
Eric Laurent16c66dd2019-05-01 17:54:10 -07002048 // Flags disqualifying an output: the match must happen before calling selectOutput()
2049 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2050 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2051
2052 // Flags expressing a functional request: must be honored in priority over
2053 // other criteria
2054 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2055 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002056 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2057 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002058 // Flags expressing a performance request: have lower priority than serving
2059 // requested sampling rate or channel mask
2060 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2061 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2062 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2063
2064 const audio_output_flags_t functionalFlags =
2065 (audio_output_flags_t)(flags & kFunctionalFlags);
2066 const audio_output_flags_t performanceFlags =
2067 (audio_output_flags_t)(flags & kPerformanceFlags);
2068
2069 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2070
Eric Laurente552edb2014-03-10 17:42:56 -07002071 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002072 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002073 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002074 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002075 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002076 // with tiebreak preferring the minimum number of extra functional flags
2077 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002078 // 3: the output supporting the exact channel mask
2079 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002080 // 5: the output with the highest sampling rate if the requested sample rate is
2081 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002082 // 6: the output with the highest number of requested performance flags
2083 // 7: the output with the bit depth the closest to the requested one
2084 // 8: the primary output
2085 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002086
Eric Laurent16c66dd2019-05-01 17:54:10 -07002087 // matching criteria values in priority order for best matching output so far
2088 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002089
Shunkai Yao808da212024-04-05 22:50:56 +00002090 const bool hasOrphanHaptic =
2091 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002092 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2093 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2094 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002095
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002096 for (audio_io_handle_t output : outputs) {
2097 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002098 // matching criteria values in priority order for current output
2099 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002100
Eric Laurent16c66dd2019-05-01 17:54:10 -07002101 if (outputDesc->isDuplicated()) {
2102 continue;
2103 }
2104 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2105 continue;
2106 }
Eric Laurent8838a382014-09-08 16:44:28 -07002107
Eric Laurent16c66dd2019-05-01 17:54:10 -07002108 // If haptic channel is specified, use the haptic output if present.
2109 // When using haptic output, same audio format and sample rate are required.
2110 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002111 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002112 // skip if haptic channel specified but output does not support it, or output support haptic
2113 // but there is no haptic channel requested AND no orphan haptic effect exist
2114 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2115 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002116 continue;
2117 }
Shunkai Yao808da212024-04-05 22:50:56 +00002118 // In the case of audio-coupled-haptic playback, there is no format conversion and
2119 // resampling in the framework, same format/channel/sampleRate for client and the output
2120 // thread is required. In the case of HapticGenerator effect, do not require format
2121 // matching.
2122 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2123 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002124 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002125 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002126 }
2127
2128 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002129 const int matchingFunctionalFlags =
2130 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2131 const int totalFunctionalFlags =
2132 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2133 // Prefer matching functional flags, but subtract unnecessary functional flags.
2134 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002135
2136 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002137 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2138 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002139 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2140 channelCount <= outputChannelCount) {
2141 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002142 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2143 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002144 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002145 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002146 currentMatchCriteria[3] = outputChannelCount;
2147 }
2148
2149 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002150 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002151 int diff; // avoid unsigned integer overflow.
2152 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2153
2154 // prefer the closest output sampling rate greater than or equal to target
2155 // if none exists, prefer the closest output sampling rate less than target.
2156 //
2157 // criteria is offset to make non-negative.
2158 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002159 }
2160
2161 // performance flags match
2162 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2163
2164 // format match
2165 if (format != AUDIO_FORMAT_INVALID) {
2166 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002167 PolicyAudioPort::kFormatDistanceMax -
2168 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002169 }
2170
2171 // primary output match
2172 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2173
2174 // compare match criteria by priority then value
2175 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2176 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2177 bestMatchCriteria = currentMatchCriteria;
2178 bestOutput = output;
2179
2180 std::stringstream result;
2181 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2182 std::ostream_iterator<int>(result, " "));
2183 ALOGV("%s new bestOutput %d criteria %s",
2184 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002185 }
2186 }
2187
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002189}
2190
Eric Laurent8fc147b2018-07-22 19:13:55 -07002191status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002192{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002193 ALOGV("%s portId %d", __FUNCTION__, portId);
2194
2195 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2196 if (outputDesc == 0) {
2197 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002198 return BAD_VALUE;
2199 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002200 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002201
Eric Laurent8fc147b2018-07-22 19:13:55 -07002202 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002203 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002204
Eric Laurent733ce942017-12-07 12:18:25 -08002205 status_t status = outputDesc->start();
2206 if (status != NO_ERROR) {
2207 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002208 }
2209
Eric Laurent97ac8712018-07-27 18:59:02 -07002210 uint32_t delayMs;
2211 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002212
2213 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002214 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002215 if (status == DEAD_OBJECT) {
2216 sp<SwAudioOutputDescriptor> desc =
2217 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2218 if (desc == nullptr) {
2219 // This is not common, it may indicate something wrong with the HAL.
2220 ALOGE("%s unable to open output with default config", __func__);
2221 return status;
2222 }
2223 desc->mUsePreferredMixerAttributes = true;
2224 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002225 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002226 }
jiabina84c3d32022-12-02 18:59:55 +00002227
2228 // If the client is the first one active on preferred mixer parameters, reopen the output
2229 // if the current mixer parameters doesn't match the preferred one.
2230 if (outputDesc->devices().size() == 1) {
2231 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2232 outputDesc->devices()[0]->getId(), client->strategy());
2233 if (info != nullptr && info->getUid() == client->uid()) {
2234 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2235 info->getConfigBase(), info->getFlags())) {
2236 stopSource(outputDesc, client);
2237 outputDesc->stop();
2238 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2239 config.channel_mask = info->getConfigBase().channel_mask;
2240 config.sample_rate = info->getConfigBase().sample_rate;
2241 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002242 sp<SwAudioOutputDescriptor> desc =
2243 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2244 if (desc == nullptr) {
2245 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002246 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002247 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002248 // Intentionally return error to let the client side resending request for
2249 // creating and starting.
2250 return DEAD_OBJECT;
2251 }
2252 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002253 if (info->getActiveClientCount() == 1 &&
2254 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2255 // If it is first bit-perfect client, reroute all clients that will be routed to
2256 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2257 PortHandleVector clientsToInvalidate;
2258 for (size_t i = 0; i < mOutputs.size(); i++) {
2259 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002260 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002261 continue;
2262 }
2263 for (const auto& c : mOutputs[i]->getClientIterable()) {
2264 clientsToInvalidate.push_back(c->portId());
2265 }
2266 }
2267 if (!clientsToInvalidate.empty()) {
2268 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2269 __func__);
2270 mpClientInterface->invalidateTracks(clientsToInvalidate);
2271 }
2272 }
jiabina84c3d32022-12-02 18:59:55 +00002273 }
2274 }
2275
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002276 if (client->hasPreferredDevice()) {
2277 // playback activity with preferred device impacts routing occurred, inform upper layers
2278 mpClientInterface->onRoutingUpdated();
2279 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002280 if (delayMs != 0) {
2281 usleep(delayMs * 1000);
2282 }
2283
2284 return status;
2285}
2286
Eric Laurent96d1dda2022-03-14 17:14:19 +01002287bool AudioPolicyManager::isLeUnicastActive() const {
2288 if (isInCall()) {
2289 return true;
2290 }
2291 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2292}
2293
2294bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2295 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2296 return false;
2297 }
2298 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2299 ALOGV("%s active %d", __func__, active);
2300 return active;
2301}
2302
Eric Laurent97ac8712018-07-27 18:59:02 -07002303status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2304 const sp<TrackClientDescriptor>& client,
2305 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002306{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002307 // cannot start playback of STREAM_TTS if any other output is being used
2308 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002309
2310 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002311 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002312 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002313 auto clientStrategy = client->strategy();
2314 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002315 if (stream == AUDIO_STREAM_TTS) {
2316 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002317 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002318 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002319 return INVALID_OPERATION;
2320 } else {
2321 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2322 }
2323 } else {
2324 // some playback other than beacon starts
2325 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2326 }
2327
Eric Laurent77305a62016-07-25 16:39:22 -07002328 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002329 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002330 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002331
François Gaffie11d30102018-11-02 16:09:09 +01002332 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002333 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002334 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002335 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002336 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002337 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002338 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002339 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002340 } else {
2341 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002342 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002343 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2344 AUDIO_FORMAT_DEFAULT);
2345 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2346 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002347 }
2348
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002349 // requiresMuteCheck is false when we can bypass mute strategy.
2350 // It covers a common case when there is no materially active audio
2351 // and muting would result in unnecessary delay and dropped audio.
2352 const uint32_t outputLatencyMs = outputDesc->latency();
2353 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002354 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002355
Eric Laurente552edb2014-03-10 17:42:56 -07002356 // increment usage count for this stream on the requested output:
2357 // NOTE that the usage count is the same for duplicated output and hardware output which is
2358 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002359 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002360
2361 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002362 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002363 // Preferred device may be exclusive, use only if no other active clients on this output
2364 devices = DeviceVector(
2365 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2366 } else {
2367 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2368 }
François Gaffie11d30102018-11-02 16:09:09 +01002369 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002370 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002371 }
2372 }
Eric Laurente552edb2014-03-10 17:42:56 -07002373
François Gaffiec005e562018-11-06 15:04:49 +01002374 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002375 selectOutputForMusicEffects();
2376 }
2377
François Gaffie1c878552018-11-22 16:53:21 +01002378 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002379 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002380 if (devices.isEmpty()) {
2381 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002382 }
François Gaffiec005e562018-11-06 15:04:49 +01002383 bool shouldWait =
2384 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2385 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2386 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002387 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002388 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002389 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002390 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002391 // An output has a shared device if
2392 // - managed by the same hw module
2393 // - supports the currently selected device
2394 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002395 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002396
Eric Laurent77305a62016-07-25 16:39:22 -07002397 // force a device change if any other output is:
2398 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002399 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002400 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002401 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002402 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002403 // change the device currently selected by the other output.
2404 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002405 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002406 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002407 force = true;
2408 }
2409 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002410 // a notification so that audio focus effect can propagate, or that a mute/unmute
2411 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002412 const uint32_t latencyMs = desc->latency();
2413 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2414
2415 if (shouldWait && isActive && (waitMs < latencyMs)) {
2416 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002417 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002418
2419 // Require mute check if another output is on a shared device
2420 // and currently active to have proper drain and avoid pops.
2421 // Note restoring AudioTracks onto this output needs to invoke
2422 // a volume ramp if there is no mute.
2423 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002424 }
2425 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002426
jiabin3ff8d7d2022-12-13 06:27:44 +00002427 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2428 // If the output is open with preferred mixer attributes, but the routed device is
2429 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2430 // changed.
2431 return DEAD_OBJECT;
2432 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002433 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302434 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2435 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002436
Eric Laurente552edb2014-03-10 17:42:56 -07002437 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002438 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002439 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002440 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002441 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002442 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002443 outputDesc->useHwGain() /*force*/)) {
2444 // request AudioService to reinitialize the volume curves asynchronously
2445 ALOGE("checkAndSetVolume failed, requesting volume range init");
2446 mpClientInterface->onVolumeRangeInitRequest();
2447 };
Eric Laurente552edb2014-03-10 17:42:56 -07002448
2449 // update the outputs if starting an output with a stream that can affect notification
2450 // routing
2451 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002452
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002453 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002454 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002455 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002456 }
Eric Laurentdc462862016-07-19 12:29:53 -07002457
2458 if (waitMs > muteWaitMs) {
2459 *delayMs = waitMs - muteWaitMs;
2460 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002461
2462 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2463 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2464 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2465 // change occurs after the MixerThread starts and causes a stream volume
2466 // glitch.
2467 //
2468 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002469 }
Eric Laurentdc462862016-07-19 12:29:53 -07002470
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002471 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002472 mEngine->getForceUse(
2473 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002474 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002475 }
2476
Eric Laurent97ac8712018-07-27 18:59:02 -07002477 // Automatically enable the remote submix input when output is started on a re routing mix
2478 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002479 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2480 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002481 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2482 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2483 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002484 "remote-submix",
2485 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002486 }
2487
Eric Laurent96d1dda2022-03-14 17:14:19 +01002488 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2489
Eric Laurente552edb2014-03-10 17:42:56 -07002490 return NO_ERROR;
2491}
2492
Eric Laurent96d1dda2022-03-14 17:14:19 +01002493void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2494 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2495 bool isUnicastActive = isLeUnicastActive();
2496
2497 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002498 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002499 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2500 for (size_t i = 0; i < mOutputs.size(); i++) {
2501 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2502 if (desc != ignoredOutput && desc->isActive()
2503 && ((isUnicastActive &&
2504 !desc->devices().
2505 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2506 || (wasUnicastActive &&
2507 !desc->devices().getDevicesFromTypes(
2508 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2509 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2510 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002511 if (desc->mUsePreferredMixerAttributes && force) {
2512 // If the device is using preferred mixer attributes, the output need to reopen
2513 // with default configuration when the new selected devices are different from
2514 // current routing devices.
2515 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2516 continue;
2517 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302518 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002519 // re-apply device specific volume if not done by setOutputDevice()
2520 if (!force) {
2521 applyStreamVolumes(desc, newDevices.types(), delayMs);
2522 }
2523 }
2524 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002525 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002526 }
2527}
2528
Eric Laurent8fc147b2018-07-22 19:13:55 -07002529status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002530{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002531 ALOGV("%s portId %d", __FUNCTION__, portId);
2532
2533 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2534 if (outputDesc == 0) {
2535 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002536 return BAD_VALUE;
2537 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002538 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002539
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002540 if (client->hasPreferredDevice(true)) {
2541 // playback activity with preferred device impacts routing occurred, inform upper layers
2542 mpClientInterface->onRoutingUpdated();
2543 }
2544
Eric Laurent97ac8712018-07-27 18:59:02 -07002545 ALOGV("stopOutput() output %d, stream %d, session %d",
2546 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002547
Eric Laurent97ac8712018-07-27 18:59:02 -07002548 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002549
Eric Laurent733ce942017-12-07 12:18:25 -08002550 if (status == NO_ERROR ) {
2551 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002552 } else {
2553 return status;
2554 }
2555
2556 if (outputDesc->devices().size() == 1) {
2557 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2558 outputDesc->devices()[0]->getId(), client->strategy());
2559 if (info != nullptr && info->getUid() == client->uid()) {
2560 info->decreaseActiveClient();
2561 if (info->getActiveClientCount() == 0) {
2562 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2563 }
2564 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002565 }
2566 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002567}
2568
Eric Laurent97ac8712018-07-27 18:59:02 -07002569status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2570 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002571{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002572 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002573 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002574 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002575 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002576
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002577 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2578
François Gaffie1c878552018-11-22 16:53:21 +01002579 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2580 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002581 // Automatically disable the remote submix input when output is stopped on a
2582 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002583 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002584 if (isSingleDeviceType(
2585 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002586 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002587 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002588 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2589 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002590 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002591 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002592 }
2593 }
2594 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002595 if (client->hasPreferredDevice(true) &&
2596 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002597 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002598 forceDeviceUpdate = true;
2599 }
2600
Eric Laurente552edb2014-03-10 17:42:56 -07002601 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002602 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002603
Eric Laurente552edb2014-03-10 17:42:56 -07002604 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002605 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002606 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002607 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002608
2609 // If the routing does not change, if an output is routed on a device using HwGain
2610 // (aka setAudioPortConfig) and there are still active clients following different
2611 // volume group(s), force reapply volume
2612 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2613 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2614
Eric Laurente552edb2014-03-10 17:42:56 -07002615 // delay the device switch by twice the latency because stopOutput() is executed when
2616 // the track stop() command is received and at that time the audio track buffer can
2617 // still contain data that needs to be drained. The latency only covers the audio HAL
2618 // and kernel buffers. Also the latency does not always include additional delay in the
2619 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302620 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002621 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002622
2623 // force restoring the device selection on other active outputs if it differs from the
2624 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002625 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002626 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002627 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002628 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002629 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002630 desc->isActive() &&
2631 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002632 (newDevices != desc->devices())) {
2633 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2634 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002635
jiabin3ff8d7d2022-12-13 06:27:44 +00002636 if (desc->mUsePreferredMixerAttributes && force) {
2637 // If the device is using preferred mixer attributes, the output need to
2638 // reopen with default configuration when the new selected devices are
2639 // different from current routing devices.
2640 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2641 continue;
2642 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302643 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002644
Eric Laurent57de36c2016-09-28 16:59:11 -07002645 // re-apply device specific volume if not done by setOutputDevice()
2646 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002647 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002648 }
Eric Laurente552edb2014-03-10 17:42:56 -07002649 }
2650 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002651 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002652 // update the outputs if stopping one with a stream that can affect notification routing
2653 handleNotificationRoutingForStream(stream);
2654 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002655
2656 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2657 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002658 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002659 }
2660
François Gaffiec005e562018-11-06 15:04:49 +01002661 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002662 selectOutputForMusicEffects();
2663 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002664
2665 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2666
Eric Laurente552edb2014-03-10 17:42:56 -07002667 return NO_ERROR;
2668 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002669 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002670 return INVALID_OPERATION;
2671 }
2672}
2673
jiabinbce0c1d2020-10-05 11:20:18 -07002674bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002675{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002676 ALOGV("%s portId %d", __FUNCTION__, portId);
2677
2678 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2679 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002680 // If an output descriptor is closed due to a device routing change,
2681 // then there are race conditions with releaseOutput from tracks
2682 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2683 // destroyed shortly thereafter.
2684 //
2685 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002686 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002687 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002688 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002689
2690 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002691
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302692 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2693 if (outputDesc->isClientActive(client)) {
2694 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2695 stopOutput(portId);
2696 }
2697
Eric Laurent8fc147b2018-07-22 19:13:55 -07002698 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2699 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002700 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002701 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002702 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002703 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002704 if (--outputDesc->mDirectOpenCount == 0) {
2705 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002706 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002707 }
2708 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302709
Andy Hung39efb7a2018-09-26 15:39:28 -07002710 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002711 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2712 // The output is pending reopened to query dynamic profiles and
2713 // there is no active clients
2714 closeOutput(outputDesc->mIoHandle);
2715 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2716 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2717 if (newOutputDesc == nullptr) {
2718 ALOGE("%s failed to open output", __func__);
2719 }
2720 return true;
2721 }
2722 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002723}
2724
Eric Laurentcaf7f482014-11-25 17:50:47 -08002725status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2726 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002727 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002728 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002729 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002730 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002731 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002732 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002733 input_type_t *inputType,
2734 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002735{
François Gaffiec005e562018-11-06 15:04:49 +01002736 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002737 "flags %#x attributes=%s requested device ID %d",
2738 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2739 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002740
Eric Laurentad2e7b92017-09-14 20:06:42 -07002741 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002742 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002743 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002744 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002745 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002746 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002747 sp<RecordClientDescriptor> clientDesc;
2748 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002749 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002750 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751
2752 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2753 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2754 return INVALID_OPERATION;
2755 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002756
Francois Gaffie716e1432019-01-14 16:58:59 +01002757 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2758 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002759 }
2760
Paul McLean466dc8e2015-04-17 13:15:36 -06002761 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002762 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002763 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002764
Eric Laurentad2e7b92017-09-14 20:06:42 -07002765 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2766 // possible
2767 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2768 *input != AUDIO_IO_HANDLE_NONE) {
2769 ssize_t index = mInputs.indexOfKey(*input);
2770 if (index < 0) {
2771 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2772 status = BAD_VALUE;
2773 goto error;
2774 }
2775 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002776 RecordClientVector clients = inputDesc->getClientsForSession(session);
2777 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002778 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2779 status = BAD_VALUE;
2780 goto error;
2781 }
2782 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2783 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002784 // corresponds to a new client and is only permitted from the same UID.
2785 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002786 if (clients.size() > 1) {
2787 for (const auto& client : clients) {
2788 // The client map is ordered by key values (portId) and portIds are allocated
2789 // incrementaly. So the first client in this list is the one opened by audio flinger
2790 // when the mmap stream is created and should be ignored as it does not correspond
2791 // to an actual client
2792 if (client == *clients.cbegin()) {
2793 continue;
2794 }
2795 if (uid != client->uid() && !client->isSilenced()) {
2796 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2797 uid, client->portId(), client->uid());
2798 status = INVALID_OPERATION;
2799 goto error;
2800 }
Eric Laurent331679c2018-04-16 17:03:16 -07002801 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002802 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002803 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002804 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002805
Eric Laurentfecbceb2021-02-09 14:46:43 +01002806 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002807 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002808 }
2809
2810 *input = AUDIO_IO_HANDLE_NONE;
2811 *inputType = API_INPUT_INVALID;
2812
Francois Gaffie716e1432019-01-14 16:58:59 +01002813 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002814 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002815 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002816 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002817 ALOGW("%s could not find input mix for attr %s",
2818 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002819 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002820 }
jiabinc1de2df2019-05-07 14:26:40 -07002821 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2822 String8(attr->tags + strlen("addr=")),
2823 AUDIO_FORMAT_DEFAULT);
2824 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002825 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002826 __func__, attributes.source, attributes.tags);
2827 status = BAD_VALUE;
2828 goto error;
2829 }
2830
Kevin Rocard25f9b052019-02-27 15:08:54 -08002831 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2832 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2833 } else {
2834 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2835 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002836 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002837 if (explicitRoutingDevice != nullptr) {
2838 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002839 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002840 // Prevent from storing invalid requested device id in clients
2841 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002842 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002843 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2844 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002845 }
François Gaffie11d30102018-11-02 16:09:09 +01002846 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002847 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002848 status = BAD_VALUE;
2849 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002850 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002851 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2852 *inputType = API_INPUT_MIX_CAPTURE;
2853 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002854 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2855 // there is an external policy, but this input is attached to a mix of recorders,
2856 // meaning it receives audio injected into the framework, so the recorder doesn't
2857 // know about it and is therefore considered "legacy"
2858 *inputType = API_INPUT_LEGACY;
2859 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002860 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002861 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002862 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002863 } else {
2864 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002865 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002866
Eric Laurent599c7582015-12-07 18:05:55 -08002867 }
2868
François Gaffiec005e562018-11-06 15:04:49 +01002869 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002870 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002871 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002872 AudioProfileVector profiles;
2873 status_t ret = getProfilesForDevices(
2874 DeviceVector(device), profiles, flags, true /*isInput*/);
2875 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002876 const auto channels = profiles[0]->getChannels();
2877 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2878 config->channel_mask = *channels.begin();
2879 }
2880 const auto sampleRates = profiles[0]->getSampleRates();
2881 if (!sampleRates.empty() &&
2882 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2883 config->sample_rate = *sampleRates.begin();
2884 }
jiabinf1c73972022-04-14 16:28:52 -07002885 config->format = profiles[0]->getFormat();
2886 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002887 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002888 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002889
Eric Laurent8f42ea12018-08-08 09:08:25 -07002890exit:
2891
François Gaffiec005e562018-11-06 15:04:49 +01002892 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2893 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002894
Francois Gaffie716e1432019-01-14 16:58:59 +01002895 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002896 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002897 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002898
Mikhail Naganov2996f672019-04-18 12:29:59 -07002899 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002900 requestedDeviceId, attributes.source, flags,
2901 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002902 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002903 // Move (if found) effect for the client session to its input
2904 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002905 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002906
2907 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2908 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002909
Eric Laurent599c7582015-12-07 18:05:55 -08002910 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002911
2912error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002913 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002914}
2915
2916
François Gaffie11d30102018-11-02 16:09:09 +01002917audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002918 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002919 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002920 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002921 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002922 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002923{
2924 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002925 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002926 bool isSoundTrigger = false;
2927
François Gaffiec005e562018-11-06 15:04:49 +01002928 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002929 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2930 if (index >= 0) {
2931 input = mSoundTriggerSessions.valueFor(session);
2932 isSoundTrigger = true;
2933 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2934 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2935 } else {
2936 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002937 }
François Gaffiec005e562018-11-06 15:04:49 +01002938 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002939 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002940 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002941 }
2942
Carter Hsua3abb402021-10-26 11:11:20 +08002943 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2944 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2945 }
2946
Eric Laurentfe231122017-11-17 17:48:06 -08002947 // sampling rate and flags may be updated by getInputProfile
2948 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2949 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002950 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002951 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002952 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002953 // find a compatible input profile (not necessarily identical in parameters)
2954 sp<IOProfile> profile = getInputProfile(
2955 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2956 if (profile == nullptr) {
2957 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002958 }
jiabin2fd710d2022-05-02 23:20:22 +00002959
Glenn Kasten05ddca52016-02-11 08:17:12 -08002960 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002961 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002962 if (samplingRate == 0) {
2963 samplingRate = profileSamplingRate;
2964 }
Eric Laurente552edb2014-03-10 17:42:56 -07002965
Eric Laurent322b4d22015-04-03 15:57:54 -07002966 if (profile->getModuleHandle() == 0) {
2967 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002968 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002969 }
2970
Eric Laurentec376dc2021-04-08 20:41:22 +02002971 // Reuse an already opened input if a client with the same session ID already exists
2972 // on that input
2973 for (size_t i = 0; i < mInputs.size(); i++) {
2974 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2975 if (desc->mProfile != profile) {
2976 continue;
2977 }
2978 RecordClientVector clients = desc->clientsList();
2979 for (const auto &client : clients) {
2980 if (session == client->session()) {
2981 return desc->mIoHandle;
2982 }
2983 }
2984 }
2985
Eric Laurent3974e3b2017-12-07 17:58:43 -08002986 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002987 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002988 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002989 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002990 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002991 continue;
2992 }
2993 // if sound trigger, reuse input if used by other sound trigger on same session
2994 // else
2995 // reuse input if active client app is not in IDLE state
2996 //
2997 RecordClientVector clients = desc->clientsList();
2998 bool doClose = false;
2999 for (const auto& client : clients) {
3000 if (isSoundTrigger != client->isSoundTrigger()) {
3001 continue;
3002 }
3003 if (client->isSoundTrigger()) {
3004 if (session == client->session()) {
3005 return desc->mIoHandle;
3006 }
3007 continue;
3008 }
3009 if (client->active() && client->appState() != APP_STATE_IDLE) {
3010 return desc->mIoHandle;
3011 }
3012 doClose = true;
3013 }
3014 if (doClose) {
3015 closeInput(desc->mIoHandle);
3016 } else {
3017 i++;
3018 }
3019 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003020 }
3021
Eric Laurentfe231122017-11-17 17:48:06 -08003022 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003023
Eric Laurentfe231122017-11-17 17:48:06 -08003024 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3025 lConfig.sample_rate = profileSamplingRate;
3026 lConfig.channel_mask = profileChannelMask;
3027 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003028
François Gaffie11d30102018-11-02 16:09:09 +01003029 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003030
3031 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003032 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003033 (profileSamplingRate != lConfig.sample_rate) ||
3034 !audio_formats_match(profileFormat, lConfig.format) ||
3035 (profileChannelMask != lConfig.channel_mask)) {
3036 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003037 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003038 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003039 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003040 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003041 }
Eric Laurent599c7582015-12-07 18:05:55 -08003042 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003043 }
3044
Eric Laurentc722f302014-12-10 11:21:49 -08003045 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003046
Eric Laurent599c7582015-12-07 18:05:55 -08003047 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003048 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003049
Eric Laurent599c7582015-12-07 18:05:55 -08003050 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003051}
3052
Eric Laurent4eb58f12018-12-07 16:41:02 -08003053status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003054{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003055 ALOGV("%s portId %d", __FUNCTION__, portId);
3056
3057 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3058 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003059 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003060 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003061 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003062 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003063 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003064 if (client->active()) {
3065 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3066 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003067 }
3068
Eric Laurent8f42ea12018-08-08 09:08:25 -07003069 audio_session_t session = client->session();
3070
Eric Laurent4eb58f12018-12-07 16:41:02 -08003071 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072
Eric Laurent4eb58f12018-12-07 16:41:02 -08003073 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003074
Eric Laurent4eb58f12018-12-07 16:41:02 -08003075 status_t status = inputDesc->start();
3076 if (status != NO_ERROR) {
3077 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003078 }
Eric Laurente552edb2014-03-10 17:42:56 -07003079
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003080 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003081 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003083
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084 // indicate active capture to sound trigger service if starting capture from a mic on
3085 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003086 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003087 if (device != nullptr) {
3088 status = setInputDevice(input, device, true /* force */);
3089 } else {
3090 ALOGW("%s no new input device can be found for descriptor %d",
3091 __FUNCTION__, inputDesc->getId());
3092 status = BAD_VALUE;
3093 }
Eric Laurente552edb2014-03-10 17:42:56 -07003094
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003095 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003096 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003097 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003098 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003099 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3100 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003101 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003102 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003103
François Gaffie11d30102018-11-02 16:09:09 +01003104 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3105 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003106 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003107 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003108 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003109
Eric Laurent8f42ea12018-08-08 09:08:25 -07003110 // automatically enable the remote submix output when input is started if not
3111 // used by a policy mix of type MIX_TYPE_RECORDERS
3112 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003113 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003115 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003116 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003117 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3118 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003119 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003120 if (address != "") {
3121 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3122 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003123 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003124 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003125 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003126 } else if (status != NO_ERROR) {
3127 // Restore client activity state.
3128 inputDesc->setClientActive(client, false);
3129 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003130 }
3131
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003132 ALOGV("%s input %d source = %d status = %d exit",
3133 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003134
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003135 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003136}
3137
Eric Laurent8fc147b2018-07-22 19:13:55 -07003138status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003139{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003140 ALOGV("%s portId %d", __FUNCTION__, portId);
3141
3142 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3143 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003144 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003145 return BAD_VALUE;
3146 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003147 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003148 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003149 if (!client->active()) {
3150 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003151 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003152 }
Carter Hsue6139d52021-07-08 10:30:20 +08003153 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003154 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003155
Eric Laurent8f42ea12018-08-08 09:08:25 -07003156 inputDesc->stop();
3157 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003158 auto current_source = inputDesc->source();
3159 setInputDevice(input, getNewInputDevice(inputDesc),
3160 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003161 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003162 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003163 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003164 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003165 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3166 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003167 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003168 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003169
3170 // automatically disable the remote submix output when input is stopped if not
3171 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003172 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003173 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003174 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003175 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003176 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3177 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003178 }
3179 if (address != "") {
3180 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3181 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003182 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003183 }
3184 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003185 resetInputDevice(input);
3186
3187 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3188 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003189 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3190 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003191 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003192 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003193 }
3194 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003195 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003196 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003197}
3198
Eric Laurent8fc147b2018-07-22 19:13:55 -07003199void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003200{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003201 ALOGV("%s portId %d", __FUNCTION__, portId);
3202
3203 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3204 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003205 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003206 return;
3207 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003208 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003209 audio_io_handle_t input = inputDesc->mIoHandle;
3210
Eric Laurent8f42ea12018-08-08 09:08:25 -07003211 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003212
Andy Hung39efb7a2018-09-26 15:39:28 -07003213 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003214 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003215 if (inputDesc->getClientCount() > 0) {
3216 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003217 return;
3218 }
3219
Eric Laurent05b90f82014-08-27 15:32:29 -07003220 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003221 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003222 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003223}
3224
Eric Laurent8f42ea12018-08-08 09:08:25 -07003225void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003226{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003227 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003228
3229 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003230 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003231 }
3232}
3233
Eric Laurent8f42ea12018-08-08 09:08:25 -07003234void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3235{
3236 stopInput(portId);
3237 releaseInput(portId);
3238}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003239
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003240bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3241 if (input->clientsList().size() == 0
3242 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3243 return true;
3244 }
3245 for (const auto& client : input->clientsList()) {
3246 sp<DeviceDescriptor> device =
3247 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3248 client->session());
3249 if (!input->supportedDevices().contains(device)) {
3250 return true;
3251 }
3252 }
3253 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3254 return false;
3255}
3256
Eric Laurent0dd51852019-04-19 18:18:58 -07003257void AudioPolicyManager::checkCloseInputs() {
3258 // After connecting or disconnecting an input device, close input if:
3259 // - it has no client (was just opened to check profile) OR
3260 // - none of its supported devices are connected anymore OR
3261 // - one of its clients cannot be routed to one of its supported
3262 // devices anymore. Otherwise update device selection
3263 std::vector<audio_io_handle_t> inputsToClose;
3264 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003265 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003266 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003267 }
3268 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003269 for (const audio_io_handle_t handle : inputsToClose) {
3270 ALOGV("%s closing input %d", __func__, handle);
3271 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003272 }
Eric Laurentd4692962014-05-05 18:13:44 -07003273}
3274
François Gaffie251c7f02018-11-07 10:41:08 +01003275void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003276{
3277 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003278 if (indexMin < 0 || indexMax < 0) {
3279 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3280 return;
3281 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003282 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003283
3284 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003285 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3286 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003287 continue;
3288 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003289 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003290 }
Eric Laurente552edb2014-03-10 17:42:56 -07003291}
3292
Eric Laurente0720872014-03-11 09:30:41 -07003293status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003294 int index,
3295 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003296{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003297 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003298 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3299 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3300 return NO_ERROR;
3301 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303302 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3303 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003304 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003305}
3306
Eric Laurente0720872014-03-11 09:30:41 -07003307status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003308 int *index,
3309 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003310{
François Gaffiec005e562018-11-06 15:04:49 +01003311 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3312 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003313 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003314 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003315 deviceTypes = mEngine->getOutputDevicesForStream(
3316 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003317 }
jiabin9a3361e2019-10-01 09:38:30 -07003318 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003319}
3320
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003321status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003322 int index,
3323 audio_devices_t device)
3324{
3325 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003326 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3327 if (group == VOLUME_GROUP_NONE) {
3328 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003329 return BAD_VALUE;
3330 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003331 ALOGV("%s: group %d matching with %s index %d",
3332 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003333 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003334 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003335 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003336 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3337 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3338 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3339 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003340 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3341
3342 status = setVolumeCurveIndex(index, device, curves);
3343 if (status != NO_ERROR) {
3344 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3345 return status;
3346 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003347
jiabin9a3361e2019-10-01 09:38:30 -07003348 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003349 auto curCurvAttrs = curves.getAttributes();
3350 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3351 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003352 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003353 } else if (!curves.getStreamTypes().empty()) {
3354 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003355 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003356 } else {
3357 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3358 return BAD_VALUE;
3359 }
jiabin9a3361e2019-10-01 09:38:30 -07003360 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3361 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003362
François Gaffiecfe17322018-11-07 13:41:29 +01003363 // update volume on all outputs and streams matching the following:
3364 // - The requested stream (or a stream matching for volume control) is active on the output
3365 // - The device (or devices) selected by the engine for this stream includes
3366 // the requested device
3367 // - For non default requested device, currently selected device on the output is either the
3368 // requested device or one of the devices selected by the engine for this stream
3369 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3370 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003371 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003372 for (size_t i = 0; i < mOutputs.size(); i++) {
3373 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003374 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003375
jiabin9a3361e2019-10-01 09:38:30 -07003376 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3377 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003378 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003379
3380 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003381 continue;
3382 }
3383 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3384 curDevices.find(device) == curDevices.end()) {
3385 continue;
3386 }
3387 bool applyVolume = false;
3388 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3389 curSrcDevices.insert(device);
3390 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003391 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3392 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003393 } else {
3394 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3395 }
3396 if (!applyVolume) {
3397 continue; // next output
3398 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003399 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3400 // If a higher priority strategy is active, and the output is routed to a device with a
3401 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003402 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003403 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003404 // If the volume source is active with higher priority source, ensure at least Sw Muted
3405 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003406 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3407 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3408 false /*preferredDevice*/);
3409 if (activeClients.empty()) {
3410 continue;
3411 }
3412 bool isPreempted = false;
3413 bool isHigherPriority = productStrategy < strategy;
3414 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003415 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003416 ALOGV("%s: Strategy=%d (\nrequester:\n"
3417 " group %d, volumeGroup=%d attributes=%s)\n"
3418 " higher priority source active:\n"
3419 " volumeGroup=%d attributes=%s) \n"
3420 " on output %zu, bailing out", __func__, productStrategy,
3421 group, group, toString(attributes).c_str(),
3422 client->volumeSource(), toString(client->attributes()).c_str(), i);
3423 applyVolume = false;
3424 isPreempted = true;
3425 break;
3426 }
3427 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003428 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003429 applyVolume = true;
3430 }
3431 }
3432 if (isPreempted || applyVolume) {
3433 break;
3434 }
3435 }
3436 if (!applyVolume) {
3437 continue; // next output
3438 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003439 }
François Gaffieed91f582020-01-31 10:35:37 +01003440 //FIXME: workaround for truncated touch sounds
3441 // delayed volume change for system stream to be removed when the problem is
3442 // handled by system UI
3443 status_t volStatus = checkAndSetVolume(
3444 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003445 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003446 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3447 if (volStatus != NO_ERROR) {
3448 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003449 }
3450 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003451
3452 // update voice volume if the an active call route exists
3453 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3454 && (curSrcDevices.find(
3455 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3456 != curSrcDevices.end())) {
3457 bool isVoiceVolSrc;
3458 bool isBtScoVolSrc;
3459 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3460 isVoiceVolSrc, isBtScoVolSrc, __func__)
3461 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003462 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3463 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3464 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003465 }
3466 }
3467
François Gaffiecfe17322018-11-07 13:41:29 +01003468 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3469 return status;
3470}
3471
François Gaffieaaac0fd2018-11-22 17:56:39 +01003472status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003473 audio_devices_t device,
3474 IVolumeCurves &volumeCurves)
3475{
3476 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3477 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003478 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3479 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003480 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303481 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3482 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003483 return BAD_VALUE;
3484 }
3485 if (!audio_is_output_device(device)) {
3486 return BAD_VALUE;
3487 }
3488
3489 // Force max volume if stream cannot be muted
3490 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3491
François Gaffieaaac0fd2018-11-22 17:56:39 +01003492 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003493 volumeCurves.addCurrentVolumeIndex(device, index);
3494 return NO_ERROR;
3495}
3496
3497status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3498 int &index,
3499 audio_devices_t device)
3500{
3501 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3502 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003503 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003504 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003505 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003506 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003507 }
jiabin9a3361e2019-10-01 09:38:30 -07003508 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003509}
3510
3511status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3512 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003513 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003514{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003515 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003516 return BAD_VALUE;
3517 }
jiabin9a3361e2019-10-01 09:38:30 -07003518 index = curves.getVolumeIndex(deviceTypes);
3519 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003520 return NO_ERROR;
3521}
3522
3523status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3524 int &index)
3525{
3526 index = getVolumeCurves(attr).getVolumeIndexMin();
3527 return NO_ERROR;
3528}
3529
3530status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3531 int &index)
3532{
3533 index = getVolumeCurves(attr).getVolumeIndexMax();
3534 return NO_ERROR;
3535}
3536
Eric Laurent36829f92017-04-07 19:04:42 -07003537audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003538{
3539 // select one output among several suitable for global effects.
3540 // The priority is as follows:
3541 // 1: An offloaded output. If the effect ends up not being offloadable,
3542 // AudioFlinger will invalidate the track and the offloaded output
3543 // will be closed causing the effect to be moved to a PCM output.
3544 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003545 // 3: The primary output
3546 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003547
François Gaffiec005e562018-11-06 15:04:49 +01003548 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3549 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003550 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003551
Eric Laurent36829f92017-04-07 19:04:42 -07003552 if (outputs.size() == 0) {
3553 return AUDIO_IO_HANDLE_NONE;
3554 }
Eric Laurente552edb2014-03-10 17:42:56 -07003555
Eric Laurent36829f92017-04-07 19:04:42 -07003556 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3557 bool activeOnly = true;
3558
3559 while (output == AUDIO_IO_HANDLE_NONE) {
3560 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3561 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3562 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3563
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003564 for (audio_io_handle_t output : outputs) {
3565 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003566 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003567 continue;
3568 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003569 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3570 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003571 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003572 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003573 }
3574 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003575 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003576 }
3577 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003578 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003579 }
3580 }
3581 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3582 output = outputOffloaded;
3583 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3584 output = outputDeepBuffer;
3585 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3586 output = outputPrimary;
3587 } else {
3588 output = outputs[0];
3589 }
3590 activeOnly = false;
3591 }
3592
3593 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003594 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3595 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003596 mMusicEffectOutput = output;
3597 }
3598
3599 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003600 return output;
3601}
3602
Eric Laurent36829f92017-04-07 19:04:42 -07003603audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3604{
3605 return selectOutputForMusicEffects();
3606}
3607
Eric Laurente0720872014-03-11 09:30:41 -07003608status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003609 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003610 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003611 int session,
3612 int id)
3613{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003614 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003615 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003616 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003617 index = mInputs.indexOfKey(io);
3618 if (index < 0) {
3619 ALOGW("registerEffect() unknown io %d", io);
3620 return INVALID_OPERATION;
3621 }
Eric Laurente552edb2014-03-10 17:42:56 -07003622 }
3623 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003624 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3625 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3626 || strategy == PRODUCT_STRATEGY_NONE));
3627 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003628}
3629
Eric Laurentc241b0d2018-11-28 09:08:49 -08003630status_t AudioPolicyManager::unregisterEffect(int id)
3631{
3632 if (mEffects.getEffect(id) == nullptr) {
3633 return INVALID_OPERATION;
3634 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003635 if (mEffects.isEffectEnabled(id)) {
3636 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3637 setEffectEnabled(id, false);
3638 }
3639 return mEffects.unregisterEffect(id);
3640}
3641
3642status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3643{
3644 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3645 if (effect == nullptr) {
3646 return INVALID_OPERATION;
3647 }
3648
3649 status_t status = mEffects.setEffectEnabled(id, enabled);
3650 if (status == NO_ERROR) {
3651 mInputs.trackEffectEnabled(effect, enabled);
3652 }
3653 return status;
3654}
3655
Eric Laurent6c796322019-04-09 14:13:17 -07003656
3657status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3658{
3659 mEffects.moveEffects(ids, io);
3660 return NO_ERROR;
3661}
3662
Eric Laurentc75307b2015-03-17 15:29:32 -07003663bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3664{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003665 auto vs = toVolumeSource(stream, false);
3666 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003667}
3668
3669bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3670{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003671 auto vs = toVolumeSource(stream, false);
3672 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003673}
3674
Eric Laurente0720872014-03-11 09:30:41 -07003675bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003676{
3677 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003678 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003679 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003680 return true;
3681 }
3682 }
3683 return false;
3684}
3685
Eric Laurent275e8e92014-11-30 15:14:47 -08003686// Register a list of custom mixes with their attributes and format.
3687// When a mix is registered, corresponding input and output profiles are
3688// added to the remote submix hw module. The profile contains only the
3689// parameters (sampling rate, format...) specified by the mix.
3690// The corresponding input remote submix device is also connected.
3691//
3692// When a remote submix device is connected, the address is checked to select the
3693// appropriate profile and the corresponding input or output stream is opened.
3694//
3695// When capture starts, getInputForAttr() will:
3696// - 1 look for a mix matching the address passed in attribtutes tags if any
3697// - 2 if none found, getDeviceForInputSource() will:
3698// - 2.1 look for a mix matching the attributes source
3699// - 2.2 if none found, default to device selection by policy rules
3700// At this time, the corresponding output remote submix device is also connected
3701// and active playback use cases can be transferred to this mix if needed when reconnecting
3702// after AudioTracks are invalidated
3703//
3704// When playback starts, getOutputForAttr() will:
3705// - 1 look for a mix matching the address passed in attribtutes tags if any
3706// - 2 if none found, look for a mix matching the attributes usage
3707// - 3 if none found, default to device and output selection by policy rules.
3708
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003709status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003710{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003711 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3712 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003713 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003714 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003715 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003716 // examine each mix's route type
3717 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003718 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003719 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3720 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3721 ALOGE("Unsupported Policy Mix %zu of %zu: "
3722 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3723 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003724 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003725 break;
3726 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003727 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3728 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003729 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003730 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3731 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003732 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003733 rSubmixModule = mHwModules.getModuleFromName(
3734 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3735 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003736 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003737 i);
3738 res = INVALID_OPERATION;
3739 break;
3740 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003741 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003742
Eric Laurent97ac8712018-07-27 18:59:02 -07003743 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003744 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003745 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003746 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003747 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3748 } else {
3749 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3750 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003751 }
François Gaffie036e1e92015-03-19 10:16:24 +01003752
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003753 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003754 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003755 res = INVALID_OPERATION;
3756 break;
3757 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003758 audio_config_t outputConfig = mix.mFormat;
3759 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003760 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3761 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003762 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3763 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003764 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003765 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3766 audio_is_linear_pcm(outputConfig.format)
3767 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003768 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003769 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3770 audio_is_linear_pcm(inputConfig.format)
3771 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003772
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003773 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003774 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003775 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003776 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003777 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003778 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003779 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003780 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3781 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003782 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003783 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003784 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003785
3786 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3787 mix.mDeviceType, mix.mDeviceAddress,
3788 String8(), AUDIO_FORMAT_DEFAULT);
3789 if (device == nullptr) {
3790 res = INVALID_OPERATION;
3791 break;
3792 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003793
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003794 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003795 // First try to find an already opened output supporting the device
3796 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003797 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003798
Eric Laurentc529cf62020-04-17 18:19:10 -07003799 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003800 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003801 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003802 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003803 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003804 } else {
3805 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003806 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003807 }
3808 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003809 // If no output found, try to find a direct output profile supporting the device
3810 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3811 sp<HwModule> module = mHwModules[i];
3812 for (size_t j = 0;
3813 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3814 j++) {
3815 sp<IOProfile> profile = module->getOutputProfiles()[j];
3816 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3817 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3818 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003819 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003820 res = INVALID_OPERATION;
3821 } else {
3822 foundOutput = true;
3823 }
3824 }
3825 }
3826 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003827 if (res != NO_ERROR) {
3828 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003829 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003830 res = INVALID_OPERATION;
3831 break;
3832 } else if (!foundOutput) {
3833 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003834 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003835 res = INVALID_OPERATION;
3836 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003837 } else {
3838 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003839 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003840 }
Eric Laurentc722f302014-12-10 11:21:49 -08003841 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003842 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003843 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003844 if (audio_flags::audio_mix_ownership()) {
3845 // Only unregister mixes that were actually registered to not accidentally unregister
3846 // mixes that already existed previously.
3847 unregisterPolicyMixes(registeredMixes);
3848 registeredMixes.clear();
3849 } else {
3850 unregisterPolicyMixes(mixes);
3851 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003852 } else if (checkOutputs) {
3853 checkForDeviceAndOutputChanges();
3854 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003855 }
3856 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003857}
3858
3859status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3860{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003861 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Marvin Raminabd9b892023-11-17 16:36:27 +01003862 status_t endResult = NO_ERROR;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003863 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003864 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003865 sp<HwModule> rSubmixModule;
3866 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003867 for (const auto& mix : mixes) {
3868 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003869
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003870 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003871 rSubmixModule = mHwModules.getModuleFromName(
3872 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3873 if (rSubmixModule == 0) {
3874 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003875 endResult = INVALID_OPERATION;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003876 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003877 }
3878 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003879
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003880 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003881
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003882 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003883 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003884 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003885 continue;
3886 }
3887
Kevin Rocard04ed0462019-05-02 17:53:24 -07003888 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003889 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003890 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3891 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003892 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003893 AUDIO_FORMAT_DEFAULT);
3894 if (res != OK) {
3895 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003896 "with type %d, address %s", device, address.c_str());
Marvin Raminabd9b892023-11-17 16:36:27 +01003897 endResult = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07003898 }
3899 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003900 }
jiabin5740f082019-08-19 15:08:30 -07003901 rSubmixModule->removeOutputProfile(address.c_str());
3902 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003903
Kevin Rocard153f92d2018-12-18 18:33:28 -08003904 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003905 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003906 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003907 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003908 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003909 } else {
3910 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003911 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003912 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003913 }
Marvin Raminabd9b892023-11-17 16:36:27 +01003914 if (audio_flags::audio_mix_ownership()) {
3915 res = endResult;
3916 if (res == NO_ERROR && checkOutputs) {
3917 checkForDeviceAndOutputChanges();
3918 updateCallAndOutputRouting();
3919 }
3920 } else {
3921 if (res == NO_ERROR && checkOutputs) {
3922 checkForDeviceAndOutputChanges();
3923 updateCallAndOutputRouting();
3924 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003925 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003926 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003927}
3928
Marvin Raminbdefaf02023-11-01 09:10:32 +01003929status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
3930 if (!audio_flags::audio_mix_test_api()) {
3931 return INVALID_OPERATION;
3932 }
3933
3934 _aidl_return.clear();
3935 _aidl_return.reserve(mPolicyMixes.size());
3936 for (const auto &policyMix: mPolicyMixes) {
3937 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
3938 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
3939 policyMix->mCbFlags);
3940 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01003941 _aidl_return.back().mToken = policyMix->mToken;
Marvin Raminbdefaf02023-11-01 09:10:32 +01003942 }
3943
3944 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return->size());
3945 return OK;
3946}
3947
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003948status_t AudioPolicyManager::updatePolicyMix(
3949 const AudioMix& mix,
3950 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3951 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3952 if (res == NO_ERROR) {
3953 checkForDeviceAndOutputChanges();
3954 updateCallAndOutputRouting();
3955 }
3956 return res;
3957}
3958
Mikhail Naganov100f0122018-11-29 11:22:16 -08003959void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3960{
3961 size_t i = 0;
3962 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3963 for (const auto& fmt : mManualSurroundFormats) {
3964 if (i++ != 0) dst->append(", ");
3965 std::string sfmt;
3966 FormatConverter::toString(fmt, sfmt);
3967 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3968 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3969 }
3970}
3971
Eric Laurentc529cf62020-04-17 18:19:10 -07003972// Returns true if all devices types match the predicate and are supported by one HW module
3973bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003974 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003975 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003976 const char *context,
3977 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003978 for (size_t i = 0; i < devices.size(); i++) {
3979 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003980 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003981 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003982 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003983 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003984 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003985 return false;
3986 }
3987 }
3988 return true;
3989}
3990
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003991void AudioPolicyManager::changeOutputDevicesMuteState(
3992 const AudioDeviceTypeAddrVector& devices) {
3993 ALOGVV("%s() num devices %zu", __func__, devices.size());
3994
3995 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3996 getSoftwareOutputsForDevices(devices);
3997
3998 for (size_t i = 0; i < outputs.size(); i++) {
3999 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4000 DeviceVector prevDevices = outputDesc->devices();
4001 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4002 }
4003}
4004
4005std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4006 const AudioDeviceTypeAddrVector& devices) const
4007{
4008 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4009 DeviceVector deviceDescriptors;
4010 for (size_t j = 0; j < devices.size(); j++) {
4011 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4012 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4013 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4014 ALOGE("%s: device type %#x address %s not supported or not an output device",
4015 __func__, devices[j].mType, devices[j].getAddress());
4016 continue;
4017 }
4018 deviceDescriptors.add(desc);
4019 }
4020 for (size_t i = 0; i < mOutputs.size(); i++) {
4021 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4022 continue;
4023 }
4024 outputs.push_back(mOutputs.valueAt(i));
4025 }
4026 return outputs;
4027}
4028
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004029status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004030 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004031 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004032 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4033 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004034 }
4035 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004036 if (res != NO_ERROR) {
4037 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4038 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004039 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004040
4041 checkForDeviceAndOutputChanges();
4042 updateCallAndOutputRouting();
4043
4044 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004045}
4046
4047status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4048 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004049 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4050 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004051 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004052 __FUNCTION__, uid);
4053 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004054 }
4055
Eric Laurentc529cf62020-04-17 18:19:10 -07004056 checkForDeviceAndOutputChanges();
4057 updateCallAndOutputRouting();
4058
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004059 return res;
4060}
4061
Eric Laurent2517af32020-11-25 15:31:27 +01004062
jiabin0a488932020-08-07 17:32:40 -07004063status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4064 device_role_t role,
4065 const AudioDeviceTypeAddrVector &devices) {
4066 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4067 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004068
Eric Laurentc529cf62020-04-17 18:19:10 -07004069 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004070 return BAD_VALUE;
4071 }
jiabin0a488932020-08-07 17:32:40 -07004072 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004073 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004074 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4075 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004076 return status;
4077 }
4078
4079 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004080
4081 bool forceVolumeReeval = false;
4082 // FIXME: workaround for truncated touch sounds
4083 // to be removed when the problem is handled by system UI
4084 uint32_t delayMs = 0;
4085 if (strategy == mCommunnicationStrategy) {
4086 forceVolumeReeval = true;
4087 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4088 updateInputRouting();
4089 }
4090 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004091
4092 return NO_ERROR;
4093}
4094
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004095void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4096 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004097{
4098 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004099 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004100 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004101 // Only apply special touch sound delay once
4102 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004103 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004104 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004105 for (size_t i = 0; i < mOutputs.size(); i++) {
4106 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4107 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004108 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4109 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004110 // As done in setDeviceConnectionState, we could also fix default device issue by
4111 // preventing the force re-routing in case of default dev that distinguishes on address.
4112 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004113 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004114 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4115 // If the device is using preferred mixer attributes, the output need to reopen
4116 // with default configuration when the new selected devices are different from
4117 // current routing devices.
4118 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4119 continue;
4120 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304121
4122 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4123 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004124 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004125 // Only apply special touch sound delay once
4126 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004127 }
4128 if (forceVolumeReeval && !newDevices.isEmpty()) {
4129 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4130 }
4131 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004132 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004133 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004134}
4135
Eric Laurent2517af32020-11-25 15:31:27 +01004136void AudioPolicyManager::updateInputRouting() {
4137 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304138 // Skip for hotword recording as the input device switch
4139 // is handled within sound trigger HAL
4140 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4141 continue;
4142 }
Eric Laurent2517af32020-11-25 15:31:27 +01004143 auto newDevice = getNewInputDevice(activeDesc);
4144 // Force new input selection if the new device can not be reached via current input
4145 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4146 setInputDevice(activeDesc->mIoHandle, newDevice);
4147 } else {
4148 closeInput(activeDesc->mIoHandle);
4149 }
4150 }
4151}
4152
Paul Wang5d7cdb52022-11-22 09:45:06 +00004153status_t
4154AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4155 device_role_t role,
4156 const AudioDeviceTypeAddrVector &devices) {
4157 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4158 dumpAudioDeviceTypeAddrVector(devices).c_str());
4159
Eric Laurent78fedbf2023-03-09 14:40:44 +01004160 if (!areAllDevicesSupported(
4161 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004162 return BAD_VALUE;
4163 }
4164 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4165 if (status != NO_ERROR) {
4166 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4167 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4168 return status;
4169 }
4170
4171 checkForDeviceAndOutputChanges();
4172
4173 bool forceVolumeReeval = false;
4174 // TODO(b/263479999): workaround for truncated touch sounds
4175 // to be removed when the problem is handled by system UI
4176 uint32_t delayMs = 0;
4177 if (strategy == mCommunnicationStrategy) {
4178 forceVolumeReeval = true;
4179 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4180 updateInputRouting();
4181 }
4182 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4183
4184 return NO_ERROR;
4185}
4186
4187status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4188 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004189{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004190 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004191
Paul Wang5d7cdb52022-11-22 09:45:06 +00004192 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004193 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004194 ALOGW_IF(status != NAME_NOT_FOUND,
4195 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004196 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004197 return status;
4198 }
4199
4200 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004201
4202 bool forceVolumeReeval = false;
4203 // FIXME: workaround for truncated touch sounds
4204 // to be removed when the problem is handled by system UI
4205 uint32_t delayMs = 0;
4206 if (strategy == mCommunnicationStrategy) {
4207 forceVolumeReeval = true;
4208 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4209 updateInputRouting();
4210 }
4211 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004212
4213 return NO_ERROR;
4214}
4215
jiabin0a488932020-08-07 17:32:40 -07004216status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4217 device_role_t role,
4218 AudioDeviceTypeAddrVector &devices) {
4219 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004220}
4221
Jiabin Huang3b98d322020-09-03 17:54:16 +00004222status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4223 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4224 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4225 dumpAudioDeviceTypeAddrVector(devices).c_str());
4226
Mikhail Naganov55773032020-10-01 15:08:13 -07004227 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004228 return BAD_VALUE;
4229 }
4230 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4231 ALOGW_IF(status != NO_ERROR,
4232 "Engine could not set preferred devices %s for audio source %d role %d",
4233 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4234
4235 return status;
4236}
4237
4238status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4239 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4240 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4241 dumpAudioDeviceTypeAddrVector(devices).c_str());
4242
Mikhail Naganov55773032020-10-01 15:08:13 -07004243 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004244 return BAD_VALUE;
4245 }
4246 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4247 ALOGW_IF(status != NO_ERROR,
4248 "Engine could not add preferred devices %s for audio source %d role %d",
4249 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4250
Eric Laurent2517af32020-11-25 15:31:27 +01004251 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004252 return status;
4253}
4254
4255status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4256 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4257{
4258 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4259 dumpAudioDeviceTypeAddrVector(devices).c_str());
4260
Eric Laurent78fedbf2023-03-09 14:40:44 +01004261 if (!areAllDevicesSupported(
4262 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004263 return BAD_VALUE;
4264 }
4265
4266 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4267 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004268 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004269 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004270 if (status == NO_ERROR) {
4271 updateInputRouting();
4272 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004273 return status;
4274}
4275
4276status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4277 device_role_t role) {
4278 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4279
4280 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004281 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004282 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004283 if (status == NO_ERROR) {
4284 updateInputRouting();
4285 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004286 return status;
4287}
4288
4289status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4290 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4291 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4292}
4293
Oscar Azucena90e77632019-11-27 17:12:28 -08004294status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004295 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004296 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004297 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4298 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004299 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004300 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4301 if (status != NO_ERROR) {
4302 ALOGE("%s() could not set device affinity for userId %d",
4303 __FUNCTION__, userId);
4304 return status;
4305 }
4306
4307 // reevaluate outputs for all devices
4308 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004309 changeOutputDevicesMuteState(devices);
4310 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4311 true /* skipDelays */);
4312 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004313
4314 return NO_ERROR;
4315}
4316
4317status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004318 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004319 AudioDeviceTypeAddrVector devices;
4320 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004321 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4322 if (status != NO_ERROR) {
4323 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4324 __FUNCTION__, userId);
4325 return status;
4326 }
4327
4328 // reevaluate outputs for all devices
4329 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004330 changeOutputDevicesMuteState(devices);
4331 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4332 true /* skipDelays */);
4333 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004334
4335 return NO_ERROR;
4336}
4337
Andy Hungc29d82b2018-10-05 12:23:17 -07004338void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004339{
Andy Hungc29d82b2018-10-05 12:23:17 -07004340 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004341 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004342 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004343 std::string stateLiteral;
4344 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004345 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004346 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4347 "communications", "media", "record", "dock", "system",
4348 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4349 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4350 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004351 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4352 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4353 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4354 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4355 dst->append(" (MANUAL: ");
4356 dumpManualSurroundFormats(dst);
4357 dst->append(")");
4358 }
4359 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004360 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004361 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4362 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004363 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004364 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004365
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004366 dst->append("\n");
4367 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4368 dst->append("\n");
4369 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004370 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004371 mOutputs.dump(dst);
4372 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004373 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004374 mAudioPatches.dump(dst);
4375 mPolicyMixes.dump(dst);
4376 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004377
Kevin Rocardb99cc752019-03-21 20:52:24 -07004378 dst->appendFormat(" AllowedCapturePolicies:\n");
4379 for (auto& policy : mAllowedCapturePolicies) {
4380 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4381 }
4382
jiabina84c3d32022-12-02 18:59:55 +00004383 dst->appendFormat(" Preferred mixer audio configuration:\n");
4384 for (const auto it : mPreferredMixerAttrInfos) {
4385 dst->appendFormat(" - device port id: %d\n", it.first);
4386 for (const auto preferredMixerInfoIt : it.second) {
4387 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4388 preferredMixerInfoIt.second->dump(dst);
4389 }
4390 }
4391
François Gaffiec005e562018-11-06 15:04:49 +01004392 dst->appendFormat("\nPolicy Engine dump:\n");
4393 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004394}
4395
4396status_t AudioPolicyManager::dump(int fd)
4397{
4398 String8 result;
4399 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004400 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004401 return NO_ERROR;
4402}
4403
Kevin Rocardb99cc752019-03-21 20:52:24 -07004404status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4405{
4406 mAllowedCapturePolicies[uid] = capturePolicy;
4407 return NO_ERROR;
4408}
4409
Eric Laurente552edb2014-03-10 17:42:56 -07004410// This function checks for the parameters which can be offloaded.
4411// This can be enhanced depending on the capability of the DSP and policy
4412// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004413audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004414{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004415 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004416 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004417 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004418 offloadInfo.format,
4419 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4420 offloadInfo.has_video);
4421
jiabin2b9d5a12021-12-10 01:06:29 +00004422 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004423 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004424 }
4425
4426 // See if there is a profile to support this.
4427 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004428 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004429 offloadInfo.sample_rate,
4430 offloadInfo.format,
4431 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004432 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4433 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004434 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4435 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4436 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004437 if (profile == nullptr) {
4438 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4439 }
4440 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4441 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4442 }
4443 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004444}
4445
Michael Chana94fbb22018-04-24 14:31:19 +10004446bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4447 const audio_attributes_t& attributes) {
4448 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004449 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004450 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4451 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004452 config.sample_rate,
4453 config.format,
4454 config.channel_mask,
4455 output_flags,
4456 true /* directOnly */);
4457 ALOGV("%s() profile %sfound with name: %s, "
4458 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4459 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004460 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004461 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004462
4463 // also try the MSD module if compatible profile not found
4464 if (profile == nullptr) {
4465 profile = getMsdProfileForOutput(outputDevices,
4466 config.sample_rate,
4467 config.format,
4468 config.channel_mask,
4469 output_flags,
4470 true /* directOnly */);
4471 ALOGV("%s() MSD profile %sfound with name: %s, "
4472 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4473 __FUNCTION__, profile != 0 ? "" : "NOT ",
4474 (profile != 0 ? profile->getTagName().c_str() : "null"),
4475 config.sample_rate, config.format, config.channel_mask, output_flags);
4476 }
4477 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004478}
4479
jiabin2b9d5a12021-12-10 01:06:29 +00004480bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4481 bool durationIgnored) {
4482 if (mMasterMono) {
4483 return false; // no offloading if mono is set.
4484 }
4485
4486 // Check if offload has been disabled
4487 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4488 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4489 return false;
4490 }
4491
4492 // Check if stream type is music, then only allow offload as of now.
4493 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4494 {
4495 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4496 return false;
4497 }
4498
4499 //TODO: enable audio offloading with video when ready
4500 const bool allowOffloadWithVideo =
4501 property_get_bool("audio.offload.video", false /* default_value */);
4502 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4503 ALOGV("%s: has_video == true, returning false", __func__);
4504 return false;
4505 }
4506
4507 //If duration is less than minimum value defined in property, return false
4508 const int min_duration_secs = property_get_int32(
4509 "audio.offload.min.duration.secs", -1 /* default_value */);
4510 if (!durationIgnored) {
4511 if (min_duration_secs >= 0) {
4512 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4513 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4514 __func__, min_duration_secs);
4515 return false;
4516 }
4517 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4518 ALOGV("%s: Offload denied by duration < default min(=%u)",
4519 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4520 return false;
4521 }
4522 }
4523
4524 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4525 // creating an offloaded track and tearing it down immediately after start when audioflinger
4526 // detects there is an active non offloadable effect.
4527 // FIXME: We should check the audio session here but we do not have it in this context.
4528 // This may prevent offloading in rare situations where effects are left active by apps
4529 // in the background.
4530 if (mEffects.isNonOffloadableEffectEnabled()) {
4531 return false;
4532 }
4533
4534 return true;
4535}
4536
4537audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4538 const audio_config_t *config) {
4539 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4540 offloadInfo.format = config->format;
4541 offloadInfo.sample_rate = config->sample_rate;
4542 offloadInfo.channel_mask = config->channel_mask;
4543 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4544 offloadInfo.has_video = false;
4545 offloadInfo.is_streaming = false;
4546 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4547
4548 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4549 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4550 audio_flags_to_audio_output_flags(attr->flags, &flags);
4551 // only retain flags that will drive compressed offload or passthrough
4552 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4553 if (offloadPossible) {
4554 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4555 }
4556 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4557
Dorin Drimusfae3c642022-03-17 18:36:30 +01004558 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004559 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004560 DeviceVector outputDevices = engineOutputDevices;
4561 // the MSD module checks for different conditions and output devices
4562 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4563 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4564 continue;
4565 }
4566 outputDevices = getMsdAudioOutDevices();
4567 }
jiabin2b9d5a12021-12-10 01:06:29 +00004568 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004569 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004570 config->sample_rate, nullptr /*updatedSamplingRate*/,
4571 config->format, nullptr /*updatedFormat*/,
4572 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004573 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004574 continue;
4575 }
4576 // reject profiles not corresponding to a device currently available
4577 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4578 continue;
4579 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004580 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4581 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004582 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004583 != AUDIO_DIRECT_NOT_SUPPORTED) {
4584 // Already reports offload gapless supported. No need to report offload support.
4585 continue;
4586 }
4587 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4588 != AUDIO_OUTPUT_FLAG_NONE) {
4589 // If offload gapless is reported, no need to report offload support.
4590 directMode = (audio_direct_mode_t) ((directMode &
4591 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4592 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4593 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004594 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004595 }
4596 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004597 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004598 }
4599 }
4600 }
4601 return directMode;
4602}
4603
Dorin Drimusf2196d82022-01-03 12:11:18 +01004604status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4605 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004606 if (mEffects.isNonOffloadableEffectEnabled()) {
4607 return OK;
4608 }
jiabinf1c73972022-04-14 16:28:52 -07004609 DeviceVector devices;
4610 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004611 if (status != OK) {
4612 return status;
4613 }
4614 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4615 if (devices.empty()) {
4616 return OK; // no output devices for the attributes
4617 }
jiabinf1c73972022-04-14 16:28:52 -07004618 return getProfilesForDevices(devices, audioProfilesVector,
4619 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004620}
4621
jiabina84c3d32022-12-02 18:59:55 +00004622status_t AudioPolicyManager::getSupportedMixerAttributes(
4623 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4624 ALOGV("%s, portId=%d", __func__, portId);
4625 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4626 if (deviceDescriptor == nullptr) {
4627 ALOGE("%s the requested device is currently unavailable", __func__);
4628 return BAD_VALUE;
4629 }
jiabin96daffc2023-05-11 17:51:55 +00004630 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4631 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4632 deviceDescriptor->type());
4633 return BAD_VALUE;
4634 }
jiabina84c3d32022-12-02 18:59:55 +00004635 for (const auto& hwModule : mHwModules) {
4636 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4637 if (curProfile->supportsDevice(deviceDescriptor)) {
4638 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4639 }
4640 }
4641 }
4642 return NO_ERROR;
4643}
4644
4645status_t AudioPolicyManager::setPreferredMixerAttributes(
4646 const audio_attributes_t *attr,
4647 audio_port_handle_t portId,
4648 uid_t uid,
4649 const audio_mixer_attributes_t *mixerAttributes) {
4650 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4651 "mixerBehavior=%d}, uid=%d, portId=%u",
4652 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4653 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4654 mixerAttributes->mixer_behavior, uid, portId);
4655 if (attr->usage != AUDIO_USAGE_MEDIA) {
4656 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4657 return BAD_VALUE;
4658 }
4659 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4660 if (deviceDescriptor == nullptr) {
4661 ALOGE("%s the requested device is currently unavailable", __func__);
4662 return BAD_VALUE;
4663 }
4664 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4665 ALOGE("%s(%d), type=%d, is not a usb output device",
4666 __func__, portId, deviceDescriptor->type());
4667 return BAD_VALUE;
4668 }
4669
4670 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4671 audio_flags_to_audio_output_flags(attr->flags, &flags);
4672 flags = (audio_output_flags_t) (flags |
4673 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4674 sp<IOProfile> profile = nullptr;
4675 DeviceVector devices(deviceDescriptor);
4676 for (const auto& hwModule : mHwModules) {
4677 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4678 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004679 && curProfile->getCompatibilityScore(
4680 devices,
4681 mixerAttributes->config.sample_rate,
4682 nullptr /*updatedSamplingRate*/,
4683 mixerAttributes->config.format,
4684 nullptr /*updatedFormat*/,
4685 mixerAttributes->config.channel_mask,
4686 nullptr /*updatedChannelMask*/,
4687 flags,
4688 false /*exactMatchRequiredForInputFlags*/)
4689 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004690 profile = curProfile;
4691 break;
4692 }
4693 }
4694 }
4695 if (profile == nullptr) {
4696 ALOGE("%s, there is no compatible profile found", __func__);
4697 return BAD_VALUE;
4698 }
4699
4700 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4701 sp<PreferredMixerAttributesInfo>::make(
4702 uid, portId, profile, flags, *mixerAttributes);
4703 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4704 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4705
4706 // If 1) there is any client from the preferred mixer configuration owner that is currently
4707 // active and matches the strategy and 2) current output is on the preferred device and the
4708 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4709 // configuration.
4710 std::vector<audio_io_handle_t> outputsToReopen;
4711 for (size_t i = 0; i < mOutputs.size(); i++) {
4712 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004713 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4714 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4715 output->mUsePreferredMixerAttributes = true;
4716 } else {
4717 for (const auto &client: output->getActiveClients()) {
4718 if (client->uid() == uid && client->strategy() == strategy) {
4719 client->setIsInvalid();
4720 outputsToReopen.push_back(output->mIoHandle);
4721 }
jiabina84c3d32022-12-02 18:59:55 +00004722 }
4723 }
4724 }
4725 }
4726 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4727 config.sample_rate = mixerAttributes->config.sample_rate;
4728 config.channel_mask = mixerAttributes->config.channel_mask;
4729 config.format = mixerAttributes->config.format;
4730 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004731 sp<SwAudioOutputDescriptor> desc =
4732 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4733 if (desc == nullptr) {
4734 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4735 continue;
4736 }
4737 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004738 }
4739
4740 return NO_ERROR;
4741}
4742
4743sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004744 audio_port_handle_t devicePortId,
4745 product_strategy_t strategy,
4746 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004747 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4748 if (it == mPreferredMixerAttrInfos.end()) {
4749 return nullptr;
4750 }
jiabind9a58d32023-06-01 17:57:30 +00004751 if (activeBitPerfectPreferred) {
4752 for (auto [strategy, info] : it->second) {
4753 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4754 && info->getActiveClientCount() != 0) {
4755 return info;
4756 }
4757 }
jiabina84c3d32022-12-02 18:59:55 +00004758 }
jiabind9a58d32023-06-01 17:57:30 +00004759 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4760 return strategyMatchedMixerAttrInfoIt == it->second.end()
4761 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004762}
4763
4764status_t AudioPolicyManager::getPreferredMixerAttributes(
4765 const audio_attributes_t *attr,
4766 audio_port_handle_t portId,
4767 audio_mixer_attributes_t* mixerAttributes) {
4768 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4769 portId, mEngine->getProductStrategyForAttributes(*attr));
4770 if (info == nullptr) {
4771 return NAME_NOT_FOUND;
4772 }
4773 *mixerAttributes = info->getMixerAttributes();
4774 return NO_ERROR;
4775}
4776
4777status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4778 audio_port_handle_t portId,
4779 uid_t uid) {
4780 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4781 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4782 if (preferredMixerAttrInfo == nullptr) {
4783 return NAME_NOT_FOUND;
4784 }
4785 if (preferredMixerAttrInfo->getUid() != uid) {
4786 ALOGE("%s, requested uid=%d, owned uid=%d",
4787 __func__, uid, preferredMixerAttrInfo->getUid());
4788 return PERMISSION_DENIED;
4789 }
4790 mPreferredMixerAttrInfos[portId].erase(strategy);
4791 if (mPreferredMixerAttrInfos[portId].empty()) {
4792 mPreferredMixerAttrInfos.erase(portId);
4793 }
4794
4795 // Reconfig existing output
4796 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4797 for (size_t i = 0; i < mOutputs.size(); i++) {
4798 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4799 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4800 }
4801 }
4802 for (const auto output : potentialOutputsToReopen) {
4803 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4804 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4805 preferredMixerAttrInfo->getFlags())) {
4806 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4807 }
4808 }
4809 return NO_ERROR;
4810}
4811
Eric Laurent6a94d692014-05-20 11:18:06 -07004812status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4813 audio_port_type_t type,
4814 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004815 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004816 unsigned int *generation)
4817{
jiabin19cdba52020-11-24 11:28:58 -08004818 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4819 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 return BAD_VALUE;
4821 }
4822 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004823 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004824 *num_ports = 0;
4825 }
4826
4827 size_t portsWritten = 0;
4828 size_t portsMax = *num_ports;
4829 *num_ports = 0;
4830 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004831 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4832 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004833 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004834 for (const auto& dev : mAvailableOutputDevices) {
4835 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004836 continue;
4837 }
4838 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004839 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004840 }
4841 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004842 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004843 }
4844 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004845 for (const auto& dev : mAvailableInputDevices) {
4846 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004847 continue;
4848 }
4849 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004850 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004851 }
4852 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004853 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 }
4855 }
4856 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4857 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4858 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4859 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4860 }
4861 *num_ports += mInputs.size();
4862 }
4863 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004864 size_t numOutputs = 0;
4865 for (size_t i = 0; i < mOutputs.size(); i++) {
4866 if (!mOutputs[i]->isDuplicated()) {
4867 numOutputs++;
4868 if (portsWritten < portsMax) {
4869 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4870 }
4871 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 }
Eric Laurent84c70242014-06-23 08:46:27 -07004873 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004874 }
4875 }
jiabina84c3d32022-12-02 18:59:55 +00004876
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004878 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004879 return NO_ERROR;
4880}
4881
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004882status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4883 std::vector<media::AudioPortFw>* _aidl_return) {
4884 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4885 audio_port_v7 port;
4886 dev->toAudioPort(&port);
4887 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4888 _aidl_return->push_back(std::move(aidlPort));
4889 return OK;
4890 };
4891
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004892 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004893 for (const auto& dev : module->getDeclaredDevices()) {
4894 if (role == media::AudioPortRole::NONE ||
4895 ((role == media::AudioPortRole::SOURCE)
4896 == audio_is_input_device(dev->type()))) {
4897 RETURN_STATUS_IF_ERROR(pushPort(dev));
4898 }
4899 }
4900 }
4901 return OK;
4902}
4903
jiabin19cdba52020-11-24 11:28:58 -08004904status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004905{
Eric Laurent99fcae42018-05-17 16:59:18 -07004906 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4907 return BAD_VALUE;
4908 }
4909 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4910 if (dev != 0) {
4911 dev->toAudioPort(port);
4912 return NO_ERROR;
4913 }
4914 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4915 if (dev != 0) {
4916 dev->toAudioPort(port);
4917 return NO_ERROR;
4918 }
4919 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4920 if (out != 0) {
4921 out->toAudioPort(port);
4922 return NO_ERROR;
4923 }
4924 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4925 if (in != 0) {
4926 in->toAudioPort(port);
4927 return NO_ERROR;
4928 }
4929 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004930}
4931
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004932status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4933 audio_patch_handle_t *handle,
4934 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004935{
François Gaffieafd4cea2019-11-18 15:50:22 +01004936 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004937 if (handle == NULL || patch == NULL) {
4938 return BAD_VALUE;
4939 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004940 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004941 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004942 return BAD_VALUE;
4943 }
4944 // only one source per audio patch supported for now
4945 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004946 return INVALID_OPERATION;
4947 }
Eric Laurent874c42872014-08-08 15:13:39 -07004948 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004949 return INVALID_OPERATION;
4950 }
Eric Laurent874c42872014-08-08 15:13:39 -07004951 for (size_t i = 0; i < patch->num_sinks; i++) {
4952 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4953 return INVALID_OPERATION;
4954 }
4955 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004956
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004957 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4958 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4959 if (srcDevice == nullptr || sinkDevice == nullptr) {
4960 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4961 return BAD_VALUE;
4962 }
4963 ALOGV("%s between source %s and sink %s", __func__,
4964 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4965 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4966 // Default attributes, default volume priority, not to infer with non raw audio patches.
4967 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4968 const struct audio_port_config *source = &patch->sources[0];
4969 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004970 new SourceClientDescriptor(
4971 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4972 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4973 true);
4974 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004975
4976 status_t status =
4977 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4978
4979 if (status != NO_ERROR) {
4980 return INVALID_OPERATION;
4981 }
4982 mAudioSources.add(portId, sourceDesc);
4983 return NO_ERROR;
4984}
4985
4986status_t AudioPolicyManager::connectAudioSourceToSink(
4987 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4988 const struct audio_patch *patch,
4989 audio_patch_handle_t &handle,
4990 uid_t uid, uint32_t delayMs)
4991{
4992 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4993 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4994 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4995 return INVALID_OPERATION;
4996 }
4997 sourceDesc->connect(handle, sinkDevice);
4998 if (isMsdPatch(handle)) {
4999 return NO_ERROR;
5000 }
5001 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5002 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5003 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5004 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5005 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5006 goto FailurePatchAdded;
5007 }
5008 status = swOutput->start();
5009 if (status != NO_ERROR) {
5010 goto FailureSourceAdded;
5011 }
5012 swOutput->addClient(sourceDesc);
5013 status = startSource(swOutput, sourceDesc, &delayMs);
5014 if (status != NO_ERROR) {
5015 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5016 goto FailureSourceActive;
5017 }
5018 if (delayMs != 0) {
5019 usleep(delayMs * 1000);
5020 }
5021 return NO_ERROR;
5022
5023FailureSourceActive:
5024 swOutput->stop();
5025 releaseOutput(sourceDesc->portId());
5026FailureSourceAdded:
5027 sourceDesc->setSwOutput(nullptr);
5028FailurePatchAdded:
5029 releaseAudioPatchInternal(handle);
5030 return INVALID_OPERATION;
5031}
5032
5033status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5034 audio_patch_handle_t *handle,
5035 uid_t uid, uint32_t delayMs,
5036 const sp<SourceClientDescriptor>& sourceDesc)
5037{
5038 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005039 sp<AudioPatch> patchDesc;
5040 ssize_t index = mAudioPatches.indexOfKey(*handle);
5041
François Gaffieafd4cea2019-11-18 15:50:22 +01005042 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5043 patch->sources[0].role,
5044 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005045#if LOG_NDEBUG == 0
5046 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005047 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5048 patch->sinks[i].role,
5049 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005050 }
5051#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005052
5053 if (index >= 0) {
5054 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005055 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5056 __func__, mUidCached, patchDesc->getUid(), uid);
5057 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005058 return INVALID_OPERATION;
5059 }
5060 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005061 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005062 }
5063
5064 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005065 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005066 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005067 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005068 return BAD_VALUE;
5069 }
Eric Laurent84c70242014-06-23 08:46:27 -07005070 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5071 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005072 if (patchDesc != 0) {
5073 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005074 ALOGV("%s source id differs for patch current id %d new id %d",
5075 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005076 return BAD_VALUE;
5077 }
5078 }
Eric Laurent874c42872014-08-08 15:13:39 -07005079 DeviceVector devices;
5080 for (size_t i = 0; i < patch->num_sinks; i++) {
5081 // Only support mix to devices connection
5082 // TODO add support for mix to mix connection
5083 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005084 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005085 return INVALID_OPERATION;
5086 }
5087 sp<DeviceDescriptor> devDesc =
5088 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5089 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005090 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005091 return BAD_VALUE;
5092 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005093
jiabin66acc432024-02-06 00:57:36 +00005094 if (outputDesc->mProfile->getCompatibilityScore(
5095 DeviceVector(devDesc),
5096 patch->sources[0].sample_rate,
5097 nullptr, // updatedSamplingRate
5098 patch->sources[0].format,
5099 nullptr, // updatedFormat
5100 patch->sources[0].channel_mask,
5101 nullptr, // updatedChannelMask
5102 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005103 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005104 return INVALID_OPERATION;
5105 }
5106 devices.add(devDesc);
5107 }
5108 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005109 return INVALID_OPERATION;
5110 }
Eric Laurent874c42872014-08-08 15:13:39 -07005111
Eric Laurent6a94d692014-05-20 11:18:06 -07005112 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005113 ALOGV("%s setting device %s on output %d",
5114 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305115 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005116 index = mAudioPatches.indexOfKey(*handle);
5117 if (index >= 0) {
5118 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005119 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005120 }
5121 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005122 patchDesc->setUid(uid);
5123 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005125 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005126 return INVALID_OPERATION;
5127 }
5128 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5129 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5130 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005131 // only one sink supported when connecting an input device to a mix
5132 if (patch->num_sinks > 1) {
5133 return INVALID_OPERATION;
5134 }
François Gaffie53615e22015-03-19 09:24:12 +01005135 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005136 if (inputDesc == NULL) {
5137 return BAD_VALUE;
5138 }
5139 if (patchDesc != 0) {
5140 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5141 return BAD_VALUE;
5142 }
5143 }
François Gaffie11d30102018-11-02 16:09:09 +01005144 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005146 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005147 return BAD_VALUE;
5148 }
5149
jiabin66acc432024-02-06 00:57:36 +00005150 if (inputDesc->mProfile->getCompatibilityScore(
5151 DeviceVector(device),
5152 patch->sinks[0].sample_rate,
5153 nullptr, /*updatedSampleRate*/
5154 patch->sinks[0].format,
5155 nullptr, /*updatedFormat*/
5156 patch->sinks[0].channel_mask,
5157 nullptr, /*updatedChannelMask*/
5158 // FIXME for the parameter type,
5159 // and the NONE
5160 (audio_output_flags_t)
5161 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005162 return INVALID_OPERATION;
5163 }
5164 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005165 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005166 device->toString().c_str(), inputDesc->mIoHandle);
5167 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005168 index = mAudioPatches.indexOfKey(*handle);
5169 if (index >= 0) {
5170 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005171 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005172 }
5173 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005174 patchDesc->setUid(uid);
5175 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005176 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005177 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005178 return INVALID_OPERATION;
5179 }
5180 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5181 // device to device connection
5182 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005183 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 return BAD_VALUE;
5185 }
5186 }
François Gaffie11d30102018-11-02 16:09:09 +01005187 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005189 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005190 return BAD_VALUE;
5191 }
Eric Laurent874c42872014-08-08 15:13:39 -07005192
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 //update source and sink with our own data as the data passed in the patch may
5194 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005195 PatchBuilder patchBuilder;
5196 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005197
5198 // if first sink is to MSD, establish single MSD patch
5199 if (getMsdAudioOutDevices().contains(
5200 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5201 ALOGV("%s patching to MSD", __FUNCTION__);
5202 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5203 goto installPatch;
5204 }
5205
François Gaffieafd4cea2019-11-18 15:50:22 +01005206 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5207 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005208
Eric Laurent874c42872014-08-08 15:13:39 -07005209 for (size_t i = 0; i < patch->num_sinks; i++) {
5210 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005211 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005212 return INVALID_OPERATION;
5213 }
François Gaffie11d30102018-11-02 16:09:09 +01005214 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005215 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005216 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005217 return BAD_VALUE;
5218 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005219 audio_port_config sinkPortConfig = {};
5220 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5221 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005222
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005223 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5224 // volume management purpose (tracking activity)
5225 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5226 // in config XML to reach the sink so that is can be declared as available.
5227 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005228 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005229 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005230 // take care of dynamic routing for SwOutput selection,
5231 audio_attributes_t attributes = sourceDesc->attributes();
5232 audio_stream_type_t stream = sourceDesc->stream();
5233 audio_attributes_t resultAttr;
5234 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5235 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005236 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5237 config.channel_mask =
5238 (audio_channel_mask_get_representation(sourceMask)
5239 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5240 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005241 config.format = sourceDesc->config().format;
5242 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5243 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5244 bool isRequestedDeviceForExclusiveUse = false;
5245 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005246 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005247 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005248 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5249 &stream, sourceDesc->uid(), &config, &flags,
5250 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005251 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005252 if (output == AUDIO_IO_HANDLE_NONE) {
5253 ALOGV("%s no output for device %s",
5254 __FUNCTION__, sinkDevice->toString().c_str());
5255 return INVALID_OPERATION;
5256 }
5257 outputDesc = mOutputs.valueFor(output);
5258 if (outputDesc->isDuplicated()) {
5259 ALOGE("%s output is duplicated", __func__);
5260 return INVALID_OPERATION;
5261 }
François Gaffie7e39df22022-04-26 12:48:49 +02005262 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5263 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005264 } else {
5265 // Same for "raw patches" aka created from createAudioPatch API
5266 SortedVector<audio_io_handle_t> outputs =
5267 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5268 // if the sink device is reachable via an opened output stream, request to
5269 // go via this output stream by adding a second source to the patch
5270 // description
5271 output = selectOutput(outputs);
5272 if (output == AUDIO_IO_HANDLE_NONE) {
5273 ALOGE("%s no output available for internal patch sink", __func__);
5274 return INVALID_OPERATION;
5275 }
5276 outputDesc = mOutputs.valueFor(output);
5277 if (outputDesc->isDuplicated()) {
5278 ALOGV("%s output for device %s is duplicated",
5279 __func__, sinkDevice->toString().c_str());
5280 return INVALID_OPERATION;
5281 }
François Gaffie7e39df22022-04-26 12:48:49 +02005282 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005283 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005284 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005285 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005286 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005287 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005288 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5289 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005290 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5291 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005292 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005293 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005294 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005295 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005296 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005297 return INVALID_OPERATION;
5298 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005299 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005300 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005301 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005302 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005303 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005304 srcMixPortConfig.ext.mix.usecase.stream =
5305 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005306 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5307 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005308 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005309 }
Eric Laurent83b88082014-06-20 18:31:16 -07005310 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 }
5312 // TODO: check from routing capabilities in config file and other conflicting patches
5313
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005314installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005315 status_t status = installPatch(
5316 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005317 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005318 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005319 return INVALID_OPERATION;
5320 }
5321 } else {
5322 return BAD_VALUE;
5323 }
5324 } else {
5325 return BAD_VALUE;
5326 }
5327 return NO_ERROR;
5328}
5329
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005330status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005331{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005332 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005333 ssize_t index = mAudioPatches.indexOfKey(handle);
5334
5335 if (index < 0) {
5336 return BAD_VALUE;
5337 }
5338 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005339 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5340 __func__, mUidCached, patchDesc->getUid(), uid);
5341 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005342 return INVALID_OPERATION;
5343 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005344 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5345 for (size_t i = 0; i < mAudioSources.size(); i++) {
5346 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5347 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5348 portId = sourceDesc->portId();
5349 break;
5350 }
5351 }
5352 return portId != AUDIO_PORT_HANDLE_NONE ?
5353 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005354}
Eric Laurent6a94d692014-05-20 11:18:06 -07005355
François Gaffieafd4cea2019-11-18 15:50:22 +01005356status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005357 uint32_t delayMs,
5358 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005359{
5360 ALOGV("%s patch %d", __func__, handle);
5361 if (mAudioPatches.indexOfKey(handle) < 0) {
5362 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5363 return BAD_VALUE;
5364 }
5365 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005367 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005369 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005371 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005372 return BAD_VALUE;
5373 }
5374
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305375 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005376 getNewOutputDevices(outputDesc, true /*fromCache*/),
5377 true,
5378 0,
5379 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5381 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005382 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005383 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005384 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005385 return BAD_VALUE;
5386 }
5387 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005388 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005389 true,
5390 NULL);
5391 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005392 status_t status =
5393 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5394 ALOGV("%s patch panel returned %d patchHandle %d",
5395 __func__, status, patchDesc->getAfHandle());
5396 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005397 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005398 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005399 // SW or HW Bridge
5400 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5401 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005402 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005403 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5404 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5405 outputDesc = sourceDesc->swOutput().promote();
5406 }
5407 if (outputDesc == nullptr) {
5408 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5409 // releaseOutput has already called closeOutput in case of direct output
5410 return NO_ERROR;
5411 }
François Gaffie7e39df22022-04-26 12:48:49 +02005412 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005413 // While using a HwBridge, force reconsidering device only if not reusing an existing
5414 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005415 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005416 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5417 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5418 // Reconsider device only for cases:
5419 // 1 / Active Output
5420 // 2 / Inactive Output previously hosting HwBridge
5421 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5422 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5423 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305424 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005425 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5426 outputDesc->devices(),
5427 force,
5428 0,
5429 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 } else {
5431 return BAD_VALUE;
5432 }
5433 } else {
5434 return BAD_VALUE;
5435 }
5436 return NO_ERROR;
5437}
5438
5439status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5440 struct audio_patch *patches,
5441 unsigned int *generation)
5442{
François Gaffie53615e22015-03-19 09:24:12 +01005443 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 return BAD_VALUE;
5445 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005446 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005447 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005448}
5449
Eric Laurente1715a42014-05-20 11:30:42 -07005450status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005451{
Eric Laurente1715a42014-05-20 11:30:42 -07005452 ALOGV("setAudioPortConfig()");
5453
5454 if (config == NULL) {
5455 return BAD_VALUE;
5456 }
5457 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5458 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005459 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5460 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005461 }
5462
Eric Laurenta121f902014-06-03 13:32:54 -07005463 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005464 if (config->type == AUDIO_PORT_TYPE_MIX) {
5465 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005466 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005467 if (outputDesc == NULL) {
5468 return BAD_VALUE;
5469 }
Eric Laurent84c70242014-06-23 08:46:27 -07005470 ALOG_ASSERT(!outputDesc->isDuplicated(),
5471 "setAudioPortConfig() called on duplicated output %d",
5472 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005473 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005474 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005475 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005476 if (inputDesc == NULL) {
5477 return BAD_VALUE;
5478 }
Eric Laurenta121f902014-06-03 13:32:54 -07005479 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005480 } else {
5481 return BAD_VALUE;
5482 }
5483 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5484 sp<DeviceDescriptor> deviceDesc;
5485 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5486 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5487 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5488 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5489 } else {
5490 return BAD_VALUE;
5491 }
5492 if (deviceDesc == NULL) {
5493 return BAD_VALUE;
5494 }
Eric Laurenta121f902014-06-03 13:32:54 -07005495 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005496 } else {
5497 return BAD_VALUE;
5498 }
5499
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005500 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005501 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5502 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005503 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005504 audioPortConfig->toAudioPortConfig(&newConfig, config);
5505 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005506 }
Eric Laurenta121f902014-06-03 13:32:54 -07005507 if (status != NO_ERROR) {
5508 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005509 }
Eric Laurente1715a42014-05-20 11:30:42 -07005510
5511 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005512}
5513
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005514void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5515{
Eric Laurentd60560a2015-04-10 11:31:20 -07005516 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005517 clearAudioPatches(uid);
5518 clearSessionRoutes(uid);
5519}
5520
Eric Laurent6a94d692014-05-20 11:18:06 -07005521void AudioPolicyManager::clearAudioPatches(uid_t uid)
5522{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005523 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005524 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005525 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005526 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005527 }
5528 }
5529}
5530
François Gaffiec005e562018-11-06 15:04:49 +01005531void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005532{
François Gaffiec005e562018-11-06 15:04:49 +01005533 // Take the first attributes following the product strategy as it is used to retrieve the routed
5534 // device. All attributes wihin a strategy follows the same "routing strategy"
5535 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5536 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005537 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005538 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005539 for (size_t j = 0; j < mOutputs.size(); j++) {
5540 if (mOutputs.keyAt(j) == ouptutToSkip) {
5541 continue;
5542 }
5543 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005544 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005545 continue;
5546 }
5547 // If the default device for this strategy is on another output mix,
5548 // invalidate all tracks in this strategy to force re connection.
5549 // Otherwise select new device on the output mix.
5550 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005551 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005552 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005553 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5554 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5555 // If the device is using preferred mixer attributes, the output need to reopen
5556 // with default configuration when the new selected devices are different from
5557 // current routing devices.
5558 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5559 continue;
5560 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305561 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005562 }
5563 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005564 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005565}
5566
5567void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5568{
5569 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005570 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005571 for (size_t i = 0; i < mOutputs.size(); i++) {
5572 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005573 for (const auto& client : outputDesc->getClientIterable()) {
5574 if (client->hasPreferredDevice() && client->uid() == uid) {
5575 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005576 auto clientStrategy = client->strategy();
5577 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5578 end(affectedStrategies)) {
5579 continue;
5580 }
5581 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005582 }
5583 }
5584 }
5585 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005586 for (const auto& strategy : affectedStrategies) {
5587 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005588 }
5589
5590 // remove input routes associated with this uid
5591 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005592 for (size_t i = 0; i < mInputs.size(); i++) {
5593 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005594 for (const auto& client : inputDesc->getClientIterable()) {
5595 if (client->hasPreferredDevice() && client->uid() == uid) {
5596 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5597 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005598 }
5599 }
5600 }
5601 // reroute inputs if necessary
5602 SortedVector<audio_io_handle_t> inputsToClose;
5603 for (size_t i = 0; i < mInputs.size(); i++) {
5604 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005605 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005606 inputsToClose.add(inputDesc->mIoHandle);
5607 }
5608 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005609 for (const auto& input : inputsToClose) {
5610 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005611 }
5612}
5613
Eric Laurentd60560a2015-04-10 11:31:20 -07005614void AudioPolicyManager::clearAudioSources(uid_t uid)
5615{
5616 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005617 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5618 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005619 stopAudioSource(mAudioSources.keyAt(i));
5620 }
5621 }
5622}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005623
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005624status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5625 audio_io_handle_t *ioHandle,
5626 audio_devices_t *device)
5627{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005628 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5629 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005630 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005631 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5632 if (deviceDesc == nullptr) {
5633 return INVALID_OPERATION;
5634 }
5635 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005636
François Gaffiedf372692015-03-19 10:43:27 +01005637 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005638}
5639
Eric Laurentd60560a2015-04-10 11:31:20 -07005640status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005641 const audio_attributes_t *attributes,
5642 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005643 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005644{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005645 ALOGV("%s", __FUNCTION__);
5646 *portId = AUDIO_PORT_HANDLE_NONE;
5647
5648 if (source == NULL || attributes == NULL || portId == NULL) {
5649 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5650 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005651 return BAD_VALUE;
5652 }
5653
Eric Laurentd60560a2015-04-10 11:31:20 -07005654 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5655 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005656 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5657 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005658 return INVALID_OPERATION;
5659 }
5660
François Gaffie11d30102018-11-02 16:09:09 +01005661 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005662 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005663 String8(source->ext.device.address),
5664 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005665 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005666 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005667 return BAD_VALUE;
5668 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005669
jiabin4ef93452019-09-10 14:29:54 -07005670 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005671
François Gaffieaaac0fd2018-11-22 17:56:39 +01005672 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005673 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005674 mEngine->getStreamTypeForAttributes(*attributes),
5675 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005676 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005677
5678 status_t status = connectAudioSource(sourceDesc);
5679 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005680 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005681 }
5682 return status;
5683}
5684
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005685status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005686{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005687 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005688
5689 // make sure we only have one patch per source.
5690 disconnectAudioSource(sourceDesc);
5691
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005692 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005693 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5694 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5695 sourceDesc->srcDevice()->type(),
5696 String8(sourceDesc->srcDevice()->address().c_str()),
5697 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005698 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005699 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005700 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005701 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005702 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5703 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5704 return INVALID_OPERATION;
5705 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005706 PatchBuilder patchBuilder;
5707 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5708 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005709
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005710 return connectAudioSourceToSink(
5711 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005712}
5713
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005714status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005715{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005716 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5717 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005718 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005719 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005720 return BAD_VALUE;
5721 }
5722 status_t status = disconnectAudioSource(sourceDesc);
5723
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005724 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005725 return status;
5726}
5727
Andy Hung2ddee192015-12-18 17:34:44 -08005728status_t AudioPolicyManager::setMasterMono(bool mono)
5729{
5730 if (mMasterMono == mono) {
5731 return NO_ERROR;
5732 }
5733 mMasterMono = mono;
5734 // if enabling mono we close all offloaded devices, which will invalidate the
5735 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5736 // for recreating the new AudioTrack as non-offloaded PCM.
5737 //
5738 // If disabling mono, we leave all tracks as is: we don't know which clients
5739 // and tracks are able to be recreated as offloaded. The next "song" should
5740 // play back offloaded.
5741 if (mMasterMono) {
5742 Vector<audio_io_handle_t> offloaded;
5743 for (size_t i = 0; i < mOutputs.size(); ++i) {
5744 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5745 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5746 offloaded.push(desc->mIoHandle);
5747 }
5748 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005749 for (const auto& handle : offloaded) {
5750 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005751 }
5752 }
5753 // update master mono for all remaining outputs
5754 for (size_t i = 0; i < mOutputs.size(); ++i) {
5755 updateMono(mOutputs.keyAt(i));
5756 }
5757 return NO_ERROR;
5758}
5759
5760status_t AudioPolicyManager::getMasterMono(bool *mono)
5761{
5762 *mono = mMasterMono;
5763 return NO_ERROR;
5764}
5765
Eric Laurentac9cef52017-06-09 15:46:26 -07005766float AudioPolicyManager::getStreamVolumeDB(
5767 audio_stream_type_t stream, int index, audio_devices_t device)
5768{
jiabin9a3361e2019-10-01 09:38:30 -07005769 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005770}
5771
jiabin81772902018-04-02 17:52:27 -07005772status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5773 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005774 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005775{
Kriti Dang6537def2021-03-02 13:46:59 +01005776 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5777 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005778 return BAD_VALUE;
5779 }
Kriti Dang6537def2021-03-02 13:46:59 +01005780 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5781 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005782
5783 size_t formatsWritten = 0;
5784 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005785
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005786 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005787 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5788 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005789 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005790 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005791 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005792 bool formatEnabled = true;
5793 switch (forceUse) {
5794 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005795 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005796 break;
5797 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5798 formatEnabled = false;
5799 break;
5800 default: // AUTO or ALWAYS => true
5801 break;
jiabin81772902018-04-02 17:52:27 -07005802 }
5803 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5804 }
jiabin81772902018-04-02 17:52:27 -07005805 }
5806 return NO_ERROR;
5807}
5808
Kriti Dang6537def2021-03-02 13:46:59 +01005809status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5810 audio_format_t *surroundFormats) {
5811 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5812 return BAD_VALUE;
5813 }
5814 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5815 __func__, *numSurroundFormats, surroundFormats);
5816
5817 size_t formatsWritten = 0;
5818 size_t formatsMax = *numSurroundFormats;
5819 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5820
5821 // Return formats from all device profiles that have already been resolved by
5822 // checkOutputsForDevice().
5823 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5824 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5825 audio_devices_t deviceType = device->type();
5826 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5827 // returns formats reported by HDMI devices.
5828 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5829 continue;
5830 }
5831 // Formats reported by sink devices
5832 std::unordered_set<audio_format_t> formatset;
5833 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5834 formatset.insert(it->second.begin(), it->second.end());
5835 }
5836
5837 // Formats hard-coded in the in policy configuration file (if any).
5838 FormatVector encodedFormats = device->encodedFormats();
5839 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5840 // Filter the formats which are supported by the vendor hardware.
5841 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005842 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005843 formats.insert(*it);
5844 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005845 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005846 if (pair.second.count(*it) != 0) {
5847 formats.insert(pair.first);
5848 break;
5849 }
5850 }
5851 }
5852 }
5853 }
5854 *numSurroundFormats = formats.size();
5855 for (const auto& format: formats) {
5856 if (formatsWritten < formatsMax) {
5857 surroundFormats[formatsWritten++] = format;
5858 }
5859 }
5860 return NO_ERROR;
5861}
5862
jiabin81772902018-04-02 17:52:27 -07005863status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5864{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005865 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005866 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5867 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005868 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005869 return BAD_VALUE;
5870 }
5871
Mikhail Naganov100f0122018-11-29 11:22:16 -08005872 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5873 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005874 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005875 return INVALID_OPERATION;
5876 }
5877
Mikhail Naganov100f0122018-11-29 11:22:16 -08005878 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005879 return NO_ERROR;
5880 }
5881
Mikhail Naganov100f0122018-11-29 11:22:16 -08005882 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005883 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005884 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005885 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005886 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005887 }
5888 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005889 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005890 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005891 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005892 }
5893 }
5894
5895 sp<SwAudioOutputDescriptor> outputDesc;
5896 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005897 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5898 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005899 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5900 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005901 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005902 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005903 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5904 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5905 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005906 name.c_str(),
5907 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005908 if (status != NO_ERROR) {
5909 continue;
5910 }
5911 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5912 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5913 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005914 name.c_str(),
5915 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005916 profileUpdated |= (status == NO_ERROR);
5917 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005918 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005919 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005920 AUDIO_DEVICE_IN_HDMI);
5921 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5922 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005923 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005924 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005925 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5926 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5927 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005928 name.c_str(),
5929 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005930 if (status != NO_ERROR) {
5931 continue;
5932 }
5933 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5934 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5935 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005936 name.c_str(),
5937 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005938 profileUpdated |= (status == NO_ERROR);
5939 }
5940
jiabin81772902018-04-02 17:52:27 -07005941 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005942 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005943 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005944 }
5945
5946 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5947}
5948
Eric Laurent5ada82e2019-08-29 17:53:54 -07005949void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005950{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005951 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005952 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005953 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005954 }
5955}
5956
jiabin6012f912018-11-02 17:06:30 -07005957bool AudioPolicyManager::isHapticPlaybackSupported()
5958{
5959 for (const auto& hwModule : mHwModules) {
5960 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5961 for (const auto &outProfile : outputProfiles) {
5962 struct audio_port audioPort;
5963 outProfile->toAudioPort(&audioPort);
5964 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5965 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5966 return true;
5967 }
5968 }
5969 }
5970 }
5971 return false;
5972}
5973
Carter Hsu325a8eb2022-01-19 19:56:51 +08005974bool AudioPolicyManager::isUltrasoundSupported()
5975{
5976 bool hasUltrasoundOutput = false;
5977 bool hasUltrasoundInput = false;
5978 for (const auto& hwModule : mHwModules) {
5979 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5980 if (!hasUltrasoundOutput) {
5981 for (const auto &outProfile : outputProfiles) {
5982 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5983 hasUltrasoundOutput = true;
5984 break;
5985 }
5986 }
5987 }
5988
5989 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5990 if (!hasUltrasoundInput) {
5991 for (const auto &inputProfile : inputProfiles) {
5992 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5993 hasUltrasoundInput = true;
5994 break;
5995 }
5996 }
5997 }
5998
5999 if (hasUltrasoundOutput && hasUltrasoundInput)
6000 return true;
6001 }
6002 return false;
6003}
6004
Atneya Nair698f5ef2022-12-15 16:15:09 -08006005bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6006{
6007 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6008 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6009 for (const auto& hwModule : mHwModules) {
6010 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6011 for (const auto &inputProfile : inputProfiles) {
6012 if ((inputProfile->getFlags() & mask) == mask) {
6013 return true;
6014 }
6015 }
6016 }
6017 return false;
6018}
6019
Eric Laurent8340e672019-11-06 11:01:08 -08006020bool AudioPolicyManager::isCallScreenModeSupported()
6021{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006022 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006023}
6024
6025
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006026status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006027{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006028 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006029 if (!sourceDesc->isConnected()) {
6030 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6031 return NO_ERROR;
6032 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006033 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6034 if (swOutput != 0) {
6035 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006036 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006037 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006038 }
jiabinbce0c1d2020-10-05 11:20:18 -07006039 if (releaseOutput(sourceDesc->portId())) {
6040 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6041 // no need to release audio patch here but just return NO_ERROR.
6042 return NO_ERROR;
6043 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006044 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006045 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006046 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006047 // close Hwoutput and remove from mHwOutputs
6048 } else {
6049 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6050 }
6051 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006052 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006053 sourceDesc->disconnect();
6054 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006055}
6056
François Gaffiec005e562018-11-06 15:04:49 +01006057sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6058 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006059{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006060 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006061 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006062 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006063 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006064 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6065 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006066 source = sourceDesc;
6067 break;
6068 }
6069 }
6070 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006071}
6072
Eric Laurentb4f42a92022-01-17 17:37:31 +01006073bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006074 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006075 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006076{
6077 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6078 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006079 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006080 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006081 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6082 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6083 return false;
6084 }
6085 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6086 return false;
6087 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006088 }
6089
Eric Laurentd332bc82023-08-04 11:45:23 +02006090 // The caller can have the audio config criteria ignored by either passing a null ptr or
6091 // the AUDIO_CONFIG_INITIALIZER value.
6092 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006093 // some positional channel masks and PCM format and for stereo if low latency performance
6094 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006095
6096 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006097 static const bool stereo_spatialization_enabled =
6098 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006099 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006100 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006101 ? audio_channel_mask_contains_stereo(config->channel_mask)
6102 : audio_is_channel_mask_spatialized(config->channel_mask);
6103 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006104 return false;
6105 }
6106 if (!audio_is_linear_pcm(config->format)) {
6107 return false;
6108 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006109 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6110 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6111 return false;
6112 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006113 }
6114
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006115 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006116 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006117 if (profile == nullptr) {
6118 return false;
6119 }
6120
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006121 return true;
6122}
6123
Shunkai Yao57b93392024-04-26 04:12:21 +00006124// The Spatializer output is compatible with Haptic use cases if:
6125// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6126// with client if client haptic channel bits were set, or
6127// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6128// including the haptic bits or creating the HapticGenerator effect for same session.
6129bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6130 const audio_config_t* config, audio_session_t sessionId) const {
6131 const auto clientHapticChannel =
6132 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6133 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6134 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6135
6136 if (threadOutputHapticChannel) {
6137 // check format and sampleRate match if client haptic channel mask exist
6138 if (clientHapticChannel) {
6139 return mSpatializerOutput->getFormat() == config->format &&
6140 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6141 }
6142 return true;
6143 } else {
6144 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6145 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6146 // HapticGenerator effect for this session) are not supported.
6147 return clientHapticChannel == 0 &&
6148 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6149 }
6150}
6151
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006152void AudioPolicyManager::checkVirtualizerClientRoutes() {
6153 std::set<audio_stream_type_t> streamsToInvalidate;
6154 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006155 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6156 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006157 audio_attributes_t attr = client->attributes();
6158 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6159 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6160 audio_config_base_t clientConfig = client->config();
6161 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006162 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006163 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006164 streamsToInvalidate.insert(client->stream());
6165 }
6166 }
6167 }
6168
jiabinc44b3462022-12-08 12:52:31 -08006169 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006170}
6171
Eric Laurente191d1b2022-04-15 11:59:25 +02006172
6173bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6174 const sp<SwAudioOutputDescriptor>& outputDesc) {
6175 if (outputDesc->isDuplicated()) {
6176 return false;
6177 }
6178 DeviceVector devices = outputDesc->supportedDevices();
6179 for (size_t i = 0; i < mOutputs.size(); i++) {
6180 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6181 if (desc == outputDesc || desc->isDuplicated()) {
6182 continue;
6183 }
6184 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6185 if (!sharedDevices.isEmpty()
6186 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6187 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6188 return false;
6189 }
6190 }
6191 return true;
6192}
6193
6194
Eric Laurentfa0f6742021-08-17 18:39:44 +02006195status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006196 const audio_attributes_t *attr,
6197 audio_io_handle_t *output) {
6198 *output = AUDIO_IO_HANDLE_NONE;
6199
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006200 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6201 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6202 audio_config_t *configPtr = nullptr;
6203 audio_config_t config;
6204 if (mixerConfig != nullptr) {
6205 config = audio_config_initializer(mixerConfig);
6206 configPtr = &config;
6207 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006208 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006209 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006210 return BAD_VALUE;
6211 }
6212
6213 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006214 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006215 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006216 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006217 return BAD_VALUE;
6218 }
6219
Eric Laurente191d1b2022-04-15 11:59:25 +02006220 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006221 for (size_t i = 0; i < mOutputs.size(); i++) {
6222 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006223 if (!desc->isDuplicated()
6224 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6225 spatializerOutputs.push_back(desc);
6226 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006227 }
6228 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006229 mSpatializerOutput.clear();
6230 bool outputsChanged = false;
6231 for (const auto& desc : spatializerOutputs) {
6232 if (desc->mProfile == profile
6233 && (configPtr == nullptr
6234 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6235 mSpatializerOutput = desc;
6236 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6237 } else {
6238 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6239 " and devices %s", __func__, desc->mIoHandle,
6240 configPtr != nullptr ? configPtr->channel_mask : 0,
6241 devices.toString().c_str());
6242 closeOutput(desc->mIoHandle);
6243 outputsChanged = true;
6244 }
Eric Laurent39095982021-08-24 18:29:27 +02006245 }
6246
Eric Laurente191d1b2022-04-15 11:59:25 +02006247 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006248 sp<SwAudioOutputDescriptor> desc =
6249 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006250 if (desc != nullptr) {
6251 mSpatializerOutput = desc;
6252 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006253 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006254 }
6255
6256 checkVirtualizerClientRoutes();
6257
Eric Laurente191d1b2022-04-15 11:59:25 +02006258 if (outputsChanged) {
6259 mPreviousOutputs = mOutputs;
6260 mpClientInterface->onAudioPortListUpdate();
6261 }
6262
6263 if (mSpatializerOutput == nullptr) {
6264 ALOGV("%s could not open spatializer output with requested config", __func__);
6265 return BAD_VALUE;
6266 }
Eric Laurent39095982021-08-24 18:29:27 +02006267 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006268 ALOGV("%s returning new spatializer output %d", __func__, *output);
6269 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006270}
6271
Eric Laurentfa0f6742021-08-17 18:39:44 +02006272status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6273 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006274 return INVALID_OPERATION;
6275 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006276 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006277 return BAD_VALUE;
6278 }
Eric Laurent39095982021-08-24 18:29:27 +02006279
Eric Laurente191d1b2022-04-15 11:59:25 +02006280 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6281 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6282 closeOutput(mSpatializerOutput->mIoHandle);
6283 //from now on mSpatializerOutput is null
6284 checkVirtualizerClientRoutes();
6285 }
Eric Laurent39095982021-08-24 18:29:27 +02006286
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006287 return NO_ERROR;
6288}
6289
Eric Laurente552edb2014-03-10 17:42:56 -07006290// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006291// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006292// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006293uint32_t AudioPolicyManager::nextAudioPortGeneration()
6294{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006295 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006296}
6297
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006298AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006299 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006300 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006301 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006302 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006303 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006304 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006305 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006306 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006307 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006308 mAudioPortGeneration(1),
6309 mBeaconMuteRefCount(0),
6310 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006311 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006312 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006313 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006314 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006315{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006316}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006317
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006318status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006319 if (mEngine == nullptr) {
6320 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006321 }
6322 mEngine->setObserver(this);
6323 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006324 if (status != NO_ERROR) {
6325 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6326 return status;
6327 }
François Gaffie2110e042015-03-24 08:41:51 +01006328
jiabin29230182023-04-04 21:02:36 +00006329 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6330 // at the end of this function.
6331 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006332 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6333 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6334
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006335 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006336 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006337 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006338
Eric Laurent3a4311c2014-03-17 12:00:47 -07006339 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006340 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6341 defaultOutputDevice == nullptr ||
6342 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6343 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6344 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006345 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006346 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006347 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006348
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006349 // Silence ALOGV statements
6350 property_set("log.tag." LOG_TAG, "D");
6351
Eric Laurente552edb2014-03-10 17:42:56 -07006352 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006353 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006354}
6355
Eric Laurente0720872014-03-11 09:30:41 -07006356AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006357{
Eric Laurente552edb2014-03-10 17:42:56 -07006358 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006359 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006360 }
6361 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006362 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006363 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006364 mAvailableOutputDevices.clear();
6365 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006366 mOutputs.clear();
6367 mInputs.clear();
6368 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006369 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006370 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006371}
6372
Eric Laurente0720872014-03-11 09:30:41 -07006373status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006374{
Eric Laurent87ffa392015-05-22 10:32:38 -07006375 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006376}
6377
Eric Laurente552edb2014-03-10 17:42:56 -07006378// ---
6379
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006380void AudioPolicyManager::onNewAudioModulesAvailable()
6381{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006382 DeviceVector newDevices;
6383 onNewAudioModulesAvailableInt(&newDevices);
6384 if (!newDevices.empty()) {
6385 nextAudioPortGeneration();
6386 mpClientInterface->onAudioPortListUpdate();
6387 }
6388}
6389
6390void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6391{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006392 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006393 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6394 continue;
6395 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006396 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006397 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6398 handle != AUDIO_MODULE_HANDLE_NONE) {
6399 hwModule->setHandle(handle);
6400 } else {
6401 ALOGW("could not load HW module %s", hwModule->getName());
6402 continue;
6403 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006404 }
6405 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006406 // open all output streams needed to access attached devices.
6407 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006408 // This also validates mAvailableOutputDevices list
6409 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6410 if (!outProfile->canOpenNewIo()) {
6411 ALOGE("Invalid Output profile max open count %u for profile %s",
6412 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6413 continue;
6414 }
6415 if (!outProfile->hasSupportedDevices()) {
6416 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6417 continue;
6418 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006419 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6420 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006421 mTtsOutputAvailable = true;
6422 }
6423
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006424 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006425 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006426 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006427 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6428 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006429 } else {
6430 // choose first device present in profile's SupportedDevices also part of
6431 // mAvailableOutputDevices.
6432 if (availProfileDevices.isEmpty()) {
6433 continue;
6434 }
6435 supportedDevice = availProfileDevices.itemAt(0);
6436 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006437 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006438 continue;
6439 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306440
6441 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6442 && availProfileDevices.areAllDevicesAttached()) {
6443 ALOGV("%s skip opening output for mmap profile %s", __func__,
6444 outProfile->getTagName().c_str());
6445 continue;
6446 }
6447
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006448 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6449 mpClientInterface);
6450 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006451 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6452 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006453 AUDIO_STREAM_DEFAULT,
6454 AUDIO_OUTPUT_FLAG_NONE, &output);
6455 if (status != NO_ERROR) {
6456 ALOGW("Cannot open output stream for devices %s on hw module %s",
6457 supportedDevice->toString().c_str(), hwModule->getName());
6458 continue;
6459 }
6460 for (const auto &device : availProfileDevices) {
6461 // give a valid ID to an attached device once confirmed it is reachable
6462 if (!device->isAttached()) {
6463 device->attach(hwModule);
6464 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006465 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006466 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006467 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6468 }
6469 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006470 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006471 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6472 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006473 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006474 }
Eric Laurent39095982021-08-24 18:29:27 +02006475 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006476 outputDesc->close();
6477 } else {
6478 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306479 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006480 DeviceVector(supportedDevice),
6481 true,
6482 0,
6483 NULL);
6484 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006485 }
6486 // open input streams needed to access attached devices to validate
6487 // mAvailableInputDevices list
6488 for (const auto& inProfile : hwModule->getInputProfiles()) {
6489 if (!inProfile->canOpenNewIo()) {
6490 ALOGE("Invalid Input profile max open count %u for profile %s",
6491 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6492 continue;
6493 }
6494 if (!inProfile->hasSupportedDevices()) {
6495 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6496 continue;
6497 }
6498 // chose first device present in profile's SupportedDevices also part of
6499 // available input devices
6500 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006501 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006502 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006503 ALOGV("%s: Input device list is empty! for profile %s",
6504 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006505 continue;
6506 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306507
6508 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6509 && availProfileDevices.areAllDevicesAttached()) {
6510 ALOGV("%s skip opening input for mmap profile %s", __func__,
6511 inProfile->getTagName().c_str());
6512 continue;
6513 }
6514
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006515 sp<AudioInputDescriptor> inputDesc =
6516 new AudioInputDescriptor(inProfile, mpClientInterface);
6517
6518 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6519 status_t status = inputDesc->open(nullptr,
6520 availProfileDevices.itemAt(0),
6521 AUDIO_SOURCE_MIC,
Liana Kazanovaa31591a2024-07-11 20:09:39 +00006522 AUDIO_INPUT_FLAG_NONE,
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006523 &input);
6524 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306525 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6526 __func__, availProfileDevices.toString().c_str(),
6527 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006528 continue;
6529 }
6530 for (const auto &device : availProfileDevices) {
6531 // give a valid ID to an attached device once confirmed it is reachable
6532 if (!device->isAttached()) {
6533 device->attach(hwModule);
6534 device->importAudioPortAndPickAudioProfile(inProfile, true);
6535 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006536 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006537 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6538 }
6539 }
6540 inputDesc->close();
6541 }
6542 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006543
6544 // Check if spatializer outputs can be closed until used.
6545 // mOutputs vector never contains duplicated outputs at this point.
6546 std::vector<audio_io_handle_t> outputsClosed;
6547 for (size_t i = 0; i < mOutputs.size(); i++) {
6548 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6549 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6550 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6551 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006552 nextAudioPortGeneration();
6553 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6554 if (index >= 0) {
6555 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6556 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6557 patchDesc->getAfHandle(), 0);
6558 mAudioPatches.removeItemsAt(index);
6559 mpClientInterface->onAudioPatchListUpdate();
6560 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006561 desc->close();
6562 }
6563 }
6564 for (auto output : outputsClosed) {
6565 removeOutput(output);
6566 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006567}
6568
Eric Laurent98e38192018-02-15 18:31:53 -08006569void AudioPolicyManager::addOutput(audio_io_handle_t output,
6570 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006571{
Eric Laurent1c333e22014-05-20 10:48:17 -07006572 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006573 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006574 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006575 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006576 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006577}
6578
François Gaffie53615e22015-03-19 09:24:12 +01006579void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6580{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006581 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6582 ALOGV("%s: removing primary output", __func__);
6583 mPrimaryOutput = nullptr;
6584 }
François Gaffie53615e22015-03-19 09:24:12 +01006585 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006586 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006587}
6588
Eric Laurent98e38192018-02-15 18:31:53 -08006589void AudioPolicyManager::addInput(audio_io_handle_t input,
6590 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006591{
Eric Laurent1c333e22014-05-20 10:48:17 -07006592 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006593 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006594}
Eric Laurente552edb2014-03-10 17:42:56 -07006595
François Gaffie11d30102018-11-02 16:09:09 +01006596status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006597 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006598 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006599{
François Gaffie11d30102018-11-02 16:09:09 +01006600 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006601 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006602 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006603
François Gaffie11d30102018-11-02 16:09:09 +01006604 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006605 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006606 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006607 }
Eric Laurente552edb2014-03-10 17:42:56 -07006608
Eric Laurent3b73df72014-03-11 09:06:29 -07006609 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006610 // first call getAudioPort to get the supported attributes from the HAL
6611 struct audio_port_v7 port = {};
6612 device->toAudioPort(&port);
6613 status_t status = mpClientInterface->getAudioPort(&port);
6614 if (status == NO_ERROR) {
6615 device->importAudioPort(port);
6616 }
6617
6618 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006619 for (size_t i = 0; i < mOutputs.size(); i++) {
6620 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006621 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006622 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006623 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6624 mOutputs.keyAt(i), device->toString().c_str());
6625 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006626 }
6627 }
6628 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006629 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006630 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006631 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6632 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006633 if (profile->supportsDevice(device)) {
6634 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306635 ALOGV("%s(): adding profile %s from module %s",
6636 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006637 }
6638 }
6639 }
6640
Eric Laurent7b279bb2015-12-14 10:18:23 -08006641 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006642
Eric Laurente552edb2014-03-10 17:42:56 -07006643 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006644 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006645 return BAD_VALUE;
6646 }
6647
6648 // open outputs for matching profiles if needed. Direct outputs are also opened to
6649 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6650 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006651 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006652
6653 // nothing to do if one output is already opened for this profile
6654 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006655 for (j = 0; j < outputs.size(); j++) {
6656 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006657 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006658 // matching profile: save the sample rates, format and channel masks supported
6659 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006660 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006661 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006662 }
Eric Laurente552edb2014-03-10 17:42:56 -07006663 break;
6664 }
6665 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006666 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006667 continue;
6668 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306669 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6670 ALOGV("%s skip opening output for mmap profile %s",
6671 __func__, profile->getTagName().c_str());
6672 continue;
6673 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006674 if (!profile->canOpenNewIo()) {
6675 ALOGW("Max Output number %u already opened for this profile %s",
6676 profile->maxOpenCount, profile->getTagName().c_str());
6677 continue;
6678 }
6679
Eric Laurent83efe1c2017-07-09 16:51:08 -07006680 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006681 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006682 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6683 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006684 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006685 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006686 profiles.removeAt(profile_index);
6687 profile_index--;
6688 } else {
6689 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006690 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006691 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006692 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6693 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006694 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006695 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006696
François Gaffie11d30102018-11-02 16:09:09 +01006697 if (device_distinguishes_on_address(deviceType)) {
6698 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6699 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306700 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6701 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006702 }
Eric Laurente552edb2014-03-10 17:42:56 -07006703 ALOGV("checkOutputsForDevice(): adding output %d", output);
6704 }
6705 }
6706
6707 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006708 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006709 return BAD_VALUE;
6710 }
Eric Laurentd4692962014-05-05 18:13:44 -07006711 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006712 // check if one opened output is not needed any more after disconnecting one device
6713 for (size_t i = 0; i < mOutputs.size(); i++) {
6714 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006715 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006716 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006717 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006718 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006719 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006720 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006721 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6722 mOutputs.keyAt(i));
6723 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006724 }
Eric Laurente552edb2014-03-10 17:42:56 -07006725 }
6726 }
Eric Laurentd4692962014-05-05 18:13:44 -07006727 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006728 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006729 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6730 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006731 if (!profile->supportsDevice(device)) {
6732 continue;
6733 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306734 ALOGV("%s(): clearing direct output profile %s on module %s",
6735 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006736 profile->clearAudioProfiles();
6737 if (!profile->hasDynamicAudioProfile()) {
6738 continue;
6739 }
6740 // When a device is disconnected, if there is an IOProfile that contains dynamic
6741 // profiles and supports the disconnected device, call getAudioPort to repopulate
6742 // the capabilities of the devices that is supported by the IOProfile.
6743 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6744 if (supportedDevice == device ||
6745 !mAvailableOutputDevices.contains(supportedDevice)) {
6746 continue;
6747 }
6748 struct audio_port_v7 port;
6749 supportedDevice->toAudioPort(&port);
6750 status_t status = mpClientInterface->getAudioPort(&port);
6751 if (status == NO_ERROR) {
6752 supportedDevice->importAudioPort(port);
6753 }
Eric Laurente552edb2014-03-10 17:42:56 -07006754 }
6755 }
6756 }
6757 }
6758 return NO_ERROR;
6759}
6760
François Gaffie11d30102018-11-02 16:09:09 +01006761status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006762 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006763{
François Gaffie11d30102018-11-02 16:09:09 +01006764 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006765 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006766 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006767 }
6768
Eric Laurentd4692962014-05-05 18:13:44 -07006769 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006770 sp<AudioInputDescriptor> desc;
6771
jiabinbf5f4262023-04-12 21:48:34 +00006772 // first call getAudioPort to get the supported attributes from the HAL
6773 struct audio_port_v7 port = {};
6774 device->toAudioPort(&port);
6775 status_t status = mpClientInterface->getAudioPort(&port);
6776 if (status == NO_ERROR) {
6777 device->importAudioPort(port);
6778 }
6779
Eric Laurent0dd51852019-04-19 18:18:58 -07006780 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006781 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006782 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006783 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006784 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006785 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006786 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006787
François Gaffie11d30102018-11-02 16:09:09 +01006788 if (profile->supportsDevice(device)) {
6789 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306790 ALOGV("%s : adding profile %s from module %s", __func__,
6791 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006792 }
6793 }
6794 }
6795
Eric Laurent0dd51852019-04-19 18:18:58 -07006796 if (profiles.isEmpty()) {
6797 ALOGW("%s: No input profile available for device %s",
6798 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006799 return BAD_VALUE;
6800 }
6801
6802 // open inputs for matching profiles if needed. Direct inputs are also opened to
6803 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6804 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6805
Eric Laurent1c333e22014-05-20 10:48:17 -07006806 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006807
Eric Laurentd4692962014-05-05 18:13:44 -07006808 // nothing to do if one input is already opened for this profile
6809 size_t input_index;
6810 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6811 desc = mInputs.valueAt(input_index);
6812 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006813 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006814 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006815 }
Eric Laurentd4692962014-05-05 18:13:44 -07006816 break;
6817 }
6818 }
6819 if (input_index != mInputs.size()) {
6820 continue;
6821 }
6822
Jaideep Sharma44824a22024-06-18 16:32:34 +05306823 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6824 ALOGV("%s skip opening input for mmap profile %s",
6825 __func__, profile->getTagName().c_str());
6826 continue;
6827 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006828 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306829 ALOGW("%s Max Input number %u already opened for this profile %s",
6830 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08006831 continue;
6832 }
6833
Eric Laurentfe231122017-11-17 17:48:06 -08006834 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006835 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306836 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Liana Kazanovaa31591a2024-07-11 20:09:39 +00006837 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006838
Eric Laurentcf2c0212014-07-25 16:20:43 -07006839 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006840 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006841 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006842 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006843 mpClientInterface->setParameters(input, String8(param));
6844 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006845 }
jiabin12537fc2023-10-12 17:56:08 +00006846 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006847 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306848 ALOGW("%s direct input missing param for profile %s", __func__,
6849 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08006850 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006851 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006852 }
6853
Eric Laurent0dd51852019-04-19 18:18:58 -07006854 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006855 addInput(input, desc);
6856 }
6857 } // endif input != 0
6858
Eric Laurentcf2c0212014-07-25 16:20:43 -07006859 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306860 ALOGW("%s could not open input for device %s on profile %s", __func__,
6861 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006862 profiles.removeAt(profile_index);
6863 profile_index--;
6864 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006865 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006866 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006867 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306868 ALOGV("%s: adding input %d for profile %s", __func__,
6869 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006870
6871 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306872 ALOGV("%s: closing input %d for profile %s", __func__,
6873 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006874 closeInput(input);
6875 }
Eric Laurentd4692962014-05-05 18:13:44 -07006876 }
6877 } // end scan profiles
6878
6879 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006880 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006881 return BAD_VALUE;
6882 }
6883 } else {
6884 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006885 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006886 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006887 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006888 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006889 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006890 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006891 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306892 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
6893 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006894 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006895 }
6896 }
6897 }
6898 } // end disconnect
6899
6900 return NO_ERROR;
6901}
6902
6903
Eric Laurente0720872014-03-11 09:30:41 -07006904void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006905{
6906 ALOGV("closeOutput(%d)", output);
6907
François Gaffie1c878552018-11-22 16:53:21 +01006908 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6909 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006910 ALOGW("closeOutput() unknown output %d", output);
6911 return;
6912 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006913 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006914 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006915
Eric Laurente552edb2014-03-10 17:42:56 -07006916 // look for duplicated outputs connected to the output being removed.
6917 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006918 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6919 if (dupOutput->isDuplicated() &&
6920 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6921 sp<SwAudioOutputDescriptor> remainingOutput =
6922 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006923 // As all active tracks on duplicated output will be deleted,
6924 // and as they were also referenced on the other output, the reference
6925 // count for their stream type must be adjusted accordingly on
6926 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006927 const bool wasActive = remainingOutput->isActive();
6928 // Note: no-op on the closing output where all clients has already been set inactive
6929 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006930 // stop() will be a no op if the output is still active but is needed in case all
6931 // active streams refcounts where cleared above
6932 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006933 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006934 }
Eric Laurente552edb2014-03-10 17:42:56 -07006935 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6936 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6937
6938 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006939 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006940 }
6941 }
6942
Eric Laurent05b90f82014-08-27 15:32:29 -07006943 nextAudioPortGeneration();
6944
François Gaffie1c878552018-11-22 16:53:21 +01006945 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006946 if (index >= 0) {
6947 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006948 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6949 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006950 mAudioPatches.removeItemsAt(index);
6951 mpClientInterface->onAudioPatchListUpdate();
6952 }
6953
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006954 if (closingOutputWasActive) {
6955 closingOutput->stop();
6956 }
François Gaffie1c878552018-11-22 16:53:21 +01006957 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006958 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6959 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6960 for (const auto device : closingOutput->devices()) {
6961 device->setPreferredConfig(nullptr);
6962 }
6963 }
Eric Laurente552edb2014-03-10 17:42:56 -07006964
François Gaffie53615e22015-03-19 09:24:12 +01006965 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006966 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006967 if (closingOutput == mSpatializerOutput) {
6968 mSpatializerOutput.clear();
6969 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006970
6971 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6972 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006973 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006974 bool directOutputOpen = false;
6975 for (size_t i = 0; i < mOutputs.size(); i++) {
6976 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6977 directOutputOpen = true;
6978 break;
6979 }
6980 }
6981 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006982 ALOGV("no direct outputs open, reset MSD patches");
6983 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6984 // how output devices for patching are resolved. Avoid by caching and reusing the
6985 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6986 // devices to patch to. This may be complicated by the fact that devices may become
6987 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006988 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006989 }
6990 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006991}
6992
6993void AudioPolicyManager::closeInput(audio_io_handle_t input)
6994{
6995 ALOGV("closeInput(%d)", input);
6996
6997 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6998 if (inputDesc == NULL) {
6999 ALOGW("closeInput() unknown input %d", input);
7000 return;
7001 }
7002
Eric Laurent6a94d692014-05-20 11:18:06 -07007003 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007004
François Gaffie11d30102018-11-02 16:09:09 +01007005 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007006 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007007 if (index >= 0) {
7008 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007009 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7010 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007011 mAudioPatches.removeItemsAt(index);
7012 mpClientInterface->onAudioPatchListUpdate();
7013 }
7014
François Gaffie6ebbce02023-07-19 13:27:53 +02007015 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007016 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007017 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007018
François Gaffie11d30102018-11-02 16:09:09 +01007019 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7020 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007021 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007022 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007023 }
Eric Laurente552edb2014-03-10 17:42:56 -07007024}
7025
François Gaffie11d30102018-11-02 16:09:09 +01007026SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7027 const DeviceVector &devices,
7028 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007029{
7030 SortedVector<audio_io_handle_t> outputs;
7031
François Gaffie11d30102018-11-02 16:09:09 +01007032 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007033 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007034 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007035 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007036 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007037 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007038 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007039 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007040 outputs.add(openOutputs.keyAt(i));
7041 }
7042 }
7043 return outputs;
7044}
7045
Mikhail Naganov37977152018-07-11 15:54:44 -07007046void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7047{
7048 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7049 // output is suspended before any tracks are moved to it
7050 checkA2dpSuspend();
7051 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007052 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007053 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007054 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007055 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007056 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7057 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7058 // configuration changes will ultimately be rerouted correctly. We can still avoid
7059 // unnecessary rerouting by caching and reusing the arguments to
7060 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7061 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007062 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007063 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007064 // an event that changed routing likely occurred, inform upper layers
7065 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007066}
7067
François Gaffiec005e562018-11-06 15:04:49 +01007068bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7069 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007070{
François Gaffiec005e562018-11-06 15:04:49 +01007071 return mEngine->getProductStrategyForAttributes(lAttr) ==
7072 mEngine->getProductStrategyForAttributes(rAttr);
7073}
7074
Francois Gaffieff1eb522020-05-06 18:37:04 +02007075void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7076{
7077 for (size_t i = 0; i < mAudioSources.size(); i++) {
7078 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7079 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007080 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007081 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007082 connectAudioSource(sourceDesc);
7083 }
7084 }
7085}
7086
7087void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7088{
7089 for (size_t i = 0; i < mAudioSources.size(); i++) {
7090 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7091 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7092 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7093 disconnectAudioSource(sourceDesc);
7094 }
7095 }
7096}
7097
François Gaffiec005e562018-11-06 15:04:49 +01007098void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7099{
7100 auto psId = mEngine->getProductStrategyForAttributes(attr);
7101
7102 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7103 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007104
François Gaffie11d30102018-11-02 16:09:09 +01007105 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7106 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007107
Eric Laurentc209fe42020-06-05 18:11:23 -07007108 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007109 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007110 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007111 // take into account dynamic audio policies related changes: if a client is now associated
7112 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007113 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007114 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7115 if (desc->isDuplicated()) {
7116 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007117 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007118 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7119 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7120 continue;
7121 }
7122 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007123 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007124 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7125 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7126 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007127 if (status != OK) {
7128 continue;
7129 }
yucliuf4de36d2020-09-14 14:57:56 -07007130 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007131 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007132 maxLatency = desc->latency();
7133 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007134 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007135 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007136 }
7137 }
7138
Eric Laurent56ed8842022-11-15 16:04:41 +01007139 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007140 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7141 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007142 for (audio_io_handle_t srcOut : srcOutputs) {
7143 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007144 if (desc == nullptr) continue;
7145
7146 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007147 maxLatency = desc->latency();
7148 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007149
Eric Laurent56ed8842022-11-15 16:04:41 +01007150 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007151 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007152 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007153 // a client on a non direct outputs has necessarily a linear PCM format
7154 // so we can call selectOutput() safely
7155 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7156 client->flags(),
7157 client->config().format,
7158 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007159 client->config().sample_rate,
7160 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007161 if (newOutput != srcOut) {
7162 invalidate = true;
7163 break;
7164 }
7165 } else {
7166 sp<IOProfile> profile = getProfileForOutput(newDevices,
7167 client->config().sample_rate,
7168 client->config().format,
7169 client->config().channel_mask,
7170 client->flags(),
7171 true /* directOnly */);
7172 if (profile != desc->mProfile) {
7173 invalidate = true;
7174 break;
7175 }
7176 }
7177 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007178 // mute strategy while moving tracks from one output to another
7179 if (invalidate) {
7180 invalidatedOutputs.push_back(desc);
7181 if (desc->isStrategyActive(psId)) {
7182 setStrategyMute(psId, true, desc);
7183 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7184 newDevices.types());
7185 }
Eric Laurente552edb2014-03-10 17:42:56 -07007186 }
François Gaffiec005e562018-11-06 15:04:49 +01007187 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007188 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007189 connectAudioSource(source);
7190 }
Eric Laurente552edb2014-03-10 17:42:56 -07007191 }
7192
Eric Laurent56ed8842022-11-15 16:04:41 +01007193 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7194 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7195 std::to_string(srcOutputs[0]).c_str(),
7196 std::to_string(dstOutputs[0]).c_str());
7197
François Gaffiec005e562018-11-06 15:04:49 +01007198 // Move effects associated to this stream from previous output to new output
7199 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007200 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007201 }
François Gaffiec005e562018-11-06 15:04:49 +01007202 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007203 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007204 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007205 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007206 desc->setTracksInvalidatedStatusByStrategy(psId);
7207 }
Eric Laurente552edb2014-03-10 17:42:56 -07007208 }
7209 }
7210}
7211
Eric Laurente0720872014-03-11 09:30:41 -07007212void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007213{
François Gaffiec005e562018-11-06 15:04:49 +01007214 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7215 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7216 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007217 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007218 }
Eric Laurente552edb2014-03-10 17:42:56 -07007219}
7220
Kevin Rocard153f92d2018-12-18 18:33:28 -08007221void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007222 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007223 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007224 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007225 for (size_t i = 0; i < mOutputs.size(); i++) {
7226 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7227 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007228 sp<AudioPolicyMix> primaryMix;
7229 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007230 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007231 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7232 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7233 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007234 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7235 for (auto &secondaryMix : secondaryMixes) {
7236 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7237 if (outputDesc != nullptr &&
7238 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7239 secondaryDescs.push_back(outputDesc);
7240 }
7241 }
7242
jiabinc44b3462022-12-08 12:52:31 -08007243 if (status != OK &&
7244 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7245 // When it failed to query secondary output, only invalidate the client that is not
7246 // MMAP. The reason is that MMAP stream will not support secondary output.
7247 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007248 } else if (!std::equal(
7249 client->getSecondaryOutputs().begin(),
7250 client->getSecondaryOutputs().end(),
7251 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007252 if (!audio_is_linear_pcm(client->config().format)) {
7253 // If the format is not PCM, the tracks should be invalidated to get correct
7254 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007255 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007256 } else {
7257 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7258 std::vector<audio_io_handle_t> secondaryOutputIds;
7259 for (const auto &secondaryDesc: secondaryDescs) {
7260 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7261 weakSecondaryDescs.push_back(secondaryDesc);
7262 }
7263 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7264 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007265 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007266 }
7267 }
7268 }
jiabin10a03f12021-05-07 23:46:28 +00007269 if (!trackSecondaryOutputs.empty()) {
7270 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7271 }
jiabinc44b3462022-12-08 12:52:31 -08007272 if (!clientsToInvalidate.empty()) {
7273 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7274 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007275 }
7276}
7277
Eric Laurent2517af32020-11-25 15:31:27 +01007278bool AudioPolicyManager::isScoRequestedForComm() const {
7279 AudioDeviceTypeAddrVector devices;
7280 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7281 for (const auto &device : devices) {
7282 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7283 return true;
7284 }
7285 }
7286 return false;
7287}
7288
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007289bool AudioPolicyManager::isHearingAidUsedForComm() const {
7290 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7291 true /*fromCache*/);
7292 for (const auto &device : devices) {
7293 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7294 return true;
7295 }
7296 }
7297 return false;
7298}
7299
7300
Eric Laurente0720872014-03-11 09:30:41 -07007301void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007302{
François Gaffie53615e22015-03-19 09:24:12 +01007303 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007304 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007305 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007306 return;
7307 }
7308
Eric Laurent3a4311c2014-03-17 12:00:47 -07007309 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007310 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7311 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007312 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007313
7314 // if suspended, restore A2DP output if:
7315 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007316 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007317 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007318 //
Eric Laurentf732e072016-08-03 19:30:28 -07007319 // if not suspended, suspend A2DP output if:
7320 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007321 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007322 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007323 //
7324 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007325 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007326 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007327 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007328 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007329
7330 mpClientInterface->restoreOutput(a2dpOutput);
7331 mA2dpSuspended = false;
7332 }
7333 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007334 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007335 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007336 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007337 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007338
7339 mpClientInterface->suspendOutput(a2dpOutput);
7340 mA2dpSuspended = true;
7341 }
7342 }
7343}
7344
François Gaffie11d30102018-11-02 16:09:09 +01007345DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7346 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007347{
François Gaffiedb1755b2023-09-01 11:50:35 +02007348 if (outputDesc == nullptr) {
7349 return DeviceVector{};
7350 }
François Gaffie11d30102018-11-02 16:09:09 +01007351
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007352 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007353 if (index >= 0) {
7354 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007355 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007356 ALOGV("%s device %s forced by patch %d", __func__,
7357 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7358 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007359 }
7360 }
7361
Dean Wheatley514b4312020-06-17 21:45:00 +10007362 // Do not retrieve engine device for outputs through MSD
7363 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7364 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7365 return outputDesc->devices();
7366 }
7367
Eric Laurent97ac8712018-07-27 18:59:02 -07007368 // Honor explicit routing requests only if no client using default routing is active on this
7369 // input: a specific app can not force routing for other apps by setting a preferred device.
7370 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007371 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007372 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007373 if (device != nullptr) {
7374 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007375 }
7376
François Gaffiea807ef92018-11-05 10:44:33 +01007377 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7378 // of setForceUse / Default Bus device here
7379 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7380 if (device != nullptr) {
7381 return DeviceVector(device);
7382 }
7383
François Gaffiedb1755b2023-09-01 11:50:35 +02007384 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007385 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7386 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307387 auto hasStreamActive = [&](auto stream) {
7388 return hasStream(streams, stream) && isStreamActive(stream, 0);
7389 };
Eric Laurent484e9272018-06-07 17:29:23 -07007390
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307391 auto doGetOutputDevicesForVoice = [&]() {
7392 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007393 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307394 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007395 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7396 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307397 };
7398
7399 // With low-latency playing on speaker, music on WFD, when the first low-latency
7400 // output is stopped, getNewOutputDevices checks for a product strategy
7401 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007402 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307403 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7404 // stream is associated to the output descriptor.
7405 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7406 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7407 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7408 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007409 // Retrieval of devices for voice DL is done on primary output profile, cannot
7410 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007411 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007412 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7413 break;
7414 }
Eric Laurente552edb2014-03-10 17:42:56 -07007415 }
François Gaffiec005e562018-11-06 15:04:49 +01007416 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007417 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007418}
7419
François Gaffie11d30102018-11-02 16:09:09 +01007420sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7421 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007422{
François Gaffie11d30102018-11-02 16:09:09 +01007423 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007424
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007425 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007426 if (index >= 0) {
7427 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007428 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007429 ALOGV("getNewInputDevice() device %s forced by patch %d",
7430 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7431 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007432 }
7433 }
7434
Eric Laurent97ac8712018-07-27 18:59:02 -07007435 // Honor explicit routing requests only if no client using default routing is active on this
7436 // input: a specific app can not force routing for other apps by setting a preferred device.
7437 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007438 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7439 if (device != nullptr) {
7440 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007441 }
7442
Eric Laurentdc95a252018-04-12 12:46:56 -07007443 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007444 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007445 audio_attributes_t attributes;
7446 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007447 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007448 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7449 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007450 attributes = topClient->attributes();
7451 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007452 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007453 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007454 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7455 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007456 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007457 }
7458
Francois Gaffie716e1432019-01-14 16:58:59 +01007459 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7460 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007461 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007462 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007463 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007464 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007465
Eric Laurente552edb2014-03-10 17:42:56 -07007466 return device;
7467}
7468
Eric Laurent794fde22016-03-11 09:50:45 -08007469bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7470 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007471 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007472}
7473
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007474status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007475 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007476 if (devices == nullptr) {
7477 return BAD_VALUE;
7478 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007479
Andy Hung6d23c0f2022-02-16 09:37:15 -08007480 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007481 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7482 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007483 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007484 for (const auto& device : curDevices) {
7485 devices->push_back(device->getDeviceTypeAddr());
7486 }
7487 return NO_ERROR;
7488}
7489
Eric Laurente0720872014-03-11 09:30:41 -07007490void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007491 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007492 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007493 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007494 updateDevicesAndOutputs();
7495 break;
7496 default:
7497 break;
7498 }
7499}
7500
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007501uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007502
7503 // skip beacon mute management if a dedicated TTS output is available
7504 if (mTtsOutputAvailable) {
7505 return 0;
7506 }
7507
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007508 switch(event) {
7509 case STARTING_OUTPUT:
7510 mBeaconMuteRefCount++;
7511 break;
7512 case STOPPING_OUTPUT:
7513 if (mBeaconMuteRefCount > 0) {
7514 mBeaconMuteRefCount--;
7515 }
7516 break;
7517 case STARTING_BEACON:
7518 mBeaconPlayingRefCount++;
7519 break;
7520 case STOPPING_BEACON:
7521 if (mBeaconPlayingRefCount > 0) {
7522 mBeaconPlayingRefCount--;
7523 }
7524 break;
7525 }
7526
7527 if (mBeaconMuteRefCount > 0) {
7528 // any playback causes beacon to be muted
7529 return setBeaconMute(true);
7530 } else {
7531 // no other playback: unmute when beacon starts playing, mute when it stops
7532 return setBeaconMute(mBeaconPlayingRefCount == 0);
7533 }
7534}
7535
7536uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7537 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7538 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7539 // keep track of muted state to avoid repeating mute/unmute operations
7540 if (mBeaconMuted != mute) {
7541 // mute/unmute AUDIO_STREAM_TTS on all outputs
7542 ALOGV("\t muting %d", mute);
7543 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007544 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7545 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7546 ALOGV("\t no tts volume source available");
7547 return 0;
7548 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007549 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007550 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007551 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007552 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007553 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007554 maxLatency = latency;
7555 }
7556 }
7557 mBeaconMuted = mute;
7558 return maxLatency;
7559 }
7560 return 0;
7561}
7562
Eric Laurente0720872014-03-11 09:30:41 -07007563void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007564{
François Gaffiec005e562018-11-06 15:04:49 +01007565 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007566 mPreviousOutputs = mOutputs;
7567}
7568
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007569uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007570 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007571 uint32_t delayMs)
7572{
7573 // mute/unmute strategies using an incompatible device combination
7574 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7575 // if unmuting, unmute only after the specified delay
7576 if (outputDesc->isDuplicated()) {
7577 return 0;
7578 }
7579
7580 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007581 DeviceVector devices = outputDesc->devices();
7582 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007583
François Gaffiec005e562018-11-06 15:04:49 +01007584 auto productStrategies = mEngine->getOrderedProductStrategies();
7585 for (const auto &productStrategy : productStrategies) {
7586 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7587 DeviceVector curDevices =
7588 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7589 curDevices = curDevices.filter(outputDesc->supportedDevices());
7590 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007591 bool doMute = false;
7592
François Gaffiec005e562018-11-06 15:04:49 +01007593 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007594 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007595 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7596 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007597 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007598 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007599 }
Eric Laurent99401132014-05-07 19:48:15 -07007600 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007601 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007602 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007603 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007604 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007605 continue;
7606 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307607 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007608 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7609 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7610 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007611 if (mute) {
7612 // FIXME: should not need to double latency if volume could be applied
7613 // immediately by the audioflinger mixer. We must account for the delay
7614 // between now and the next time the audioflinger thread for this output
7615 // will process a buffer (which corresponds to one buffer size,
7616 // usually 1/2 or 1/4 of the latency).
7617 if (muteWaitMs < desc->latency() * 2) {
7618 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007619 }
7620 }
7621 }
7622 }
7623 }
7624 }
7625
Eric Laurent99401132014-05-07 19:48:15 -07007626 // temporary mute output if device selection changes to avoid volume bursts due to
7627 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007628 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007629 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007630
Eric Laurentdc462862016-07-19 12:29:53 -07007631 if (muteWaitMs < tempMuteWaitMs) {
7632 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007633 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007634
7635 // If recommended duration is defined, replace temporary mute duration to avoid
7636 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7637 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7638 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7639 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7640 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7641
François Gaffieaaac0fd2018-11-22 17:56:39 +01007642 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7643 // make sure that we do not start the temporary mute period too early in case of
7644 // delayed device change
7645 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7646 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007647 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007648 }
7649 }
7650
Eric Laurente552edb2014-03-10 17:42:56 -07007651 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7652 if (muteWaitMs > delayMs) {
7653 muteWaitMs -= delayMs;
7654 usleep(muteWaitMs * 1000);
7655 return muteWaitMs;
7656 }
7657 return 0;
7658}
7659
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307660uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7661 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007662 const DeviceVector &devices,
7663 bool force,
7664 int delayMs,
7665 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007666 bool requiresMuteCheck, bool requiresVolumeCheck,
7667 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007668{
jiabin3ff8d7d2022-12-13 06:27:44 +00007669 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307670 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7671 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7672 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007673 uint32_t muteWaitMs;
7674
7675 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307676 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007677 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307678 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007679 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007680 return muteWaitMs;
7681 }
Eric Laurente552edb2014-03-10 17:42:56 -07007682
7683 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007684 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007685 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007686 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007687
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307688 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7689 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007690
7691 if (!filteredDevices.isEmpty()) {
7692 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007693 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007694
7695 // if the outputs are not materially active, there is no need to mute.
7696 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007697 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007698 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307699 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7700 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007701 muteWaitMs = 0;
7702 }
Eric Laurente552edb2014-03-10 17:42:56 -07007703
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007704 bool outputRouted = outputDesc->isRouted();
7705
Eric Laurent79ea9582020-06-11 18:49:24 -07007706 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7707 // output profile or if new device is not supported AND previous device(s) is(are) still
7708 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007709 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307710 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7711 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007712 // restore previous device after evaluating strategy mute state
7713 outputDesc->setDevices(prevDevices);
7714 return muteWaitMs;
7715 }
7716
Eric Laurente552edb2014-03-10 17:42:56 -07007717 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007718 // the requested device is AUDIO_DEVICE_NONE
7719 // OR the requested device is the same as current device
7720 // AND force is not specified
7721 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007722 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007723 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307724 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7725 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7726 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007727 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307728 ALOGV("%s %s setting same device on routed output, force apply volumes",
7729 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007730 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7731 }
Eric Laurente552edb2014-03-10 17:42:56 -07007732 return muteWaitMs;
7733 }
7734
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307735 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7736 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007737
Eric Laurente552edb2014-03-10 17:42:56 -07007738 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007739 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007740 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007741 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007742 PatchBuilder patchBuilder;
7743 patchBuilder.addSource(outputDesc);
7744 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7745 for (const auto &filteredDevice : filteredDevices) {
7746 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007747 }
7748
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007749 // Add half reported latency to delayMs when muteWaitMs is null in order
7750 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007751 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7752 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7753 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007754 }
Eric Laurente552edb2014-03-10 17:42:56 -07007755
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007756 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7757 if (!skipMuteDelay) {
7758 // update stream volumes according to new device
7759 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7760 }
Eric Laurente552edb2014-03-10 17:42:56 -07007761
7762 return muteWaitMs;
7763}
7764
Eric Laurentc75307b2015-03-17 15:29:32 -07007765status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007766 int delayMs,
7767 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007768{
Eric Laurent6a94d692014-05-20 11:18:06 -07007769 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007770 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7771 return INVALID_OPERATION;
7772 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007773 if (patchHandle) {
7774 index = mAudioPatches.indexOfKey(*patchHandle);
7775 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007776 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007777 }
7778 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007779 return INVALID_OPERATION;
7780 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007781 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007782 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007783 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007784 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007785 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007786 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007787 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007788 return status;
7789}
7790
7791status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007792 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007793 bool force,
7794 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007795{
7796 status_t status = NO_ERROR;
7797
Eric Laurent1f2f2232014-06-02 12:01:23 -07007798 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007799 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7800 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007801
François Gaffie11d30102018-11-02 16:09:09 +01007802 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007803 PatchBuilder patchBuilder;
7804 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007805 // AUDIO_SOURCE_HOTWORD is for internal use only:
7806 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007807 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7808 auto result = usecase;
7809 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7810 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7811 }
7812 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007813 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007814 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007815 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007816 }
7817 }
7818 return status;
7819}
7820
Eric Laurent6a94d692014-05-20 11:18:06 -07007821status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7822 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007823{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007824 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007825 ssize_t index;
7826 if (patchHandle) {
7827 index = mAudioPatches.indexOfKey(*patchHandle);
7828 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007829 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007830 }
7831 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007832 return INVALID_OPERATION;
7833 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007834 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007835 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007836 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007837 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007838 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007839 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007840 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007841 return status;
7842}
7843
François Gaffie11d30102018-11-02 16:09:09 +01007844sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007845 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007846 audio_format_t& format,
7847 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007848 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007849{
7850 // Choose an input profile based on the requested capture parameters: select the first available
7851 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007852 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007853
Atneya Nair0f0a8032022-12-12 16:20:12 -08007854 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7855 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7856 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7857
7858 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007859
jiabin2fd710d2022-05-02 23:20:22 +00007860 for (;;) {
7861 sp<IOProfile> firstInexact = nullptr;
7862 uint32_t updatedSamplingRate = 0;
7863 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7864 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7865 for (const auto& hwModule : mHwModules) {
7866 for (const auto& profile : hwModule->getInputProfiles()) {
7867 // profile->log();
7868 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007869 if (profile->getCompatibilityScore(
7870 DeviceVector(device),
7871 samplingRate,
7872 &updatedSamplingRate,
7873 format,
7874 &updatedFormat,
7875 channelMask,
7876 &updatedChannelMask,
7877 // FIXME ugly cast
7878 (audio_output_flags_t) flags,
7879 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7880 samplingRate = updatedSamplingRate;
7881 format = updatedFormat;
7882 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007883 return profile;
7884 }
jiabin66acc432024-02-06 00:57:36 +00007885 if (firstInexact == nullptr
7886 && profile->getCompatibilityScore(
7887 DeviceVector(device),
7888 samplingRate,
7889 &updatedSamplingRate,
7890 format,
7891 &updatedFormat,
7892 channelMask,
7893 &updatedChannelMask,
7894 // FIXME ugly cast
7895 (audio_output_flags_t) flags,
7896 false /*exactMatchRequiredForInputFlags*/)
7897 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007898 firstInexact = profile;
7899 }
7900 }
7901 }
7902
7903 if (firstInexact != nullptr) {
7904 samplingRate = updatedSamplingRate;
7905 format = updatedFormat;
7906 channelMask = updatedChannelMask;
7907 return firstInexact;
7908 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7909 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7910 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7911 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7912 flags = AUDIO_INPUT_FLAG_NONE;
7913 } else { // fail
7914 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7915 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7916 samplingRate, format, channelMask, oriFlags);
7917 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007918 }
7919 }
jiabin2fd710d2022-05-02 23:20:22 +00007920
7921 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007922}
7923
François Gaffieaaac0fd2018-11-22 17:56:39 +01007924float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7925 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007926 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007927 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007928{
jiabin9a3361e2019-10-01 09:38:30 -07007929 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007930
7931 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7932 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7933 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7934 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007935 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7936 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7937 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7938 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7939 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena5300db62023-08-30 18:45:18 -07007940 // Verify that the current volume source is not the ringer volume to prevent recursively
7941 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7942 // to the same volume group.
7943 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007944 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7945 mOutputs.isActive(ringVolumeSrc, 0)) {
7946 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007947 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007948 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007949 }
7950
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007951 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007952 if ((volumeSource != callVolumeSrc && (isInCall() ||
7953 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007954 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007955 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7956 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007957 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7958 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7959 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007960 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007961 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007962 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007963 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007964 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007965 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007966 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7967 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7968 // programmatically muted.
7969 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7970 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7971 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007972 bool exemptFromCapping =
7973 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7974 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007975 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7976 volumeSource, volumeDb);
7977 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007978 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7979 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7980 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007981 }
7982 }
Eric Laurente552edb2014-03-10 17:42:56 -07007983 // if a headset is connected, apply the following rules to ring tones and notifications
7984 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007985 // - always attenuate notifications volume by 6dB
7986 // - attenuate ring tones volume by 6dB unless music is not playing and
7987 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007988 // - if music is playing, always limit the volume to current music volume,
7989 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007990 if (!Intersection(deviceTypes,
7991 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7992 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007993 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7994 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007995 ((volumeSource == alarmVolumeSrc ||
7996 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007997 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7998 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7999 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008000 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8001 curves.canBeMuted()) {
8002
Eric Laurente552edb2014-03-10 17:42:56 -07008003 // when the phone is ringing we must consider that music could have been paused just before
8004 // by the music application and behave as if music was active if the last music track was
8005 // just stopped
Oscar Azucena5300db62023-08-30 18:45:18 -07008006 // Verify that the current volume source is not the music volume to prevent recursively
8007 // calling to compute volume. This could happen in cases where music and
8008 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
8009 if (volumeSource != musicVolumeSrc &&
8010 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8011 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01008012 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008013 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008014 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8015 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008016 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008017 float musicVolDb = computeVolume(musicCurves,
8018 musicVolumeSrc,
8019 musicCurves.getVolumeIndex(musicDevice),
8020 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008021 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8022 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8023 if (volumeDb > minVolDb) {
8024 volumeDb = minVolDb;
8025 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008026 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008027 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8028 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008029 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8030 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8031 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8032 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008033 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008034 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008035 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8036 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008037 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8038 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008039 }
8040 }
jiabin9a3361e2019-10-01 09:38:30 -07008041 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008042 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008043 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008044 }
8045 }
8046
François Gaffie43c73442018-11-08 08:21:55 +01008047 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008048}
8049
Eric Laurent3839bc02018-07-10 18:33:34 -07008050int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008051 VolumeSource fromVolumeSource,
8052 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008053{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008054 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008055 return srcIndex;
8056 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008057 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8058 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008059 float minSrc = (float)srcCurves.getVolumeIndexMin();
8060 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8061 float minDst = (float)dstCurves.getVolumeIndexMin();
8062 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008063
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008064 // preserve mute request or correct range
8065 if (srcIndex < minSrc) {
8066 if (srcIndex == 0) {
8067 return 0;
8068 }
8069 srcIndex = minSrc;
8070 } else if (srcIndex > maxSrc) {
8071 srcIndex = maxSrc;
8072 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008073 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8074}
8075
François Gaffieaaac0fd2018-11-22 17:56:39 +01008076status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8077 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008078 int index,
8079 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008080 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008081 int delayMs,
8082 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008083{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008084 // do not change actual attributes volume if the attributes is muted
8085 if (outputDesc->isMuted(volumeSource)) {
8086 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8087 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008088 return NO_ERROR;
8089 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008090
Eric Laurent5baf07c2024-01-11 16:57:27 +00008091 bool isVoiceVolSrc;
8092 bool isBtScoVolSrc;
8093 if (!isVolumeConsistentForCalls(
8094 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008095 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008096 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008097 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008098 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008099
jiabin9a3361e2019-10-01 09:38:30 -07008100 if (deviceTypes.empty()) {
8101 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008102 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008103 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008104 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008105 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008106
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008107 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8108 ALOGE("invalid volume index range");
8109 return BAD_VALUE;
8110 }
8111
jiabin9a3361e2019-10-01 09:38:30 -07008112 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8113 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008114 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008115 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008116 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8117 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008118 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008119 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008120 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008121 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8122 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008123
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008124 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008125 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8126 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8127 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008128 }
Eric Laurente552edb2014-03-10 17:42:56 -07008129 return NO_ERROR;
8130}
8131
Eric Laurent5baf07c2024-01-11 16:57:27 +00008132void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008133 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008134 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008135 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008136 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008137 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008138 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8139 } else {
8140 voiceVolume = index == 0 ? 0.0 : 1.0;
8141 }
8142 if (voiceVolume != mLastVoiceVolume) {
8143 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8144 mLastVoiceVolume = voiceVolume;
8145 }
8146}
8147
8148bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8149 const DeviceTypeSet& deviceTypes,
8150 bool& isVoiceVolSrc,
8151 bool& isBtScoVolSrc,
8152 const char* caller) {
8153 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8154 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8155 const bool isScoRequested = isScoRequestedForComm();
8156 const bool isHAUsed = isHearingAidUsedForComm();
8157
8158 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8159 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8160
8161 if ((callVolSrc != btScoVolSrc) &&
8162 ((isVoiceVolSrc && isScoRequested) ||
8163 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8164 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8165 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8166 volumeSource, isScoRequested ? " " : " not ");
8167 return false;
8168 }
8169 return true;
8170}
8171
Eric Laurentc75307b2015-03-17 15:29:32 -07008172void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008173 const DeviceTypeSet& deviceTypes,
8174 int delayMs,
8175 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008176{
jiabincd510522020-01-22 09:40:55 -08008177 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008178 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8179 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8180 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008181 curves.getVolumeIndex(deviceTypes),
8182 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008183 }
8184}
8185
François Gaffiec005e562018-11-06 15:04:49 +01008186void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8187 bool on,
8188 const sp<AudioOutputDescriptor>& outputDesc,
8189 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008190 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008191{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008192 std::vector<VolumeSource> sourcesToMute;
8193 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8194 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8195 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008196 VolumeSource source = toVolumeSource(attributes, false);
8197 if ((source != VOLUME_SOURCE_NONE) &&
8198 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8199 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008200 sourcesToMute.push_back(source);
8201 }
Eric Laurente552edb2014-03-10 17:42:56 -07008202 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008203 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008204 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008205 }
8206
Eric Laurente552edb2014-03-10 17:42:56 -07008207}
8208
François Gaffieaaac0fd2018-11-22 17:56:39 +01008209void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8210 bool on,
8211 const sp<AudioOutputDescriptor>& outputDesc,
8212 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008213 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008214{
jiabin9a3361e2019-10-01 09:38:30 -07008215 if (deviceTypes.empty()) {
8216 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008217 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008218 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008219 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008220 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008221 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008222 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008223 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8224 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008225 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008226 }
8227 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008228 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8229 // ignored
8230 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008231 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008232 if (!outputDesc->isMuted(volumeSource)) {
8233 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008234 return;
8235 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008236 if (outputDesc->decMuteCount(volumeSource) == 0) {
8237 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008238 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008239 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008240 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008241 delayMs);
8242 }
8243 }
8244}
8245
François Gaffie53615e22015-03-19 09:24:12 +01008246bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8247{
François Gaffiec005e562018-11-06 15:04:49 +01008248 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008249 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8250 return true;
8251 }
8252
8253 // has known usage?
8254 switch (paa->usage) {
8255 case AUDIO_USAGE_UNKNOWN:
8256 case AUDIO_USAGE_MEDIA:
8257 case AUDIO_USAGE_VOICE_COMMUNICATION:
8258 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8259 case AUDIO_USAGE_ALARM:
8260 case AUDIO_USAGE_NOTIFICATION:
8261 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8262 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8263 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8264 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8265 case AUDIO_USAGE_NOTIFICATION_EVENT:
8266 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8267 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8268 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8269 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008270 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008271 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008272 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008273 case AUDIO_USAGE_EMERGENCY:
8274 case AUDIO_USAGE_SAFETY:
8275 case AUDIO_USAGE_VEHICLE_STATUS:
8276 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008277 break;
8278 default:
8279 return false;
8280 }
8281 return true;
8282}
8283
François Gaffie2110e042015-03-24 08:41:51 +01008284audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8285{
8286 return mEngine->getForceUse(usage);
8287}
8288
Eric Laurent96d1dda2022-03-14 17:14:19 +01008289bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008290 return isStateInCall(mEngine->getPhoneState());
8291}
8292
Eric Laurent96d1dda2022-03-14 17:14:19 +01008293bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008294 return is_state_in_call(state);
8295}
8296
Eric Laurentf9cccec2022-11-16 19:12:00 +01008297bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008298 audio_mode_t mode = mEngine->getPhoneState();
8299 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008300 || (mode == AUDIO_MODE_CALL_SCREEN)
8301 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008302}
8303
Eric Laurentf9cccec2022-11-16 19:12:00 +01008304bool AudioPolicyManager::isInCallOrScreening() const {
8305 audio_mode_t mode = mEngine->getPhoneState();
8306 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8307}
8308
Eric Laurentd60560a2015-04-10 11:31:20 -07008309void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8310{
8311 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008312 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008313 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008314 sourceDesc->sinkDevice()->equals(deviceDesc))
8315 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008316 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008317 }
8318 }
8319
8320 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8321 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8322 bool release = false;
8323 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8324 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8325 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8326 source->ext.device.type == deviceDesc->type()) {
8327 release = true;
8328 }
8329 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008330 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008331 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8332 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8333 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008334 sink->ext.device.type == deviceDesc->type() &&
8335 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8336 || strncmp(sink->ext.device.address, address,
8337 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008338 release = true;
8339 }
8340 }
8341 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008342 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8343 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008344 }
8345 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008346
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008347 mInputs.clearSessionRoutesForDevice(deviceDesc);
8348
Francois Gaffie716e1432019-01-14 16:58:59 +01008349 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008350}
8351
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008352void AudioPolicyManager::modifySurroundFormats(
8353 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008354 std::unordered_set<audio_format_t> enforcedSurround(
8355 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008356 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008357 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008358 allSurround.insert(pair.first);
8359 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8360 }
Phil Burk09bc4612016-02-24 15:58:15 -08008361
8362 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8363 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008364 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008365 // This is the resulting set of formats depending on the surround mode:
8366 // 'all surround' = allSurround
8367 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8368 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8369 // 'manual surround' = mManualSurroundFormats
8370 // AUTO: formats v 'enforced surround'
8371 // ALWAYS: formats v 'all surround' v 'enforced surround'
8372 // NEVER: formats ^ 'non-surround'
8373 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008374
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008375 std::unordered_set<audio_format_t> formatSet;
8376 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8377 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008378 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008379 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008380 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008381 formatSet.insert(*formatIter);
8382 }
8383 }
8384 } else {
8385 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8386 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008387 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008388
jiabin81772902018-04-02 17:52:27 -07008389 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008390 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008391 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8392 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8393 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008394 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008395 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8396 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8397 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008398 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008399 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008400 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008401 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008402 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008403 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008404}
8405
jiabin06e4bab2019-07-29 10:13:34 -07008406void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8407 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008408 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8409 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8410
8411 // If NEVER, then remove support for channelMasks > stereo.
8412 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008413 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8414 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008415 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008416 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008417 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008418 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008419 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008420 }
8421 }
jiabin81772902018-04-02 17:52:27 -07008422 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8423 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8424 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008425 bool supports5dot1 = false;
8426 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008427 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008428 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8429 supports5dot1 = true;
8430 break;
8431 }
8432 }
8433 // If not then add 5.1 support.
8434 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008435 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008436 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008437 }
Phil Burk09bc4612016-02-24 15:58:15 -08008438 }
8439}
8440
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008441void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008442 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008443 const sp<IOProfile>& profile) {
8444 if (!profile->hasDynamicAudioProfile()) {
8445 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008446 }
François Gaffie112b0af2015-11-19 16:13:25 +01008447
jiabin12537fc2023-10-12 17:56:08 +00008448 audio_port_v7 devicePort;
8449 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008450
jiabin12537fc2023-10-12 17:56:08 +00008451 audio_port_v7 mixPort;
8452 profile->toAudioPort(&mixPort);
8453 mixPort.ext.mix.handle = ioHandle;
8454
8455 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8456 if (status != NO_ERROR) {
8457 ALOGE("%s failed to query the attributes of the mix port", __func__);
8458 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008459 }
jiabin12537fc2023-10-12 17:56:08 +00008460
8461 std::set<audio_format_t> supportedFormats;
8462 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8463 supportedFormats.insert(mixPort.audio_profiles[i].format);
8464 }
8465 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8466 mReportedFormatsMap[devDesc] = formats;
8467
8468 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8469 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8470 modifySurroundFormats(devDesc, &formats);
8471 size_t modifiedNumProfiles = 0;
8472 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8473 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8474 formats.end()) {
8475 // Skip the format that is not present after modifying surround formats.
8476 continue;
8477 }
8478 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8479 sizeof(struct audio_profile));
8480 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8481 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8482 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8483 modifySurroundChannelMasks(&channels);
8484 std::copy(channels.begin(), channels.end(),
8485 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8486 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8487 }
8488 mixPort.num_audio_profiles = modifiedNumProfiles;
8489 }
8490 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008491}
Eric Laurentd60560a2015-04-10 11:31:20 -07008492
Mikhail Naganovdc769682018-05-04 15:34:08 -07008493status_t AudioPolicyManager::installPatch(const char *caller,
8494 audio_patch_handle_t *patchHandle,
8495 AudioIODescriptorInterface *ioDescriptor,
8496 const struct audio_patch *patch,
8497 int delayMs)
8498{
8499 ssize_t index = mAudioPatches.indexOfKey(
8500 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8501 *patchHandle : ioDescriptor->getPatchHandle());
8502 sp<AudioPatch> patchDesc;
8503 status_t status = installPatch(
8504 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8505 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008506 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008507 }
8508 return status;
8509}
8510
8511status_t AudioPolicyManager::installPatch(const char *caller,
8512 ssize_t index,
8513 audio_patch_handle_t *patchHandle,
8514 const struct audio_patch *patch,
8515 int delayMs,
8516 uid_t uid,
8517 sp<AudioPatch> *patchDescPtr)
8518{
8519 sp<AudioPatch> patchDesc;
8520 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8521 if (index >= 0) {
8522 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008523 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008524 }
8525
8526 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8527 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8528 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8529 if (status == NO_ERROR) {
8530 if (index < 0) {
8531 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008532 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008533 } else {
8534 patchDesc->mPatch = *patch;
8535 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008536 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008537 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008538 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008539 }
8540 nextAudioPortGeneration();
8541 mpClientInterface->onAudioPatchListUpdate();
8542 }
8543 if (patchDescPtr) *patchDescPtr = patchDesc;
8544 return status;
8545}
8546
jiabinbce0c1d2020-10-05 11:20:18 -07008547bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8548{
8549 const TrackClientVector activeClients = output->getActiveClients();
8550 if (activeClients.empty()) {
8551 return true;
8552 }
8553 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8554 if (index < 0) {
8555 ALOGE("%s, no audio patch found while there are active clients on output %d",
8556 __func__, output->getId());
8557 return false;
8558 }
8559 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8560 DeviceVector routedDevices;
8561 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8562 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8563 patchDesc->mPatch.sinks[i].id);
8564 if (device == nullptr) {
8565 ALOGE("%s, no audio device found with id(%d)",
8566 __func__, patchDesc->mPatch.sinks[i].id);
8567 return false;
8568 }
8569 routedDevices.add(device);
8570 }
8571 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008572 if (client->isInvalid()) {
8573 // No need to take care about invalidated clients.
8574 continue;
8575 }
jiabinbce0c1d2020-10-05 11:20:18 -07008576 sp<DeviceDescriptor> preferredDevice =
8577 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8578 if (mEngine->getOutputDevicesForAttributes(
8579 client->attributes(), preferredDevice, false) == routedDevices) {
8580 return false;
8581 }
8582 }
8583 return true;
8584}
8585
8586sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008587 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008588 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8589 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008590{
8591 for (const auto& device : devices) {
8592 // TODO: This should be checking if the profile supports the device combo.
8593 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008594 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8595 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008596 return nullptr;
8597 }
8598 }
8599 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8600 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008601 status_t status = desc->open(halConfig, mixerConfig, devices,
8602 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008603 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008604 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008605 return nullptr;
8606 }
jiabin14b50cc2023-12-13 19:01:52 +00008607 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8608 auto portConfig = desc->getConfig();
8609 for (const auto& device : devices) {
8610 device->setPreferredConfig(&portConfig);
8611 }
8612 }
jiabinbce0c1d2020-10-05 11:20:18 -07008613
8614 // Here is where the out_set_parameters() for card & device gets called
8615 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8616 const audio_devices_t deviceType = device->type();
8617 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008618 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008619 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8620 mpClientInterface->setParameters(output, String8(param));
8621 free(param);
8622 }
jiabin12537fc2023-10-12 17:56:08 +00008623 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008624 if (!profile->hasValidAudioProfile()) {
8625 ALOGW("%s() missing param", __func__);
8626 desc->close();
8627 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008628 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8629 // Reopen the output with the best audio profile picked by APM when the profile supports
8630 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008631 desc->close();
8632 output = AUDIO_IO_HANDLE_NONE;
8633 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8634 profile->pickAudioProfile(
8635 config.sample_rate, config.channel_mask, config.format);
8636 config.offload_info.sample_rate = config.sample_rate;
8637 config.offload_info.channel_mask = config.channel_mask;
8638 config.offload_info.format = config.format;
8639
jiabina84c3d32022-12-02 18:59:55 +00008640 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008641 if (status != NO_ERROR) {
8642 return nullptr;
8643 }
8644 }
8645
8646 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008647
baek.kim -61c20122022-07-27 10:05:32 +00008648 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8649 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8650
jiabinbce0c1d2020-10-05 11:20:18 -07008651 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8652 sp<AudioPolicyMix> policyMix;
8653 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8654 policyMix->setOutput(desc);
8655 desc->mPolicyMix = policyMix;
8656 } else {
8657 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008658 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008659 }
8660
baek.kim -61c20122022-07-27 10:05:32 +00008661 } else if (hasPrimaryOutput() && speaker != nullptr
8662 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008663 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8664 // no duplicated output for:
8665 // - direct outputs
8666 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008667 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008668 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8669
8670 //TODO: configure audio effect output stage here
8671
8672 // open a duplicating output thread for the new output and the primary output
8673 sp<SwAudioOutputDescriptor> dupOutputDesc =
8674 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8675 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8676 if (status == NO_ERROR) {
8677 // add duplicated output descriptor
8678 addOutput(duplicatedOutput, dupOutputDesc);
8679 } else {
8680 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8681 mPrimaryOutput->mIoHandle, output);
8682 desc->close();
8683 removeOutput(output);
8684 nextAudioPortGeneration();
8685 return nullptr;
8686 }
8687 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008688 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8689 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8690 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008691 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008692 }
jiabinbce0c1d2020-10-05 11:20:18 -07008693 return desc;
8694}
8695
jiabinf1c73972022-04-14 16:28:52 -07008696status_t AudioPolicyManager::getDevicesForAttributes(
8697 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8698 // Devices are determined in the following precedence:
8699 //
8700 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8701 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8702 //
8703 // If no such dynamic policy then
8704 // 2) Devices containing an active client using setPreferredDevice
8705 // with same strategy as the attributes.
8706 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8707 //
8708 // If no corresponding active client with setPreferredDevice then
8709 // 3) Devices associated with the strategy determined by the attributes
8710 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8711 //
8712 // See related getOutputForAttrInt().
8713
8714 // check dynamic policies but only for primary descriptors (secondary not used for audible
8715 // audio routing, only used for duplication for playback capture)
8716 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008717 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008718 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008719 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8720 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8721 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008722 if (status != OK) {
8723 return status;
8724 }
8725
8726 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8727 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8728 // as they are unaffected by device/stream volume
8729 // (per SwAudioOutputDescriptor::isFixedVolume()).
8730 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8731 ) {
8732 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8733 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8734 devices.add(deviceDesc);
8735 } else {
8736 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8737 // which selects setPreferredDevice if active. This means forVolume call
8738 // will take an active setPreferredDevice, if such exists.
8739
8740 devices = mEngine->getOutputDevicesForAttributes(
8741 attr, nullptr /* preferredDevice */, false /* fromCache */);
8742 }
8743
8744 if (forVolume) {
8745 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8746 // for single volume control in AudioService (such relationship should exist if
8747 // SPEAKER_SAFE is present).
8748 //
8749 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8750 DeviceVector speakerSafeDevices =
8751 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8752 if (!speakerSafeDevices.isEmpty()) {
8753 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8754 devices.remove(speakerSafeDevices);
8755 }
8756 }
8757
8758 return NO_ERROR;
8759}
8760
8761status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8762 AudioProfileVector& audioProfiles,
8763 uint32_t flags,
8764 bool isInput) {
8765 for (const auto& hwModule : mHwModules) {
8766 // the MSD module checks for different conditions
8767 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8768 continue;
8769 }
8770 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8771 : hwModule->getOutputProfiles();
8772 for (const auto& profile : ioProfiles) {
8773 if (!profile->areAllDevicesSupported(devices) ||
8774 !profile->isCompatibleProfileForFlags(
8775 flags, false /*exactMatchRequiredForInputFlags*/)) {
8776 continue;
8777 }
8778 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8779 }
8780 }
8781
8782 if (!isInput) {
8783 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8784 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8785 if (msdModule != nullptr) {
8786 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8787 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8788 for (const auto &profile: msdModule->getOutputProfiles()) {
8789 if (!profile->asAudioPort()->isDirectOutput()) {
8790 continue;
8791 }
8792 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8793 }
8794 } else {
8795 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8796 }
8797 }
8798 }
8799
8800 return NO_ERROR;
8801}
8802
jiabin3ff8d7d2022-12-13 06:27:44 +00008803sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8804 const audio_config_t *config,
8805 audio_output_flags_t flags,
8806 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008807 closeOutput(outputDesc->mIoHandle);
8808 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8809 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8810 if (preferredOutput == nullptr) {
8811 ALOGE("%s failed to reopen output device=%d, caller=%s",
8812 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008813 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008814 return preferredOutput;
8815}
8816
8817void AudioPolicyManager::reopenOutputsWithDevices(
8818 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8819 for (const auto& [output, devices] : outputsToReopen) {
8820 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8821 closeOutput(output);
8822 openOutputWithProfileAndDevice(desc->mProfile, devices);
8823 }
jiabina84c3d32022-12-02 18:59:55 +00008824}
8825
jiabinc44b3462022-12-08 12:52:31 -08008826PortHandleVector AudioPolicyManager::getClientsForStream(
8827 audio_stream_type_t streamType) const {
8828 PortHandleVector clients;
8829 for (size_t i = 0; i < mOutputs.size(); ++i) {
8830 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8831 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8832 }
8833 return clients;
8834}
8835
8836void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8837 PortHandleVector clients;
8838 for (auto stream : streams) {
8839 PortHandleVector clientsForStream = getClientsForStream(stream);
8840 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8841 }
8842 mpClientInterface->invalidateTracks(clients);
8843}
8844
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008845} // namespace android