blob: 3318f8e4b51a38e56fdc28e6f6db3e615abe8ef8 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700377 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700378 } // end if is output device
379
Eric Laurente552edb2014-03-10 17:42:56 -0700380 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700381 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100382 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700383 switch (state)
384 {
385 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700386 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100388 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700389 return INVALID_OPERATION;
390 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700391
392 if (mAvailableInputDevices.add(device) < 0) {
393 return NO_MEMORY;
394 }
395
François Gaffie44481e72016-04-20 07:49:57 +0200396 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
397 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700399 // Propagate device availability to Engine
400 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200401
Eric Laurent0dd51852019-04-19 18:18:58 -0700402 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700403 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
404
Eric Laurent0dd51852019-04-19 18:18:58 -0700405 mAvailableInputDevices.remove(device);
406
jiabinc0048632023-04-27 22:04:31 +0000407 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100408
409 mHwModules.cleanUpForDevice(device);
410
Eric Laurentd4692962014-05-05 18:13:44 -0700411 return INVALID_OPERATION;
412 }
413
Eric Laurentd4692962014-05-05 18:13:44 -0700414 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700415
416 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700417 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700418 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700420 return INVALID_OPERATION;
421 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700422
François Gaffie11d30102018-11-02 16:09:09 +0100423 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700424
jiabinc0048632023-04-27 22:04:31 +0000425 // Notify the HAL to prepare to disconnect device
426 broadcastDeviceConnectionState(
427 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700428
François Gaffie11d30102018-11-02 16:09:09 +0100429 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700430
431 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100432
jiabinc0048632023-04-27 22:04:31 +0000433 // Set Disconnect to HALs
434 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
435
Kriti Dangef6be8f2020-11-05 11:58:19 +0100436 // remove device from mReportedFormatsMap cache
437 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700438
439 // Propagate device availability to Engine
440 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700441 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700442
443 default:
François Gaffie11d30102018-11-02 16:09:09 +0100444 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700445 return BAD_VALUE;
446 }
447
Eric Laurent0dd51852019-04-19 18:18:58 -0700448 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700449 // As the input device list can impact the output device selection, update
450 // getDeviceForStrategy() cache
451 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700452
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100453 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200454 // Reconnect Audio Source
455 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
456 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
457 checkAudioSourceForAttributes(attributes);
458 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700459 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100460 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700461 }
462
Eric Laurentb52c1522014-05-20 11:27:36 -0700463 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700464 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700465 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700466
François Gaffie11d30102018-11-02 16:09:09 +0100467 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700468 return BAD_VALUE;
469}
470
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100471status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
472 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800473 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700474 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
475 devDescr->setName(device_name);
476 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100477}
478
Eric Laurent736a1022019-03-27 18:28:46 -0700479void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
480 audio_policy_dev_state_t state) {
481
482 // the Engine does not have to know about remote submix devices used by dynamic audio policies
483 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
484 return;
485 }
486 mEngine->setDeviceConnectionState(device, state);
487}
488
489
Eric Laurente0720872014-03-11 09:30:41 -0700490audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100491 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700492{
Eric Laurent634b7142016-04-20 13:48:02 -0700493 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800494 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
495 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700496 (strlen(device_address) != 0)/*matchAddress*/);
497
498 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100499 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700500 device, device_address);
501 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
502 }
François Gaffie53615e22015-03-19 09:24:12 +0100503
Eric Laurent3a4311c2014-03-17 12:00:47 -0700504 DeviceVector *deviceVector;
505
Eric Laurente552edb2014-03-10 17:42:56 -0700506 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700507 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700508 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700509 deviceVector = &mAvailableInputDevices;
510 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100511 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700512 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700513 }
Eric Laurent634b7142016-04-20 13:48:02 -0700514
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800515 return (deviceVector->getDevice(
516 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800518}
519
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
521 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 const char *device_name,
523 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
526 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800528 // connect/disconnect only 1 device at a time
529 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
530
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700532 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800534 // Nothing to do: device is not connected
535 return NO_ERROR;
536 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700539 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800540 // configure codecs.
541 // Handle two specific cases by sending a set parameter to
542 // configure A2DP codecs. No need to toggle device state.
543 // Case 1: A2DP active device switches from primary to primary
544 // module
545 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100546 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700547 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800548 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
549 if (availablePrimaryOutputDevices().contains(devDesc) &&
550 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100551 bool isA2dp = audio_is_a2dp_out_device(device);
552 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
553 : String8(AudioParameter::keyReconfigLeSupported);
554 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800555 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100556 int isReconfigSupported;
557 repliedParameters.getInt(supportKey, isReconfigSupported);
558 if (isReconfigSupported) {
559 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
560 : String8(AudioParameter::keyReconfigLe);
561 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800562 param.add(key, String8("true"));
563 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
564 devDesc->setEncodedFormat(encodedFormat);
565 return NO_ERROR;
566 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700567 }
568 }
cnx421bd2dcc42020-07-11 14:58:44 +0800569 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000570 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800571 for (size_t i = 0; i < mOutputs.size(); i++) {
572 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000573 // mute media strategies to avoid sending the music tail into
574 // the earpiece or headset.
575 if (desc->isStrategyActive(musicStrategy)) {
576 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
577 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
578 tempRecommendedMuteDuration : desc->latency() * 4;
579 if (muteWaitMs < tempMuteDurationMs) {
580 muteWaitMs = tempMuteDurationMs;
581 }
582 }
cnx421bd2dcc42020-07-11 14:58:44 +0800583 setStrategyMute(musicStrategy, true, desc);
584 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
585 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
586 nullptr, true /*fromCache*/).types());
587 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000588 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
589 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
590 // happens after the actual device switch.
591 if (muteWaitMs > 0) {
592 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
593 usleep(muteWaitMs * 1000);
594 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800595 // Toggle the device state: UNAVAILABLE -> AVAILABLE
596 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100597 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800598 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800599 device_address, device_name,
600 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800601 if (status != NO_ERROR) {
602 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
603 status);
604 return status;
605 }
606
607 status = setDeviceConnectionState(device,
608 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800609 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800610 if (status != NO_ERROR) {
611 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
612 status);
613 return status;
614 }
615
616 return NO_ERROR;
617}
618
Pattydd807582021-11-04 21:01:03 +0800619status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
620 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800621{
Pattydd807582021-11-04 21:01:03 +0800622 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800623 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800624 std::unordered_set<audio_format_t> formatSet;
625 sp<HwModule> primaryModule =
626 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700627 if (primaryModule == nullptr) {
628 ALOGE("%s() unable to get primary module", __func__);
629 return NO_INIT;
630 }
Pattydd807582021-11-04 21:01:03 +0800631
632 DeviceTypeSet audioDeviceSet;
633
634 switch(device) {
635 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
636 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
637 break;
638 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800639 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
640 break;
641 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
642 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800643 break;
644 default:
645 ALOGE("%s() device type 0x%08x not supported", __func__, device);
646 return BAD_VALUE;
647 }
648
jiabin9a3361e2019-10-01 09:38:30 -0700649 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800650 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800651 for (const auto& device : declaredDevices) {
652 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800653 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800654 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800655 return status;
656}
657
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100658DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
659{
660 DeviceVector rxSinkdevices{};
661 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
662 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
663 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
664 auto rxSinkDevice = rxSinkdevices.itemAt(0);
665 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
666 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
667 // retrieve Rx Source device descriptor
668 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
669 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
670
671 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
672 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
673 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
674 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
675 return DeviceVector(rxSinkDevice);
676 }
677 }
678 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
679 // the device returned is not necessarily reachable via this output
680 // (filter later by setOutputDevices())
681 return getNewOutputDevices(mPrimaryOutput, fromCache);
682}
683
684status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
685{
François Gaffiedb1755b2023-09-01 11:50:35 +0200686 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100687 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
688 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
689 }
690 return INVALID_OPERATION;
691}
692
693status_t AudioPolicyManager::updateCallRoutingInternal(
694 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700695{
696 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100697 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700698 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200699 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700700 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100701 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700702 }
François Gaffie11d30102018-11-02 16:09:09 +0100703
Francois Gaffie716e1432019-01-14 16:58:59 +0100704 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100705 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200706
707 disconnectTelephonyAudioSource(mCallRxSourceClient);
708 disconnectTelephonyAudioSource(mCallTxSourceClient);
709
710 if (rxDevices.isEmpty()) {
711 ALOGW("%s() no selected output device", __func__);
712 return INVALID_OPERATION;
713 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000714 if (txSourceDevice == nullptr) {
715 ALOGE("%s() selected input device not available", __func__);
716 return INVALID_OPERATION;
717 }
François Gaffiec005e562018-11-06 15:04:49 +0100718
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100719 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100720 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700721
François Gaffie9eb18552018-11-05 10:33:26 +0100722 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700723 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100724 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700725 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100726 // retrieve Rx Source and Tx Sink device descriptors
727 sp<DeviceDescriptor> rxSourceDevice =
728 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
729 String8(),
730 AUDIO_FORMAT_DEFAULT);
731 sp<DeviceDescriptor> txSinkDevice =
732 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
733 String8(),
734 AUDIO_FORMAT_DEFAULT);
735
736 // RX and TX Telephony device are declared by Primary Audio HAL
737 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
738 (telephonyRxModule->getHalVersionMajor() >= 3)) {
739 if (rxSourceDevice == 0 || txSinkDevice == 0) {
740 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100741 ALOGE("%s() no telephony Tx and/or RX device", __func__);
742 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100743 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100744 // createAudioPatchInternal now supports both HW / SW bridging
745 createRxPatch = true;
746 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100747 } else {
748 // If the RX device is on the primary HW module, then use legacy routing method for
749 // voice calls via setOutputDevice() on primary output.
750 // Otherwise, create two audio patches for TX and RX path.
751 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
752 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700753 // If the TX device is also on the primary HW module, setOutputDevice() will take care
754 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100755 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
756 (txSinkDevice != 0);
757 }
758 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
759 // Otherwise, create two audio patches for TX and RX path.
760 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200761 if (!hasPrimaryOutput()) {
762 ALOGW("%s() no primary output available", __func__);
763 return INVALID_OPERATION;
764 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530765 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700766 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200767 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800768 // If the TX device is on the primary HW module but RX device is
769 // on other HW module, SinkMetaData of telephony input should handle it
770 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700771 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700772 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100773 // terminate active capture if on the same HW module as the call TX source device
774 // FIXME: would be better to refine to only inputs whose profile connects to the
775 // call TX device but this information is not in the audio patch and logic here must be
776 // symmetric to the one in startInput()
777 for (const auto& activeDesc : mInputs.getActiveInputs()) {
778 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
779 closeActiveClients(activeDesc);
780 }
781 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800783 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100784 if (waitMs != nullptr) {
785 *waitMs = muteWaitMs;
786 }
787 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800788}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700789
Mikhail Naganov100f0122018-11-29 11:22:16 -0800790bool AudioPolicyManager::isDeviceOfModule(
791 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
792 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
793 if (module != 0) {
794 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
795 .indexOf(devDesc) != NAME_NOT_FOUND
796 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
797 .indexOf(devDesc) != NAME_NOT_FOUND;
798 }
799 return false;
800}
801
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200802void AudioPolicyManager::connectTelephonyRxAudioSource()
803{
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200805 const struct audio_port_config source = {
806 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
807 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
808 };
809 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100810
811 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
812 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
813 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
814 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200815 ALOGE_IF(mCallRxSourceClient == nullptr,
816 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200817}
818
Francois Gaffie601801d2021-06-22 13:27:39 +0200819void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200820{
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 if (clientDesc == nullptr) {
822 return;
823 }
824 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
825 "%s error stopping audio source", __func__);
826 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200827}
828
829void AudioPolicyManager::connectTelephonyTxAudioSource(
830 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
831 uint32_t delayMs)
832{
Francois Gaffie601801d2021-06-22 13:27:39 +0200833 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200834 if (srcDevice == nullptr || sinkDevice == nullptr) {
835 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
836 return;
837 }
838 PatchBuilder patchBuilder;
839 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
840 ALOGV("%s between source %s and sink %s", __func__,
841 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200842 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200843 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
844
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200845 struct audio_port_config source = {};
846 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100847 mCallTxSourceClient = new SourceClientDescriptor(
848 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
849 mCommunnicationStrategy, toVolumeSource(aa), true);
850 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
851
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200852 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
853 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
855 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200856 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
857 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200858 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200859 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200860}
861
Eric Laurente0720872014-03-11 09:30:41 -0700862void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700863{
864 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100865 // store previous phone state for management of sonification strategy below
866 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100867 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100868
869 if (mEngine->setPhoneState(state) != NO_ERROR) {
870 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700871 return;
872 }
François Gaffie2110e042015-03-24 08:41:51 +0100873 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700874 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700875 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700876 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800877 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700878 }
879
François Gaffie2110e042015-03-24 08:41:51 +0100880 /**
881 * Switching to or from incall state or switching between telephony and VoIP lead to force
882 * routing command.
883 */
Eric Laurent74b71512019-11-06 17:21:57 -0800884 bool force = ((isStateInCall(oldState) != isStateInCall(state))
885 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700886
887 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700888 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700889
Eric Laurente552edb2014-03-10 17:42:56 -0700890 int delayMs = 0;
891 if (isStateInCall(state)) {
892 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100893 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
894 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700895 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700896 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700897 // mute media and sonification strategies and delay device switch by the largest
898 // latency of any output where either strategy is active.
899 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100900 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
901 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
902 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700903 (delayMs < (int)desc->latency()*2)) {
904 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700905 }
François Gaffiec005e562018-11-06 15:04:49 +0100906 setStrategyMute(musicStrategy, true, desc);
907 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
908 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
909 nullptr, true /*fromCache*/).types());
910 setStrategyMute(sonificationStrategy, true, desc);
911 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
912 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
913 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700914 }
915 }
916
François Gaffiedb1755b2023-09-01 11:50:35 +0200917 if (state == AUDIO_MODE_IN_CALL) {
918 (void)updateCallRouting(false /*fromCache*/, delayMs);
919 } else {
920 if (oldState == AUDIO_MODE_IN_CALL) {
921 disconnectTelephonyAudioSource(mCallRxSourceClient);
922 disconnectTelephonyAudioSource(mCallTxSourceClient);
923 }
924 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100925 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
926 // force routing command to audio hardware when ending call
927 // even if no device change is needed
928 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
929 rxDevices = mPrimaryOutput->devices();
930 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530931 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700932 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700933 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700934
jiabin3ff8d7d2022-12-13 06:27:44 +0000935 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700936 // reevaluate routing on all outputs in case tracks have been started during the call
937 for (size_t i = 0; i < mOutputs.size(); i++) {
938 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100939 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000940 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
941 && desc->mPreferredAttrInfo != nullptr) {
942 // If the output is using preferred mixer attributes and the audio mode is not normal,
943 // the output need to reopen with default configuration.
944 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
945 continue;
946 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200947 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
948 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530949 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200950 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700951 }
952 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000953 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700954
Eric Laurent96d1dda2022-03-14 17:14:19 +0100955 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
956
Eric Laurente552edb2014-03-10 17:42:56 -0700957 if (isStateInCall(state)) {
958 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700959 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800960 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962
963 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100964 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
965 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700966}
967
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700968audio_mode_t AudioPolicyManager::getPhoneState() {
969 return mEngine->getPhoneState();
970}
971
Eric Laurente0720872014-03-11 09:30:41 -0700972void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100973 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700974{
François Gaffie2110e042015-03-24 08:41:51 +0100975 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700976 if (config == mEngine->getForceUse(usage)) {
977 return;
978 }
Eric Laurente552edb2014-03-10 17:42:56 -0700979
François Gaffie2110e042015-03-24 08:41:51 +0100980 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
981 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
982 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700983 }
François Gaffie2110e042015-03-24 08:41:51 +0100984 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
985 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
986 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700987
988 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700989 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800990
Eric Laurent22fcda22019-05-17 16:28:47 -0700991 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
992 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800993 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700994 }
995
Eric Laurentdc462862016-07-19 12:29:53 -0700996 //FIXME: workaround for truncated touch sounds
997 // to be removed when the problem is handled by system UI
998 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700999 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1000 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1001 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001002
1003 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001004 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001005}
1006
Eric Laurente0720872014-03-11 09:30:41 -07001007void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001008{
1009 ALOGV("setSystemProperty() property %s, value %s", property, value);
1010}
1011
Dorin Drimusecc9f422022-03-09 17:57:40 +01001012// Find an MSD output profile compatible with the parameters passed.
1013// When "directOnly" is set, restrict search to profiles for direct outputs.
1014sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1015 const DeviceVector& devices,
1016 uint32_t samplingRate,
1017 audio_format_t format,
1018 audio_channel_mask_t channelMask,
1019 audio_output_flags_t flags,
1020 bool directOnly)
1021{
1022 flags = getRelevantFlags(flags, directOnly);
1023
1024 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1025 if (msdModule != nullptr) {
1026 // for the msd module check if there are patches to the output devices
1027 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1028 HwModuleCollection modules;
1029 modules.add(msdModule);
1030 return searchCompatibleProfileHwModules(
1031 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1032 flags, directOnly);
1033 }
1034 }
1035 return nullptr;
1036}
1037
Michael Chana94fbb22018-04-24 14:31:19 +10001038// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1039// search to profiles for direct outputs.
1040sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001041 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001042 uint32_t samplingRate,
1043 audio_format_t format,
1044 audio_channel_mask_t channelMask,
1045 audio_output_flags_t flags,
1046 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001047{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001048 flags = getRelevantFlags(flags, directOnly);
1049
1050 return searchCompatibleProfileHwModules(
1051 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1052}
1053
1054audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1055 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001056 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001057 // only retain flags that will drive the direct output profile selection
1058 // if explicitly requested
1059 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001060 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001061 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1062 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001063 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001064 return flags;
1065}
Eric Laurent861a6282015-05-18 15:40:16 -07001066
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1068 const HwModuleCollection& hwModules,
1069 const DeviceVector& devices,
1070 uint32_t samplingRate,
1071 audio_format_t format,
1072 audio_channel_mask_t channelMask,
1073 audio_output_flags_t flags,
1074 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001075 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001076 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001077 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001078 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001079 samplingRate, NULL /*updatedSamplingRate*/,
1080 format, NULL /*updatedFormat*/,
1081 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001082 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001083 continue;
1084 }
1085 // reject profiles not corresponding to a device currently available
1086 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1087 continue;
1088 }
1089 // reject profiles if connected device does not support codec
1090 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1091 continue;
1092 }
1093 if (!directOnly) {
1094 return curProfile;
1095 }
1096
1097 // when searching for direct outputs, if several profiles are compatible, give priority
1098 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001099 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001100 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001101 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001102 }
1103 profile = curProfile;
1104 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1105 break;
1106 }
Eric Laurente552edb2014-03-10 17:42:56 -07001107 }
1108 }
Eric Laurent861a6282015-05-18 15:40:16 -07001109 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001110}
1111
Eric Laurentfa0f6742021-08-17 18:39:44 +02001112sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001113 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001114{
1115 for (const auto& hwModule : mHwModules) {
1116 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001117 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001118 continue;
1119 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001120 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001121 // reject profiles not corresponding to a device currently available
1122 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1123 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1124 continue;
1125 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001126 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1127 != devices.size()) {
1128 continue;
1129 }
1130 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001131 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1132 return curProfile;
1133 }
1134 }
1135 return nullptr;
1136}
1137
Eric Laurentf4e63452017-11-06 19:31:46 +00001138audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001139{
François Gaffiec005e562018-11-06 15:04:49 +01001140 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001141
1142 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1143 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1144 // format, flags, etc. This may result in some discrepancy for functions that utilize
1145 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1146 // and AudioSystem::getOutputSamplingRate().
1147
François Gaffie11d30102018-11-02 16:09:09 +01001148 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001149 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1150 if (stream == AUDIO_STREAM_MUSIC &&
1151 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1152 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1153 }
1154 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001155
François Gaffie11d30102018-11-02 16:09:09 +01001156 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1157 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001158 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001159}
1160
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001161status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1162 const audio_attributes_t *srcAttr,
1163 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001164{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001165 if (srcAttr != NULL) {
1166 if (!isValidAttributes(srcAttr)) {
1167 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1168 __func__,
1169 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1170 srcAttr->tags);
1171 return BAD_VALUE;
1172 }
1173 *dstAttr = *srcAttr;
1174 } else {
1175 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1176 ALOGE("%s: invalid stream type", __func__);
1177 return BAD_VALUE;
1178 }
François Gaffiec005e562018-11-06 15:04:49 +01001179 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001180 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001181
1182 // Only honor audibility enforced when required. The client will be
1183 // forced to reconnect if the forced usage changes.
1184 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001185 dstAttr->flags = static_cast<audio_flags_mask_t>(
1186 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001187 }
1188
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001189 return NO_ERROR;
1190}
1191
Kevin Rocard153f92d2018-12-18 18:33:28 -08001192status_t AudioPolicyManager::getOutputForAttrInt(
1193 audio_attributes_t *resultAttr,
1194 audio_io_handle_t *output,
1195 audio_session_t session,
1196 const audio_attributes_t *attr,
1197 audio_stream_type_t *stream,
1198 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001199 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001200 audio_output_flags_t *flags,
1201 audio_port_handle_t *selectedDeviceId,
1202 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001204 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001205 bool *isSpatialized,
1206 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001207{
François Gaffiec005e562018-11-06 15:04:49 +01001208 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001209 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001210 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001211 const sp<DeviceDescriptor> requestedDevice =
1212 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1213
Eric Laurent8a1095a2019-11-08 14:44:16 -08001214 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001215 *isSpatialized = false;
1216
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001217 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1218 if (status != NO_ERROR) {
1219 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001220 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001221 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001222 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001223 }
François Gaffiec005e562018-11-06 15:04:49 +01001224 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001225
François Gaffiec005e562018-11-06 15:04:49 +01001226 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1227 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001228
Oscar Azucena873d10f2023-01-12 18:34:42 -08001229 bool usePrimaryOutputFromPolicyMixes = false;
1230
Kevin Rocard153f92d2018-12-18 18:33:28 -08001231 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1232 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1233 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001235 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1236 .channel_mask = config->channel_mask,
1237 .format = config->format,
1238 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001239 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001240 mAvailableOutputDevices, requestedDevice, primaryMix,
1241 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001242 if (status != OK) {
1243 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001244 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001245
Kevin Rocard153f92d2018-12-18 18:33:28 -08001246 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001247 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1248 && !audio_is_linear_pcm(config->format)) {
1249 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001250 return BAD_VALUE;
1251 }
1252 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001253 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001254 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1255 primaryMix->mDeviceAddress,
1256 AUDIO_FORMAT_DEFAULT);
1257 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001258 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001259 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1260 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001261 // if a direct output can be opened to deliver the track's multi-channel content to the
1262 // output rather than being downmixed by the primary output, then use this direct
1263 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1264 // mix.
1265 bool tryDirectForChannelMask = policyDesc != nullptr
1266 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1267 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001268 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001269 audio_io_handle_t newOutput;
1270 status = openDirectOutput(
1271 *stream, session, config,
1272 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001273 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001274 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001275 policyDesc = mOutputs.valueFor(newOutput);
1276 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001277 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001278 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001279 policyDesc = nullptr;
1280 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001281 }
1282 if (policyDesc != nullptr) {
1283 policyDesc->mPolicyMix = primaryMix;
1284 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001285 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1286 : AUDIO_PORT_HANDLE_NONE;
1287 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1288 // Remove direct flag as it is not on a direct output.
1289 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1290 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001291
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001292 ALOGV("getOutputForAttr() returns output %d", *output);
1293 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1294 *outputType = API_OUT_MIX_PLAYBACK;
1295 } else {
1296 *outputType = API_OUTPUT_LEGACY;
1297 }
1298 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001299 } else {
1300 if (policyMixDevice != nullptr) {
1301 ALOGE("%s, try to use primary mix but no output found", __func__);
1302 return INVALID_OPERATION;
1303 }
1304 // Fallback to default engine selection as the selected primary mix device is not
1305 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001306 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001307 }
François Gaffiec005e562018-11-06 15:04:49 +01001308 // Virtual sources must always be dynamicaly or explicitly routed
1309 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1310 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1311 return BAD_VALUE;
1312 }
1313 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1314 // in order to let the choice of the order to future vendor engine
1315 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001316
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001317 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001318 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001319 }
1320
Nadav Barb2f18162018-07-18 13:01:53 +03001321 // Set incall music only if device was explicitly set, and fallback to the device which is
1322 // chosen by the engine if not.
1323 // FIXME: provide a more generic approach which is not device specific and move this back
1324 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001325 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001326 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001327 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001328 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001329 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001330 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001331 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001332 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001333 }
1334 }
1335
François Gaffiec005e562018-11-06 15:04:49 +01001336 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1337 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1338 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001339
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001340 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001341 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001342 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001343 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001344 ALOGV("%s() Using MSD devices %s instead of devices %s",
1345 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 } else {
1347 *output = AUDIO_IO_HANDLE_NONE;
1348 }
1349 }
1350 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001351 sp<PreferredMixerAttributesInfo> info = nullptr;
1352 if (outputDevices.size() == 1) {
1353 info = getPreferredMixerAttributesInfo(
1354 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001355 mEngine->getProductStrategyForAttributes(*resultAttr),
1356 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001357 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1358 // and it is currently active.
1359 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001360 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001361 info = nullptr;
1362 }
jiabin220eea12024-05-17 17:55:20 +00001363 if (com::android::media::audioserver::
1364 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1365 if (info != nullptr && info->getUid() == uid &&
1366 info->configMatches(*config) &&
1367 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1368 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1369 [this, &outputDevices](audio_usage_t usage) {
1370 return mOutputs.isUsageActiveOnDevice(
1371 usage, outputDevices[0]); }))) {
1372 // Bit-perfect request is not allowed when the phone mode is not normal or
1373 // there is any higher priority user case active.
1374 return INVALID_OPERATION;
1375 }
1376 }
jiabina84c3d32022-12-02 18:59:55 +00001377 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001378 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001379 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001380 // The client will be active if the client is currently preferred mixer owner and the
1381 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001382 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001383 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001384 && info->getUid() == uid
1385 && *output != AUDIO_IO_HANDLE_NONE
1386 // When bit-perfect output is selected for the preferred mixer attributes owner,
1387 // only need to consider the config matches.
1388 && mOutputs.valueFor(*output)->isConfigurationMatched(
1389 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001390
1391 if (*isBitPerfect) {
1392 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1393 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001394 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001395 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001396 AudioProfileVector profiles;
1397 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1398 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001399 const auto channels = profiles[0]->getChannels();
1400 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1401 config->channel_mask = *channels.begin();
1402 }
1403 const auto sampleRates = profiles[0]->getSampleRates();
1404 if (!sampleRates.empty() &&
1405 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1406 config->sample_rate = *sampleRates.begin();
1407 }
jiabinf1c73972022-04-14 16:28:52 -07001408 config->format = profiles[0]->getFormat();
1409 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001410 return INVALID_OPERATION;
1411 }
Paul McLeanaa981192015-03-21 09:55:15 -07001412
François Gaffiec005e562018-11-06 15:04:49 +01001413 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001414 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001415 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001416 *selectedDeviceId = outputDevice->getId();
1417 break;
1418 }
1419 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001420
Eric Laurent8a1095a2019-11-08 14:44:16 -08001421 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1422 *outputType = API_OUTPUT_TELEPHONY_TX;
1423 } else {
1424 *outputType = API_OUTPUT_LEGACY;
1425 }
1426
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001427 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1428
1429 return NO_ERROR;
1430}
1431
1432status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1433 audio_io_handle_t *output,
1434 audio_session_t session,
1435 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001436 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001437 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001438 audio_output_flags_t *flags,
1439 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001440 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001441 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001442 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001443 bool *isSpatialized,
1444 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001445{
1446 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1447 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1448 return INVALID_OPERATION;
1449 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001450 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001451 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001452 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001453 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001454 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001455 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001456 const sp<DeviceDescriptor> requestedDevice =
1457 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1458
1459 // Prevent from storing invalid requested device id in clients
1460 const audio_port_handle_t sanitizedRequestedPortId =
1461 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1462 *selectedDeviceId = sanitizedRequestedPortId;
1463
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001464 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001465 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001466 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1467 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001468 if (status != NO_ERROR) {
1469 return status;
1470 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001471 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001472 if (secondaryOutputs != nullptr) {
1473 for (auto &secondaryMix : secondaryMixes) {
1474 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1475 if (outputDesc != nullptr &&
1476 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1477 secondaryOutputs->push_back(outputDesc->mIoHandle);
1478 weakSecondaryOutputDescs.push_back(outputDesc);
1479 }
1480 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001481 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001482
Eric Laurent8fc147b2018-07-22 19:13:55 -07001483 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001484 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001485 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001486 };
jiabin4ef93452019-09-10 14:29:54 -07001487 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001488
Eric Laurentc209fe42020-06-05 18:11:23 -07001489 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001490 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001491 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001492 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001493 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001494 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001495 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001496 std::move(weakSecondaryOutputDescs),
1497 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001498 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001499
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001500 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1501 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001502
Eric Laurente83b55d2014-11-14 10:06:21 -08001503 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001504}
1505
Eric Laurentc529cf62020-04-17 18:19:10 -07001506status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1507 audio_session_t session,
1508 const audio_config_t *config,
1509 audio_output_flags_t flags,
1510 const DeviceVector &devices,
1511 audio_io_handle_t *output) {
1512
1513 *output = AUDIO_IO_HANDLE_NONE;
1514
1515 // skip direct output selection if the request can obviously be attached to a mixed output
1516 // and not explicitly requested
1517 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1518 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1519 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1520 return NAME_NOT_FOUND;
1521 }
1522
1523 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1524 // This prevents creating an offloaded track and tearing it down immediately after start
1525 // when audioflinger detects there is an active non offloadable effect.
1526 // FIXME: We should check the audio session here but we do not have it in this context.
1527 // This may prevent offloading in rare situations where effects are left active by apps
1528 // in the background.
1529 sp<IOProfile> profile;
1530 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1531 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1532 profile = getProfileForOutput(
1533 devices, config->sample_rate, config->format, config->channel_mask,
1534 flags, true /* directOnly */);
1535 }
1536
1537 if (profile == nullptr) {
1538 return NAME_NOT_FOUND;
1539 }
1540
1541 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1542 for (size_t i = 0; i < mOutputs.size(); i++) {
1543 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1544 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1545 // reuse direct output if currently open by the same client
1546 // and configured with same parameters
1547 if ((config->sample_rate == desc->getSamplingRate()) &&
1548 (config->format == desc->getFormat()) &&
1549 (config->channel_mask == desc->getChannelMask()) &&
1550 (session == desc->mDirectClientSession)) {
1551 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001552 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001553 mOutputs.keyAt(i), session);
1554 *output = mOutputs.keyAt(i);
1555 return NO_ERROR;
1556 }
1557 }
1558 }
1559
1560 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001561 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1562 return NAME_NOT_FOUND;
1563 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1564 // MMAP gracefully handles lack of an exclusive track resource by mixing
1565 // above the audio framework. For AAudio to know that the limit is reached,
1566 // return an error.
1567 return NAME_NOT_FOUND;
1568 } else {
1569 // Close outputs on this profile, if available, to free resources for this request
1570 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1571 const auto desc = mOutputs.valueAt(i);
1572 if (desc->mProfile == profile) {
1573 closeOutput(desc->mIoHandle);
1574 }
1575 }
1576 }
1577 }
1578
1579 // Unable to close streams to find free resources for this request
1580 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001581 return NAME_NOT_FOUND;
1582 }
1583
Atneya Nairb16666a2023-12-11 20:18:33 -08001584 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001585
Michael Chan6fb34492020-12-08 15:44:49 +11001586 // An MSD patch may be using the only output stream that can service this request. Release
1587 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001588 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001589
Eric Laurentf1f22e72021-07-13 14:04:14 +02001590 status_t status =
1591 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001592
1593 // only accept an output with the requested parameters
1594 if (status != NO_ERROR ||
1595 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1596 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1597 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1598 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1599 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1600 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1601 config->channel_mask, outputDesc->getChannelMask());
1602 if (*output != AUDIO_IO_HANDLE_NONE) {
1603 outputDesc->close();
1604 }
1605 // fall back to mixer output if possible when the direct output could not be open
1606 if (audio_is_linear_pcm(config->format) &&
1607 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1608 return NAME_NOT_FOUND;
1609 }
1610 *output = AUDIO_IO_HANDLE_NONE;
1611 return BAD_VALUE;
1612 }
1613 outputDesc->mDirectOpenCount = 1;
1614 outputDesc->mDirectClientSession = session;
1615
1616 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001617 setOutputDevices(__func__, outputDesc,
1618 devices,
1619 true,
1620 0,
1621 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001622 mPreviousOutputs = mOutputs;
1623 ALOGV("%s returns new direct output %d", __func__, *output);
1624 mpClientInterface->onAudioPortListUpdate();
1625 return NO_ERROR;
1626}
1627
François Gaffie11d30102018-11-02 16:09:09 +01001628audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1629 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001630 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001631 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001632 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001633 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001634 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001635 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001636 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001637{
Andy Hungc88b0642018-04-27 15:42:35 -07001638 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001639
jiabine375d412019-02-26 12:54:53 -08001640 // Discard haptic channel mask when forcing muting haptic channels.
1641 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001642 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1643 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001644
Eric Laurente552edb2014-03-10 17:42:56 -07001645 // open a direct output if required by specified parameters
1646 //force direct flag if offload flag is set: offloading implies a direct output stream
1647 // and all common behaviors are driven by checking only the direct flag
1648 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001649 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1650 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001651 }
Nadav Bar766fb022018-01-07 12:18:03 +02001652 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1653 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001654 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001655
1656 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1657
Eric Laurente83b55d2014-11-14 10:06:21 -08001658 // only allow deep buffering for music stream type
1659 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001660 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001661 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001662 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001663 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1664 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001665 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001666 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001667 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001668 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001669 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001670 audio_is_linear_pcm(config->format) &&
1671 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001672 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001673 AUDIO_OUTPUT_FLAG_DIRECT);
1674 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001675 }
Eric Laurente552edb2014-03-10 17:42:56 -07001676
Carter Hsua3abb402021-10-26 11:11:20 +08001677 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1678 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1679 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1680 }
1681
Eric Laurentf9230d52024-01-26 18:49:09 +01001682 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001683 // was specified and offload or direct playback is not explicitly requested, and there is no
1684 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001685 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001686 if (mSpatializerOutput != nullptr &&
1687 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1688 prefMixerConfigInfo == nullptr &&
1689 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1690 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001691 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001692 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001693 }
1694
Eric Laurentc529cf62020-04-17 18:19:10 -07001695 audio_config_t directConfig = *config;
1696 directConfig.channel_mask = channelMask;
1697 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1698 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001699 return output;
1700 }
1701
Eric Laurent14cbfca2016-03-17 09:42:16 -07001702 // A request for HW A/V sync cannot fallback to a mixed output because time
1703 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001704 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001705 return AUDIO_IO_HANDLE_NONE;
1706 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001707 // A request for Tuner cannot fallback to a mixed output
1708 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1709 return AUDIO_IO_HANDLE_NONE;
1710 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001711
Eric Laurente552edb2014-03-10 17:42:56 -07001712 // ignoring channel mask due to downmix capability in mixer
1713
1714 // open a non direct output
1715
1716 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001717 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001718 // get which output is suitable for the specified stream. The actual
1719 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001720 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001721 if (prefMixerConfigInfo != nullptr) {
1722 for (audio_io_handle_t outputHandle : outputs) {
1723 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1724 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1725 output = outputHandle;
1726 break;
1727 }
1728 }
1729 if (output == AUDIO_IO_HANDLE_NONE) {
1730 // No output open with the preferred profile. Open a new one.
1731 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1732 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1733 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1734 config.format = prefMixerConfigInfo->getConfigBase().format;
1735 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1736 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1737 &config, prefMixerConfigInfo->getFlags());
1738 if (preferredOutput == nullptr) {
1739 ALOGE("%s failed to open output with preferred mixer config", __func__);
1740 } else {
1741 output = preferredOutput->mIoHandle;
1742 }
1743 }
1744 } else {
1745 // at this stage we should ignore the DIRECT flag as no direct output could be
1746 // found earlier
1747 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001748 if (com::android::media::audioserver::
1749 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1750 // If the preferred mixer attributes is null, do not select the bit-perfect output
1751 // unless the bit-perfect output is the only output.
1752 // The bit-perfect output can exist while the passed in preferred mixer attributes
1753 // info is null when it is a high priority client. The high priority clients are
1754 // ringtone or alarm, which is not a bit-perfect use case.
1755 size_t i = 0;
1756 while (i < outputs.size() && outputs.size() > 1) {
1757 auto desc = mOutputs.valueFor(outputs[i]);
1758 // The output descriptor must not be null here.
1759 if (desc->isBitPerfect()) {
1760 outputs.removeItemsAt(i);
1761 } else {
1762 i += 1;
1763 }
1764 }
1765 }
jiabina84c3d32022-12-02 18:59:55 +00001766 output = selectOutput(
1767 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1768 }
Eric Laurente552edb2014-03-10 17:42:56 -07001769 }
François Gaffie11d30102018-11-02 16:09:09 +01001770 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001771 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001772 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001773
Eric Laurente552edb2014-03-10 17:42:56 -07001774 return output;
1775}
1776
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001777sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001778 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1779 mAvailableInputDevices);
1780 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1781}
1782
1783DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1784 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1785 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001786}
1787
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001788const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001789 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001790 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1791 if (msdModule != 0) {
1792 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1793 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1794 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1795 const struct audio_port_config *source = &patch->mPatch.sources[j];
1796 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1797 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001798 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001799 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001800 }
1801 }
1802 }
1803 return msdPatches;
1804}
1805
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001806bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1807 ssize_t index = mAudioPatches.indexOfKey(handle);
1808 if (index < 0) {
1809 return false;
1810 }
1811 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1812 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1813 if (msdModule == nullptr) {
1814 return false;
1815 }
1816 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1817 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1818 return true;
1819 }
1820 index = getMsdOutputPatches().indexOfKey(handle);
1821 if (index < 0) {
1822 return false;
1823 }
1824 return true;
1825}
1826
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001827status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1828 const InputProfileCollection &inputProfiles,
1829 const OutputProfileCollection &outputProfiles,
1830 const sp<DeviceDescriptor> &sourceDevice,
1831 const sp<DeviceDescriptor> &sinkDevice,
1832 AudioProfileVector& sourceProfiles,
1833 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001834 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001835 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 return NO_INIT;
1837 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001838 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 return NO_INIT;
1841 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001843 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1844 inProfile->supportsDevice(sourceDevice)) {
1845 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001846 }
1847 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001848 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001849 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001850 outProfile->supportsDevice(sinkDevice)) {
1851 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001852 }
1853 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001854 return NO_ERROR;
1855}
1856
1857status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1858 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1859 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1860{
Dean Wheatley16809da2022-12-09 14:55:46 +11001861 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1862 static const std::vector<audio_format_t> formatsOrder = {{
1863 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001864 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1865 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001866 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1867 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1868 // preferred).
1869 std::vector<audio_channel_mask_t> masks = {{
1870 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1871 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1872 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1873 // insert index masks (higher counts most preferred) as preferred over position masks
1874 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1875 masks.insert(
1876 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1877 }
1878 return masks;
1879 }();
1880
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001882 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1883 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001885 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1886 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001887 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001888 }
1889 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1890 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1891 sinkConfig->format = bestSinkConfig.format;
1892 // For encoded streams force direct flag to prevent downstream mixing.
1893 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1894 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001895 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1896 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001897 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001898 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1899 // raw and IEC61937 framed streams.
1900 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1901 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1902 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1904 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001905 sourceConfig->channel_mask =
1906 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1907 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1908 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001909 sourceConfig->format = bestSinkConfig.format;
1910 // Copy input stream directly without any processing (e.g. resampling).
1911 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1912 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1913 if (hwAvSync) {
1914 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1915 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1916 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1917 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1918 }
1919 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1920 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1921 sinkConfig->config_mask |= config_mask;
1922 sourceConfig->config_mask |= config_mask;
1923 return NO_ERROR;
1924}
1925
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001926PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1927 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001928{
1929 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001930 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1931 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1932 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1933 if (deviceModule == nullptr) {
1934 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1935 return patchBuilder;
1936 }
1937 const InputProfileCollection inputProfiles = msdIsSource ?
1938 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1939 const OutputProfileCollection outputProfiles = msdIsSource ?
1940 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1941
1942 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1943 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1944 device : getMsdAudioOutDevices().itemAt(0);
1945 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1946
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001947 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1948 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001949 AudioProfileVector sourceProfiles;
1950 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1952 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001953 for (auto hwAvSync : { true, false }) {
1954 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1955 sourceProfiles, sinkProfiles) != NO_ERROR) {
1956 continue;
1957 }
1958 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1959 &sinkConfig) == NO_ERROR) {
1960 // Found a matching config. Re-create PatchBuilder with this config.
1961 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1962 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001963 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001964 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001965 " supporting PCM format conversion.", __func__);
1966 return patchBuilder;
1967}
1968
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001969status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001970 DeviceVector devices;
1971 if (outputDevices != nullptr && outputDevices->size() > 0) {
1972 devices.add(*outputDevices);
1973 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001974 // Use media strategy for unspecified output device. This should only
1975 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1976 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001977 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001978 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001979 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001980 }
Michael Chan6fb34492020-12-08 15:44:49 +11001981 std::vector<PatchBuilder> patchesToCreate;
1982 for (auto i = 0u; i < devices.size(); ++i) {
1983 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001984 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001985 }
1986 // Retain only the MSD patches associated with outputDevices request.
1987 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001988 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001989 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1990 auto retainedPatch = false;
1991 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1992 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1993 patchesToRemove.removeItemsAt(i);
1994 retainedPatch = true;
1995 break;
1996 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001997 }
Michael Chan6fb34492020-12-08 15:44:49 +11001998 if (retainedPatch) {
1999 it = patchesToCreate.erase(it);
2000 continue;
2001 }
2002 ++it;
2003 }
2004 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2005 return NO_ERROR;
2006 }
2007 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2008 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002009 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002010 }
Michael Chan6fb34492020-12-08 15:44:49 +11002011 status_t status = NO_ERROR;
2012 for (const auto &p : patchesToCreate) {
2013 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2014 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2015 char message[256];
2016 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2017 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2018 currStatus == NO_ERROR ? "Success" : "Error",
2019 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2020 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2021 if (currStatus == NO_ERROR) {
2022 ALOGD("%s", message);
2023 } else {
2024 ALOGE("%s", message);
2025 if (status == NO_ERROR) {
2026 status = currStatus;
2027 }
2028 }
2029 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002030 return status;
2031}
2032
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002033void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2034 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002035 for (size_t i = 0; i < msdPatches.size(); i++) {
2036 const auto& patch = msdPatches[i];
2037 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2038 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2039 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2040 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2041 releaseAudioPatch(patch->getHandle(), mUidCached);
2042 break;
2043 }
2044 }
2045 }
2046}
2047
Dorin Drimus94d94412022-02-02 09:05:02 +01002048bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002049 DeviceVector devicesToCheck =
2050 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002051 AudioPatchCollection msdPatches = getMsdOutputPatches();
2052 for (size_t i = 0; i < msdPatches.size(); i++) {
2053 const auto& patch = msdPatches[i];
2054 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2055 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2056 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2057 const auto& foundDevice = devicesToCheck.getDevice(
2058 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2059 if (foundDevice != nullptr) {
2060 devicesToCheck.remove(foundDevice);
2061 if (devicesToCheck.isEmpty()) {
2062 return true;
2063 }
2064 }
2065 }
2066 }
2067 }
2068 return false;
2069}
2070
Eric Laurente0720872014-03-11 09:30:41 -07002071audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002072 audio_output_flags_t flags,
2073 audio_format_t format,
2074 audio_channel_mask_t channelMask,
2075 uint32_t samplingRate,
2076 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002077{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002078 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2079 "%s called with format %#x", __func__, format);
2080
jiabinebb6af42020-06-09 17:31:17 -07002081 // Return the output that haptic-generating attached to when 1) session id is specified,
2082 // 2) haptic-generating effect exists for given session id and 3) the output that
2083 // haptic-generating effect attached to is in given outputs.
2084 if (sessionId != AUDIO_SESSION_NONE) {
2085 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2086 sessionId, FX_IID_HAPTICGENERATOR);
2087 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2088 return hapticGeneratingOutput;
2089 }
2090 }
2091
Eric Laurent16c66dd2019-05-01 17:54:10 -07002092 // Flags disqualifying an output: the match must happen before calling selectOutput()
2093 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2094 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2095
2096 // Flags expressing a functional request: must be honored in priority over
2097 // other criteria
2098 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2099 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002100 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2101 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002102 // Flags expressing a performance request: have lower priority than serving
2103 // requested sampling rate or channel mask
2104 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2105 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2106 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2107
2108 const audio_output_flags_t functionalFlags =
2109 (audio_output_flags_t)(flags & kFunctionalFlags);
2110 const audio_output_flags_t performanceFlags =
2111 (audio_output_flags_t)(flags & kPerformanceFlags);
2112
2113 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2114
Eric Laurente552edb2014-03-10 17:42:56 -07002115 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002116 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002117 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002118 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002119 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002120 // with tiebreak preferring the minimum number of extra functional flags
2121 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002122 // 3: the output supporting the exact channel mask
2123 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002124 // 5: the output with the highest sampling rate if the requested sample rate is
2125 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002126 // 6: the output with the highest number of requested performance flags
2127 // 7: the output with the bit depth the closest to the requested one
2128 // 8: the primary output
2129 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002130
Eric Laurent16c66dd2019-05-01 17:54:10 -07002131 // matching criteria values in priority order for best matching output so far
2132 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002133
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002134 const bool hasOrphanHaptic =
2135 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002136 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2137 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2138 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002139
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002140 for (audio_io_handle_t output : outputs) {
2141 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002142 // matching criteria values in priority order for current output
2143 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002144
Eric Laurent16c66dd2019-05-01 17:54:10 -07002145 if (outputDesc->isDuplicated()) {
2146 continue;
2147 }
2148 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2149 continue;
2150 }
Eric Laurent8838a382014-09-08 16:44:28 -07002151
Eric Laurent16c66dd2019-05-01 17:54:10 -07002152 // If haptic channel is specified, use the haptic output if present.
2153 // When using haptic output, same audio format and sample rate are required.
2154 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002155 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002156 // skip if haptic channel specified but output does not support it, or output support haptic
2157 // but there is no haptic channel requested AND no orphan haptic effect exist
2158 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2159 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002160 continue;
2161 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002162 // In the case of audio-coupled-haptic playback, there is no format conversion and
2163 // resampling in the framework, same format/channel/sampleRate for client and the output
2164 // thread is required. In the case of HapticGenerator effect, do not require format
2165 // matching.
2166 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2167 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002168 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002169 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002170 }
2171
2172 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002173 const int matchingFunctionalFlags =
2174 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2175 const int totalFunctionalFlags =
2176 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2177 // Prefer matching functional flags, but subtract unnecessary functional flags.
2178 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002179
2180 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002181 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2182 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002183 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2184 channelCount <= outputChannelCount) {
2185 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002186 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2187 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002189 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 currentMatchCriteria[3] = outputChannelCount;
2191 }
2192
2193 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002194 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002195 int diff; // avoid unsigned integer overflow.
2196 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2197
2198 // prefer the closest output sampling rate greater than or equal to target
2199 // if none exists, prefer the closest output sampling rate less than target.
2200 //
2201 // criteria is offset to make non-negative.
2202 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002203 }
2204
2205 // performance flags match
2206 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2207
2208 // format match
2209 if (format != AUDIO_FORMAT_INVALID) {
2210 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002211 PolicyAudioPort::kFormatDistanceMax -
2212 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002213 }
2214
2215 // primary output match
2216 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2217
2218 // compare match criteria by priority then value
2219 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2220 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2221 bestMatchCriteria = currentMatchCriteria;
2222 bestOutput = output;
2223
2224 std::stringstream result;
2225 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2226 std::ostream_iterator<int>(result, " "));
2227 ALOGV("%s new bestOutput %d criteria %s",
2228 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002229 }
2230 }
2231
Eric Laurent16c66dd2019-05-01 17:54:10 -07002232 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002233}
2234
Eric Laurent8fc147b2018-07-22 19:13:55 -07002235status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002236{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002237 ALOGV("%s portId %d", __FUNCTION__, portId);
2238
2239 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2240 if (outputDesc == 0) {
2241 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002242 return BAD_VALUE;
2243 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002244 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002245
Eric Laurent8fc147b2018-07-22 19:13:55 -07002246 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002247 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002248
jiabin220eea12024-05-17 17:55:20 +00002249 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2250 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2251 && outputDesc->isBitPerfect()) {
2252 // Usually, APM selects bit-perfect output for high priority use cases only when
2253 // bit-perfect output is the only output that can be routed to the selected device.
2254 // However, here is no need to play high priority use cases such as ringtone and alarm
2255 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2256 // can attach to new output.
2257 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2258 __func__, client->stream());
2259 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2260 return DEAD_OBJECT;
2261 }
2262
Eric Laurent733ce942017-12-07 12:18:25 -08002263 status_t status = outputDesc->start();
2264 if (status != NO_ERROR) {
2265 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002266 }
2267
Eric Laurent97ac8712018-07-27 18:59:02 -07002268 uint32_t delayMs;
2269 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002270
2271 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002272 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002273 if (status == DEAD_OBJECT) {
2274 sp<SwAudioOutputDescriptor> desc =
2275 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2276 if (desc == nullptr) {
2277 // This is not common, it may indicate something wrong with the HAL.
2278 ALOGE("%s unable to open output with default config", __func__);
2279 return status;
2280 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002281 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002282 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002283 }
jiabina84c3d32022-12-02 18:59:55 +00002284
2285 // If the client is the first one active on preferred mixer parameters, reopen the output
2286 // if the current mixer parameters doesn't match the preferred one.
2287 if (outputDesc->devices().size() == 1) {
2288 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2289 outputDesc->devices()[0]->getId(), client->strategy());
2290 if (info != nullptr && info->getUid() == client->uid()) {
2291 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2292 info->getConfigBase(), info->getFlags())) {
2293 stopSource(outputDesc, client);
2294 outputDesc->stop();
2295 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2296 config.channel_mask = info->getConfigBase().channel_mask;
2297 config.sample_rate = info->getConfigBase().sample_rate;
2298 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002299 sp<SwAudioOutputDescriptor> desc =
2300 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2301 if (desc == nullptr) {
2302 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002303 }
jiabin220eea12024-05-17 17:55:20 +00002304 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002305 // Intentionally return error to let the client side resending request for
2306 // creating and starting.
2307 return DEAD_OBJECT;
2308 }
2309 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002310 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002311 // If it is first bit-perfect client, reroute all clients that will be routed to
2312 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2313 PortHandleVector clientsToInvalidate;
2314 for (size_t i = 0; i < mOutputs.size(); i++) {
2315 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002316 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002317 continue;
2318 }
2319 for (const auto& c : mOutputs[i]->getClientIterable()) {
2320 clientsToInvalidate.push_back(c->portId());
2321 }
2322 }
2323 if (!clientsToInvalidate.empty()) {
2324 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2325 __func__);
2326 mpClientInterface->invalidateTracks(clientsToInvalidate);
2327 }
2328 }
jiabina84c3d32022-12-02 18:59:55 +00002329 }
2330 }
2331
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002332 if (client->hasPreferredDevice()) {
2333 // playback activity with preferred device impacts routing occurred, inform upper layers
2334 mpClientInterface->onRoutingUpdated();
2335 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002336 if (delayMs != 0) {
2337 usleep(delayMs * 1000);
2338 }
2339
jiabin220eea12024-05-17 17:55:20 +00002340 if (status == NO_ERROR &&
2341 outputDesc->mPreferredAttrInfo != nullptr &&
2342 outputDesc->isBitPerfect() &&
2343 com::android::media::audioserver::
2344 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2345 // A new client is started on bit-perfect output, update all clients internal mute.
2346 updateClientsInternalMute(outputDesc);
2347 }
2348
Eric Laurentc75307b2015-03-17 15:29:32 -07002349 return status;
2350}
2351
Eric Laurent96d1dda2022-03-14 17:14:19 +01002352bool AudioPolicyManager::isLeUnicastActive() const {
2353 if (isInCall()) {
2354 return true;
2355 }
2356 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2357}
2358
2359bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2360 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2361 return false;
2362 }
2363 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2364 ALOGV("%s active %d", __func__, active);
2365 return active;
2366}
2367
Eric Laurent97ac8712018-07-27 18:59:02 -07002368status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2369 const sp<TrackClientDescriptor>& client,
2370 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002371{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002372 // cannot start playback of STREAM_TTS if any other output is being used
2373 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002374
2375 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002376 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002377 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002378 auto clientStrategy = client->strategy();
2379 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002380 if (stream == AUDIO_STREAM_TTS) {
2381 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002382 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002383 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002384 return INVALID_OPERATION;
2385 } else {
2386 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2387 }
2388 } else {
2389 // some playback other than beacon starts
2390 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2391 }
2392
Eric Laurent77305a62016-07-25 16:39:22 -07002393 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002394 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002395 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002396
François Gaffie11d30102018-11-02 16:09:09 +01002397 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002398 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002399 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002400 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002401 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002402 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002403 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002404 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002405 } else {
2406 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002407 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002408 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2409 AUDIO_FORMAT_DEFAULT);
2410 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2411 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002412 }
2413
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002414 // requiresMuteCheck is false when we can bypass mute strategy.
2415 // It covers a common case when there is no materially active audio
2416 // and muting would result in unnecessary delay and dropped audio.
2417 const uint32_t outputLatencyMs = outputDesc->latency();
2418 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002419 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002420
Eric Laurente552edb2014-03-10 17:42:56 -07002421 // increment usage count for this stream on the requested output:
2422 // NOTE that the usage count is the same for duplicated output and hardware output which is
2423 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002424 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002425
2426 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002427 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002428 // Preferred device may be exclusive, use only if no other active clients on this output
2429 devices = DeviceVector(
2430 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2431 } else {
2432 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2433 }
François Gaffie11d30102018-11-02 16:09:09 +01002434 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002435 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002436 }
2437 }
Eric Laurente552edb2014-03-10 17:42:56 -07002438
François Gaffiec005e562018-11-06 15:04:49 +01002439 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002440 selectOutputForMusicEffects();
2441 }
2442
François Gaffie1c878552018-11-22 16:53:21 +01002443 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002444 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002445 if (devices.isEmpty()) {
2446 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002447 }
François Gaffiec005e562018-11-06 15:04:49 +01002448 bool shouldWait =
2449 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2450 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2451 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002452 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002453 const bool needToCloseBitPerfectOutput =
2454 (com::android::media::audioserver::
2455 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2456 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2457 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002458 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002459 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002460 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002461 // An output has a shared device if
2462 // - managed by the same hw module
2463 // - supports the currently selected device
2464 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002465 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002466
Eric Laurent77305a62016-07-25 16:39:22 -07002467 // force a device change if any other output is:
2468 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002469 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002470 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002471 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002472 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002473 // change the device currently selected by the other output.
2474 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002475 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002476 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002477 force = true;
2478 }
2479 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002480 // a notification so that audio focus effect can propagate, or that a mute/unmute
2481 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002482 const uint32_t latencyMs = desc->latency();
2483 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2484
2485 if (shouldWait && isActive && (waitMs < latencyMs)) {
2486 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002487 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002488
2489 // Require mute check if another output is on a shared device
2490 // and currently active to have proper drain and avoid pops.
2491 // Note restoring AudioTracks onto this output needs to invoke
2492 // a volume ramp if there is no mute.
2493 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002494
2495 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2496 outputsToReopen.push_back(desc);
2497 }
Eric Laurente552edb2014-03-10 17:42:56 -07002498 }
2499 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002500
jiabin220eea12024-05-17 17:55:20 +00002501 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002502 // If the output is open with preferred mixer attributes, but the routed device is
2503 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2504 // changed.
2505 return DEAD_OBJECT;
2506 }
jiabin220eea12024-05-17 17:55:20 +00002507 for (auto& outputToReopen : outputsToReopen) {
2508 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2509 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002510 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302511 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2512 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002513
Eric Laurente552edb2014-03-10 17:42:56 -07002514 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002515 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002516 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002517 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002518 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002519 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002520 outputDesc->useHwGain() /*force*/)) {
2521 // request AudioService to reinitialize the volume curves asynchronously
2522 ALOGE("checkAndSetVolume failed, requesting volume range init");
2523 mpClientInterface->onVolumeRangeInitRequest();
2524 };
Eric Laurente552edb2014-03-10 17:42:56 -07002525
2526 // update the outputs if starting an output with a stream that can affect notification
2527 // routing
2528 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002529
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002530 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002531 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002532 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002533 }
Eric Laurentdc462862016-07-19 12:29:53 -07002534
2535 if (waitMs > muteWaitMs) {
2536 *delayMs = waitMs - muteWaitMs;
2537 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002538
2539 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2540 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2541 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2542 // change occurs after the MixerThread starts and causes a stream volume
2543 // glitch.
2544 //
2545 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002546 }
Eric Laurentdc462862016-07-19 12:29:53 -07002547
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002548 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002549 mEngine->getForceUse(
2550 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002551 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002552 }
2553
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 // Automatically enable the remote submix input when output is started on a re routing mix
2555 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002556 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2557 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002558 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2559 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2560 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002561 "remote-submix",
2562 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002563 }
2564
Eric Laurent96d1dda2022-03-14 17:14:19 +01002565 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2566
Eric Laurente552edb2014-03-10 17:42:56 -07002567 return NO_ERROR;
2568}
2569
Eric Laurent96d1dda2022-03-14 17:14:19 +01002570void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2571 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2572 bool isUnicastActive = isLeUnicastActive();
2573
2574 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002575 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002576 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2577 for (size_t i = 0; i < mOutputs.size(); i++) {
2578 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2579 if (desc != ignoredOutput && desc->isActive()
2580 && ((isUnicastActive &&
2581 !desc->devices().
2582 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2583 || (wasUnicastActive &&
2584 !desc->devices().getDevicesFromTypes(
2585 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2586 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2587 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002588 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002589 // If the device is using preferred mixer attributes, the output need to reopen
2590 // with default configuration when the new selected devices are different from
2591 // current routing devices.
2592 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2593 continue;
2594 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302595 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002596 // re-apply device specific volume if not done by setOutputDevice()
2597 if (!force) {
2598 applyStreamVolumes(desc, newDevices.types(), delayMs);
2599 }
2600 }
2601 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002602 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002603 }
2604}
2605
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002607{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002608 ALOGV("%s portId %d", __FUNCTION__, portId);
2609
2610 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2611 if (outputDesc == 0) {
2612 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002613 return BAD_VALUE;
2614 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002615 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002616
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002617 if (client->hasPreferredDevice(true)) {
2618 // playback activity with preferred device impacts routing occurred, inform upper layers
2619 mpClientInterface->onRoutingUpdated();
2620 }
2621
Eric Laurent97ac8712018-07-27 18:59:02 -07002622 ALOGV("stopOutput() output %d, stream %d, session %d",
2623 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002624
Eric Laurent97ac8712018-07-27 18:59:02 -07002625 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002626
Eric Laurent733ce942017-12-07 12:18:25 -08002627 if (status == NO_ERROR ) {
2628 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002629 } else {
2630 return status;
2631 }
2632
2633 if (outputDesc->devices().size() == 1) {
2634 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2635 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002636 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002637 if (info != nullptr && info->getUid() == client->uid()) {
2638 info->decreaseActiveClient();
2639 if (info->getActiveClientCount() == 0) {
2640 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002641 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002642 }
2643 }
jiabin220eea12024-05-17 17:55:20 +00002644 if (com::android::media::audioserver::
2645 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2646 !outputReopened && outputDesc->isBitPerfect()) {
2647 // Only need to update the clients' internal mute when the output is bit-perfect and it
2648 // is not reopened.
2649 updateClientsInternalMute(outputDesc);
2650 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002651 }
2652 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002653}
2654
Eric Laurent97ac8712018-07-27 18:59:02 -07002655status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2656 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002657{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002658 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002659 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002660 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002661 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002662
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002663 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2664
François Gaffie1c878552018-11-22 16:53:21 +01002665 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2666 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002667 // Automatically disable the remote submix input when output is stopped on a
2668 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002669 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002670 if (isSingleDeviceType(
2671 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002672 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002673 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002674 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2675 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002676 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002677 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002678 }
2679 }
2680 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002681 if (client->hasPreferredDevice(true) &&
2682 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002683 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002684 forceDeviceUpdate = true;
2685 }
2686
Eric Laurente552edb2014-03-10 17:42:56 -07002687 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002688 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002689
Eric Laurente552edb2014-03-10 17:42:56 -07002690 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002691 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002692 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002693 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002694
2695 // If the routing does not change, if an output is routed on a device using HwGain
2696 // (aka setAudioPortConfig) and there are still active clients following different
2697 // volume group(s), force reapply volume
2698 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2699 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2700
Eric Laurente552edb2014-03-10 17:42:56 -07002701 // delay the device switch by twice the latency because stopOutput() is executed when
2702 // the track stop() command is received and at that time the audio track buffer can
2703 // still contain data that needs to be drained. The latency only covers the audio HAL
2704 // and kernel buffers. Also the latency does not always include additional delay in the
2705 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302706 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002707 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002708
2709 // force restoring the device selection on other active outputs if it differs from the
2710 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002711 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002712 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002713 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002714 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002715 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002716 desc->isActive() &&
2717 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002718 (newDevices != desc->devices())) {
2719 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2720 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002721
jiabin220eea12024-05-17 17:55:20 +00002722 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002723 // If the device is using preferred mixer attributes, the output need to
2724 // reopen with default configuration when the new selected devices are
2725 // different from current routing devices.
2726 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2727 continue;
2728 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302729 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002730
Eric Laurent57de36c2016-09-28 16:59:11 -07002731 // re-apply device specific volume if not done by setOutputDevice()
2732 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002733 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002734 }
Eric Laurente552edb2014-03-10 17:42:56 -07002735 }
2736 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002737 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002738 // update the outputs if stopping one with a stream that can affect notification routing
2739 handleNotificationRoutingForStream(stream);
2740 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002741
2742 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2743 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002744 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002745 }
2746
François Gaffiec005e562018-11-06 15:04:49 +01002747 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002748 selectOutputForMusicEffects();
2749 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002750
2751 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2752
Eric Laurente552edb2014-03-10 17:42:56 -07002753 return NO_ERROR;
2754 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002755 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002756 return INVALID_OPERATION;
2757 }
2758}
2759
jiabinbce0c1d2020-10-05 11:20:18 -07002760bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002761{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002762 ALOGV("%s portId %d", __FUNCTION__, portId);
2763
2764 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2765 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002766 // If an output descriptor is closed due to a device routing change,
2767 // then there are race conditions with releaseOutput from tracks
2768 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2769 // destroyed shortly thereafter.
2770 //
2771 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002772 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002773 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002774 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002775
2776 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002777
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302778 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2779 if (outputDesc->isClientActive(client)) {
2780 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2781 stopOutput(portId);
2782 }
2783
Eric Laurent8fc147b2018-07-22 19:13:55 -07002784 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2785 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002786 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002787 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002788 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002789 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002790 if (--outputDesc->mDirectOpenCount == 0) {
2791 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002792 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002793 }
2794 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302795
Andy Hung39efb7a2018-09-26 15:39:28 -07002796 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002797 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2798 // The output is pending reopened to query dynamic profiles and
2799 // there is no active clients
2800 closeOutput(outputDesc->mIoHandle);
2801 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2802 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2803 if (newOutputDesc == nullptr) {
2804 ALOGE("%s failed to open output", __func__);
2805 }
2806 return true;
2807 }
2808 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002809}
2810
Eric Laurentcaf7f482014-11-25 17:50:47 -08002811status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2812 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002813 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002814 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002815 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002816 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002817 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002818 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002819 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002820 audio_port_handle_t *portId,
2821 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002822{
François Gaffiec005e562018-11-06 15:04:49 +01002823 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002824 "flags %#x attributes=%s requested device ID %d",
2825 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2826 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002827
Eric Laurentad2e7b92017-09-14 20:06:42 -07002828 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002829 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002830 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002831 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002832 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002833 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 sp<RecordClientDescriptor> clientDesc;
2835 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002836 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002837 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002838
2839 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2840 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2841 return INVALID_OPERATION;
2842 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002843
Francois Gaffie716e1432019-01-14 16:58:59 +01002844 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2845 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002846 }
2847
Paul McLean466dc8e2015-04-17 13:15:36 -06002848 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002849 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002850 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002851
Eric Laurentad2e7b92017-09-14 20:06:42 -07002852 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2853 // possible
2854 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2855 *input != AUDIO_IO_HANDLE_NONE) {
2856 ssize_t index = mInputs.indexOfKey(*input);
2857 if (index < 0) {
2858 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2859 status = BAD_VALUE;
2860 goto error;
2861 }
2862 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002863 RecordClientVector clients = inputDesc->getClientsForSession(session);
2864 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002865 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2866 status = BAD_VALUE;
2867 goto error;
2868 }
2869 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2870 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002871 // corresponds to a new client and is only permitted from the same UID.
2872 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002873 if (clients.size() > 1) {
2874 for (const auto& client : clients) {
2875 // The client map is ordered by key values (portId) and portIds are allocated
2876 // incrementaly. So the first client in this list is the one opened by audio flinger
2877 // when the mmap stream is created and should be ignored as it does not correspond
2878 // to an actual client
2879 if (client == *clients.cbegin()) {
2880 continue;
2881 }
2882 if (uid != client->uid() && !client->isSilenced()) {
2883 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2884 uid, client->portId(), client->uid());
2885 status = INVALID_OPERATION;
2886 goto error;
2887 }
Eric Laurent331679c2018-04-16 17:03:16 -07002888 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002889 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002890 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002891 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002892
Eric Laurentfecbceb2021-02-09 14:46:43 +01002893 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002894 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002895 }
2896
2897 *input = AUDIO_IO_HANDLE_NONE;
2898 *inputType = API_INPUT_INVALID;
2899
Francois Gaffie716e1432019-01-14 16:58:59 +01002900 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002901 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002902 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002903 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002904 ALOGW("%s could not find input mix for attr %s",
2905 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002906 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002907 }
jiabinc1de2df2019-05-07 14:26:40 -07002908 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2909 String8(attr->tags + strlen("addr=")),
2910 AUDIO_FORMAT_DEFAULT);
2911 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002912 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002913 __func__, attributes.source, attributes.tags);
2914 status = BAD_VALUE;
2915 goto error;
2916 }
2917
Kevin Rocard25f9b052019-02-27 15:08:54 -08002918 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2919 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2920 } else {
2921 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2922 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002923 if (virtualDeviceId) {
2924 *virtualDeviceId = policyMix->mVirtualDeviceId;
2925 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002926 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002927 if (explicitRoutingDevice != nullptr) {
2928 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002929 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002930 // Prevent from storing invalid requested device id in clients
2931 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002932 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002933 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2934 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002935 }
François Gaffie11d30102018-11-02 16:09:09 +01002936 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002937 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002938 status = BAD_VALUE;
2939 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002940 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002941 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2942 *inputType = API_INPUT_MIX_CAPTURE;
2943 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002944 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2945 // there is an external policy, but this input is attached to a mix of recorders,
2946 // meaning it receives audio injected into the framework, so the recorder doesn't
2947 // know about it and is therefore considered "legacy"
2948 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002949
2950 if (virtualDeviceId) {
2951 *virtualDeviceId = policyMix->mVirtualDeviceId;
2952 }
François Gaffie11d30102018-11-02 16:09:09 +01002953 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002954 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002955 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002956 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002957 } else {
2958 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002959 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002960
Eric Laurent599c7582015-12-07 18:05:55 -08002961 }
2962
François Gaffiec005e562018-11-06 15:04:49 +01002963 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002964 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002965 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002966 AudioProfileVector profiles;
2967 status_t ret = getProfilesForDevices(
2968 DeviceVector(device), profiles, flags, true /*isInput*/);
2969 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002970 const auto channels = profiles[0]->getChannels();
2971 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2972 config->channel_mask = *channels.begin();
2973 }
2974 const auto sampleRates = profiles[0]->getSampleRates();
2975 if (!sampleRates.empty() &&
2976 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2977 config->sample_rate = *sampleRates.begin();
2978 }
jiabinf1c73972022-04-14 16:28:52 -07002979 config->format = profiles[0]->getFormat();
2980 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002981 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002982 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002983
Marvin Ramine5a122d2023-12-07 13:57:59 +01002984
2985 if (policyMix != nullptr && virtualDeviceId != nullptr) {
2986 *virtualDeviceId = policyMix->mVirtualDeviceId;
2987 }
2988
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989exit:
2990
François Gaffiec005e562018-11-06 15:04:49 +01002991 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2992 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002993
Francois Gaffie716e1432019-01-14 16:58:59 +01002994 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002995 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002996 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002997
Mikhail Naganov2996f672019-04-18 12:29:59 -07002998 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002999 requestedDeviceId, attributes.source, flags,
3000 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003001 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003002 // Move (if found) effect for the client session to its input
3003 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003004 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003005
3006 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3007 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003008
Eric Laurent599c7582015-12-07 18:05:55 -08003009 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003010
3011error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003012 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003013}
3014
3015
François Gaffie11d30102018-11-02 16:09:09 +01003016audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003017 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003018 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003019 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003020 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003021 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003022{
3023 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003024 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003025 bool isSoundTrigger = false;
3026
François Gaffiec005e562018-11-06 15:04:49 +01003027 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003028 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3029 if (index >= 0) {
3030 input = mSoundTriggerSessions.valueFor(session);
3031 isSoundTrigger = true;
3032 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3033 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3034 } else {
3035 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003036 }
François Gaffiec005e562018-11-06 15:04:49 +01003037 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003038 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003039 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003040 }
3041
Carter Hsua3abb402021-10-26 11:11:20 +08003042 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3043 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3044 }
3045
Eric Laurentfe231122017-11-17 17:48:06 -08003046 // sampling rate and flags may be updated by getInputProfile
3047 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3048 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003049 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003050 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003051 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003052 // find a compatible input profile (not necessarily identical in parameters)
3053 sp<IOProfile> profile = getInputProfile(
3054 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3055 if (profile == nullptr) {
3056 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003057 }
jiabin2fd710d2022-05-02 23:20:22 +00003058
Glenn Kasten05ddca52016-02-11 08:17:12 -08003059 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003060 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003061 if (samplingRate == 0) {
3062 samplingRate = profileSamplingRate;
3063 }
Eric Laurente552edb2014-03-10 17:42:56 -07003064
Eric Laurent322b4d22015-04-03 15:57:54 -07003065 if (profile->getModuleHandle() == 0) {
3066 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003067 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003068 }
3069
Eric Laurentec376dc2021-04-08 20:41:22 +02003070 // Reuse an already opened input if a client with the same session ID already exists
3071 // on that input
3072 for (size_t i = 0; i < mInputs.size(); i++) {
3073 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3074 if (desc->mProfile != profile) {
3075 continue;
3076 }
3077 RecordClientVector clients = desc->clientsList();
3078 for (const auto &client : clients) {
3079 if (session == client->session()) {
3080 return desc->mIoHandle;
3081 }
3082 }
3083 }
3084
Eric Laurentc71b11b2024-06-03 12:54:53 +00003085 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003086 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003087 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3088 // First pick best candidate for preemption (there may not be any):
3089 // - Preempt and input if:
3090 // - It has only strictly lower priority use cases than the new client
3091 // - It has equal priority use cases than the new client, was not
3092 // opened thanks to preemption or has been active since opened.
3093 // - Order the preemption candidates by inactive first and priority second
3094 sp<AudioInputDescriptor> closeCandidate;
3095 int leastCloseRank = INT_MAX;
3096 static const int sCloseActive = 0x100;
3097
3098 for (size_t i = 0; i < mInputs.size(); i++) {
3099 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3100 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003101 continue;
3102 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003103 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3104 if (topPrioClient == nullptr) {
3105 continue;
3106 }
3107 int topPrio = source_priority(topPrioClient->source());
3108 if (topPrio < source_priority(attributes.source)
3109 || (topPrio == source_priority(attributes.source)
3110 && !desc->isPreemptor())) {
3111 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3112 if (closeRank < leastCloseRank) {
3113 leastCloseRank = closeRank;
3114 closeCandidate = desc;
3115 }
3116 }
3117 }
3118
3119 if (closeCandidate != nullptr) {
3120 closeInput(closeCandidate->mIoHandle);
3121 // Mark the new input as being issued from a preemption
3122 // so that is will not be preempted later
3123 isPreemptor = true;
3124 } else {
3125 // Then pick the best reusable input (There is always one)
3126 // The order of preference is:
3127 // 1) active inputs with same use case as the new client
3128 // 2) inactive inputs with same use case
3129 // 3) active inputs with different use cases
3130 // 4) inactive inputs with different use cases
3131 sp<AudioInputDescriptor> reuseCandidate;
3132 int leastReuseRank = INT_MAX;
3133 static const int sReuseDifferentUseCase = 0x100;
3134
3135 for (size_t i = 0; i < mInputs.size(); i++) {
3136 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3137 if (desc->mProfile != profile) {
3138 continue;
3139 }
3140 int reuseRank = sReuseDifferentUseCase;
3141 for (const auto& client: desc->getClientIterable()) {
3142 if (client->source() == attributes.source) {
3143 reuseRank = 0;
3144 break;
3145 }
3146 }
3147 reuseRank += desc->isActive() ? 0 : 1;
3148 if (reuseRank < leastReuseRank) {
3149 leastReuseRank = reuseRank;
3150 reuseCandidate = desc;
3151 }
3152 }
3153 return reuseCandidate->mIoHandle;
3154 }
3155 } else { // fix_input_sharing_logic()
3156 for (size_t i = 0; i < mInputs.size(); ) {
3157 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3158 if (desc->mProfile != profile) {
3159 i++;
3160 continue;
3161 }
3162 // if sound trigger, reuse input if used by other sound trigger on same session
3163 // else
3164 // reuse input if active client app is not in IDLE state
3165 //
3166 RecordClientVector clients = desc->clientsList();
3167 bool doClose = false;
3168 for (const auto& client : clients) {
3169 if (isSoundTrigger != client->isSoundTrigger()) {
3170 continue;
3171 }
3172 if (client->isSoundTrigger()) {
3173 if (session == client->session()) {
3174 return desc->mIoHandle;
3175 }
3176 continue;
3177 }
3178 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003179 return desc->mIoHandle;
3180 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003181 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003182 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003183 if (doClose) {
3184 closeInput(desc->mIoHandle);
3185 } else {
3186 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003187 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003188 }
3189 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003190 }
3191
Eric Laurentc71b11b2024-06-03 12:54:53 +00003192 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3193 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003194
Eric Laurentfe231122017-11-17 17:48:06 -08003195 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3196 lConfig.sample_rate = profileSamplingRate;
3197 lConfig.channel_mask = profileChannelMask;
3198 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003199
François Gaffie11d30102018-11-02 16:09:09 +01003200 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003201
3202 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003203 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003204 (profileSamplingRate != lConfig.sample_rate) ||
3205 !audio_formats_match(profileFormat, lConfig.format) ||
3206 (profileChannelMask != lConfig.channel_mask)) {
3207 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003208 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003209 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003210 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003211 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003212 }
Eric Laurent599c7582015-12-07 18:05:55 -08003213 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003214 }
3215
Eric Laurentc722f302014-12-10 11:21:49 -08003216 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003217
Eric Laurent599c7582015-12-07 18:05:55 -08003218 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003219 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003220
Eric Laurent599c7582015-12-07 18:05:55 -08003221 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003222}
3223
Eric Laurent4eb58f12018-12-07 16:41:02 -08003224status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003225{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003226 ALOGV("%s portId %d", __FUNCTION__, portId);
3227
3228 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3229 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003230 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003231 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003232 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003233 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003234 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003235 if (client->active()) {
3236 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3237 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003238 }
3239
Eric Laurent8f42ea12018-08-08 09:08:25 -07003240 audio_session_t session = client->session();
3241
Eric Laurent4eb58f12018-12-07 16:41:02 -08003242 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003243
Eric Laurent4eb58f12018-12-07 16:41:02 -08003244 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003245
Eric Laurent4eb58f12018-12-07 16:41:02 -08003246 status_t status = inputDesc->start();
3247 if (status != NO_ERROR) {
3248 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003249 }
Eric Laurente552edb2014-03-10 17:42:56 -07003250
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003251 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003252 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003253 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003254
Eric Laurent8f42ea12018-08-08 09:08:25 -07003255 // indicate active capture to sound trigger service if starting capture from a mic on
3256 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003257 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003258 if (device != nullptr) {
3259 status = setInputDevice(input, device, true /* force */);
3260 } else {
3261 ALOGW("%s no new input device can be found for descriptor %d",
3262 __FUNCTION__, inputDesc->getId());
3263 status = BAD_VALUE;
3264 }
Eric Laurente552edb2014-03-10 17:42:56 -07003265
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003266 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003267 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003268 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003269 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003270 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3271 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003272 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003273 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003274
François Gaffie11d30102018-11-02 16:09:09 +01003275 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3276 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003277 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003278 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003279 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003280
Eric Laurent8f42ea12018-08-08 09:08:25 -07003281 // automatically enable the remote submix output when input is started if not
3282 // used by a policy mix of type MIX_TYPE_RECORDERS
3283 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003284 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003285 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003286 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003287 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003288 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3289 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003290 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003291 if (address != "") {
3292 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3293 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003294 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003295 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003296 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003297 } else if (status != NO_ERROR) {
3298 // Restore client activity state.
3299 inputDesc->setClientActive(client, false);
3300 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003301 }
3302
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003303 ALOGV("%s input %d source = %d status = %d exit",
3304 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003305
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003306 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003307}
3308
Eric Laurent8fc147b2018-07-22 19:13:55 -07003309status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003310{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003311 ALOGV("%s portId %d", __FUNCTION__, portId);
3312
3313 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3314 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003315 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003316 return BAD_VALUE;
3317 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003318 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003319 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003320 if (!client->active()) {
3321 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003322 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003323 }
Carter Hsue6139d52021-07-08 10:30:20 +08003324 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003325 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003326
Eric Laurent8f42ea12018-08-08 09:08:25 -07003327 inputDesc->stop();
3328 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003329 auto current_source = inputDesc->source();
3330 setInputDevice(input, getNewInputDevice(inputDesc),
3331 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003332 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003333 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003335 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003336 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3337 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003338 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003339 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003340
3341 // automatically disable the remote submix output when input is stopped if not
3342 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003343 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003344 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003345 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003346 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003347 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3348 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003349 }
3350 if (address != "") {
3351 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3352 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003353 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003354 }
3355 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003356 resetInputDevice(input);
3357
3358 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3359 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003360 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3361 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003362 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003363 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003364 }
3365 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003366 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003367 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003368}
3369
Eric Laurent8fc147b2018-07-22 19:13:55 -07003370void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003371{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003372 ALOGV("%s portId %d", __FUNCTION__, portId);
3373
3374 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3375 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003376 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003377 return;
3378 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003379 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003380 audio_io_handle_t input = inputDesc->mIoHandle;
3381
Eric Laurent8f42ea12018-08-08 09:08:25 -07003382 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003383
Andy Hung39efb7a2018-09-26 15:39:28 -07003384 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003385
3386 // If no more clients are present in this session, park effects to an orphan chain
3387 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3388 if (clientsOnSession.size() == 0) {
3389 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3390 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003391 if (inputDesc->getClientCount() > 0) {
3392 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003393 return;
3394 }
3395
Eric Laurent05b90f82014-08-27 15:32:29 -07003396 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003397 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003398 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003399}
3400
Eric Laurent8f42ea12018-08-08 09:08:25 -07003401void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003402{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003403 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003404
3405 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003406 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003407 }
3408}
3409
Eric Laurent8f42ea12018-08-08 09:08:25 -07003410void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3411{
3412 stopInput(portId);
3413 releaseInput(portId);
3414}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003415
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003416bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3417 if (input->clientsList().size() == 0
3418 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3419 return true;
3420 }
3421 for (const auto& client : input->clientsList()) {
3422 sp<DeviceDescriptor> device =
3423 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3424 client->session());
3425 if (!input->supportedDevices().contains(device)) {
3426 return true;
3427 }
3428 }
3429 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3430 return false;
3431}
3432
Eric Laurent0dd51852019-04-19 18:18:58 -07003433void AudioPolicyManager::checkCloseInputs() {
3434 // After connecting or disconnecting an input device, close input if:
3435 // - it has no client (was just opened to check profile) OR
3436 // - none of its supported devices are connected anymore OR
3437 // - one of its clients cannot be routed to one of its supported
3438 // devices anymore. Otherwise update device selection
3439 std::vector<audio_io_handle_t> inputsToClose;
3440 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003441 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003442 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003443 }
3444 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003445 for (const audio_io_handle_t handle : inputsToClose) {
3446 ALOGV("%s closing input %d", __func__, handle);
3447 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003448 }
Eric Laurentd4692962014-05-05 18:13:44 -07003449}
3450
Vlad Popa87e0e582024-05-20 18:49:20 -07003451status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3452 const char *address __unused,
3453 bool enabled,
3454 audio_stream_type_t streamToDriveAbs)
3455{
3456 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3457 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3458 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3459 toString(streamToDriveAbs).c_str());
3460 return BAD_VALUE;
3461 }
3462
3463 if (enabled) {
3464 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3465 } else {
3466 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3467 }
3468
3469 return NO_ERROR;
3470}
3471
François Gaffie251c7f02018-11-07 10:41:08 +01003472void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003473{
3474 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003475 if (indexMin < 0 || indexMax < 0) {
3476 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3477 return;
3478 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003479 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003480
3481 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003482 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3483 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003484 continue;
3485 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003486 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003487 }
Eric Laurente552edb2014-03-10 17:42:56 -07003488}
3489
Eric Laurente0720872014-03-11 09:30:41 -07003490status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003491 int index,
3492 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003493{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003494 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003495 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3496 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3497 return NO_ERROR;
3498 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003499 ALOGV("%s: stream %s attributes=%s", __func__,
3500 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003501 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003502}
3503
Eric Laurente0720872014-03-11 09:30:41 -07003504status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003505 int *index,
3506 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003507{
François Gaffiec005e562018-11-06 15:04:49 +01003508 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3509 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003510 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003511 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003512 deviceTypes = mEngine->getOutputDevicesForStream(
3513 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003514 }
jiabin9a3361e2019-10-01 09:38:30 -07003515 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003516}
3517
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003518status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003519 int index,
3520 audio_devices_t device)
3521{
3522 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003523 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3524 if (group == VOLUME_GROUP_NONE) {
3525 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003526 return BAD_VALUE;
3527 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003528 ALOGV("%s: group %d matching with %s index %d",
3529 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003530 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003531 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003532 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003533 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3534 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3535 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3536 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003537 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3538
3539 status = setVolumeCurveIndex(index, device, curves);
3540 if (status != NO_ERROR) {
3541 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3542 return status;
3543 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003544
jiabin9a3361e2019-10-01 09:38:30 -07003545 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003546 auto curCurvAttrs = curves.getAttributes();
3547 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3548 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003549 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003550 } else if (!curves.getStreamTypes().empty()) {
3551 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003552 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003553 } else {
3554 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3555 return BAD_VALUE;
3556 }
jiabin9a3361e2019-10-01 09:38:30 -07003557 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3558 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003559
François Gaffiecfe17322018-11-07 13:41:29 +01003560 // update volume on all outputs and streams matching the following:
3561 // - The requested stream (or a stream matching for volume control) is active on the output
3562 // - The device (or devices) selected by the engine for this stream includes
3563 // the requested device
3564 // - For non default requested device, currently selected device on the output is either the
3565 // requested device or one of the devices selected by the engine for this stream
3566 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3567 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003568 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003569 for (size_t i = 0; i < mOutputs.size(); i++) {
3570 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003571 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003572
jiabin9a3361e2019-10-01 09:38:30 -07003573 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3574 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003575 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003576
3577 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003578 continue;
3579 }
3580 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3581 curDevices.find(device) == curDevices.end()) {
3582 continue;
3583 }
3584 bool applyVolume = false;
3585 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3586 curSrcDevices.insert(device);
3587 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003588 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3589 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003590 } else {
3591 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3592 }
3593 if (!applyVolume) {
3594 continue; // next output
3595 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003596 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3597 // If a higher priority strategy is active, and the output is routed to a device with a
3598 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003599 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003600 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003601 // If the volume source is active with higher priority source, ensure at least Sw Muted
3602 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003603 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3604 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3605 false /*preferredDevice*/);
3606 if (activeClients.empty()) {
3607 continue;
3608 }
3609 bool isPreempted = false;
3610 bool isHigherPriority = productStrategy < strategy;
3611 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003612 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003613 ALOGV("%s: Strategy=%d (\nrequester:\n"
3614 " group %d, volumeGroup=%d attributes=%s)\n"
3615 " higher priority source active:\n"
3616 " volumeGroup=%d attributes=%s) \n"
3617 " on output %zu, bailing out", __func__, productStrategy,
3618 group, group, toString(attributes).c_str(),
3619 client->volumeSource(), toString(client->attributes()).c_str(), i);
3620 applyVolume = false;
3621 isPreempted = true;
3622 break;
3623 }
3624 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003625 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003626 applyVolume = true;
3627 }
3628 }
3629 if (isPreempted || applyVolume) {
3630 break;
3631 }
3632 }
3633 if (!applyVolume) {
3634 continue; // next output
3635 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003636 }
François Gaffieed91f582020-01-31 10:35:37 +01003637 //FIXME: workaround for truncated touch sounds
3638 // delayed volume change for system stream to be removed when the problem is
3639 // handled by system UI
3640 status_t volStatus = checkAndSetVolume(
3641 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003642 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003643 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3644 if (volStatus != NO_ERROR) {
3645 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003646 }
3647 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003648
3649 // update voice volume if the an active call route exists
3650 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3651 && (curSrcDevices.find(
3652 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3653 != curSrcDevices.end())) {
3654 bool isVoiceVolSrc;
3655 bool isBtScoVolSrc;
3656 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3657 isVoiceVolSrc, isBtScoVolSrc, __func__)
3658 && (isVoiceVolSrc || isBtScoVolSrc)) {
3659 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3660 }
3661 }
3662
François Gaffiecfe17322018-11-07 13:41:29 +01003663 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3664 return status;
3665}
3666
François Gaffieaaac0fd2018-11-22 17:56:39 +01003667status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003668 audio_devices_t device,
3669 IVolumeCurves &volumeCurves)
3670{
3671 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3672 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003673 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3674 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003675 (index > volumeCurves.getVolumeIndexMax())) {
3676 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3677 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3678 return BAD_VALUE;
3679 }
3680 if (!audio_is_output_device(device)) {
3681 return BAD_VALUE;
3682 }
3683
3684 // Force max volume if stream cannot be muted
3685 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3686
François Gaffieaaac0fd2018-11-22 17:56:39 +01003687 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003688 volumeCurves.addCurrentVolumeIndex(device, index);
3689 return NO_ERROR;
3690}
3691
3692status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3693 int &index,
3694 audio_devices_t device)
3695{
3696 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3697 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003698 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003699 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003700 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003701 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003702 }
jiabin9a3361e2019-10-01 09:38:30 -07003703 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003704}
3705
3706status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3707 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003708 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003709{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003710 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003711 return BAD_VALUE;
3712 }
jiabin9a3361e2019-10-01 09:38:30 -07003713 index = curves.getVolumeIndex(deviceTypes);
3714 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003715 return NO_ERROR;
3716}
3717
3718status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3719 int &index)
3720{
3721 index = getVolumeCurves(attr).getVolumeIndexMin();
3722 return NO_ERROR;
3723}
3724
3725status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3726 int &index)
3727{
3728 index = getVolumeCurves(attr).getVolumeIndexMax();
3729 return NO_ERROR;
3730}
3731
Eric Laurent36829f92017-04-07 19:04:42 -07003732audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003733{
3734 // select one output among several suitable for global effects.
3735 // The priority is as follows:
3736 // 1: An offloaded output. If the effect ends up not being offloadable,
3737 // AudioFlinger will invalidate the track and the offloaded output
3738 // will be closed causing the effect to be moved to a PCM output.
3739 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003740 // 3: The primary output
3741 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003742
François Gaffiec005e562018-11-06 15:04:49 +01003743 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3744 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003745 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003746
Eric Laurent36829f92017-04-07 19:04:42 -07003747 if (outputs.size() == 0) {
3748 return AUDIO_IO_HANDLE_NONE;
3749 }
Eric Laurente552edb2014-03-10 17:42:56 -07003750
Eric Laurent36829f92017-04-07 19:04:42 -07003751 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3752 bool activeOnly = true;
3753
3754 while (output == AUDIO_IO_HANDLE_NONE) {
3755 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3756 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3757 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3758
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003759 for (audio_io_handle_t output : outputs) {
3760 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003761 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003762 continue;
3763 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003764 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3765 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003766 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003767 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003768 }
3769 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003770 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003771 }
3772 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003773 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003774 }
3775 }
3776 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3777 output = outputOffloaded;
3778 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3779 output = outputDeepBuffer;
3780 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3781 output = outputPrimary;
3782 } else {
3783 output = outputs[0];
3784 }
3785 activeOnly = false;
3786 }
3787
3788 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003789 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3790 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003791 mMusicEffectOutput = output;
3792 }
3793
3794 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003795 return output;
3796}
3797
Eric Laurent36829f92017-04-07 19:04:42 -07003798audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3799{
3800 return selectOutputForMusicEffects();
3801}
3802
Eric Laurente0720872014-03-11 09:30:41 -07003803status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003804 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003805 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003806 int session,
3807 int id)
3808{
Shunkai Yao29d10572024-03-19 04:31:47 +00003809 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003810 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003811 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003812 index = mInputs.indexOfKey(io);
3813 if (index < 0) {
3814 ALOGW("registerEffect() unknown io %d", io);
3815 return INVALID_OPERATION;
3816 }
Eric Laurente552edb2014-03-10 17:42:56 -07003817 }
3818 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003819 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3820 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3821 || strategy == PRODUCT_STRATEGY_NONE));
3822 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003823}
3824
Eric Laurentc241b0d2018-11-28 09:08:49 -08003825status_t AudioPolicyManager::unregisterEffect(int id)
3826{
3827 if (mEffects.getEffect(id) == nullptr) {
3828 return INVALID_OPERATION;
3829 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003830 if (mEffects.isEffectEnabled(id)) {
3831 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3832 setEffectEnabled(id, false);
3833 }
3834 return mEffects.unregisterEffect(id);
3835}
3836
3837status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3838{
3839 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3840 if (effect == nullptr) {
3841 return INVALID_OPERATION;
3842 }
3843
3844 status_t status = mEffects.setEffectEnabled(id, enabled);
3845 if (status == NO_ERROR) {
3846 mInputs.trackEffectEnabled(effect, enabled);
3847 }
3848 return status;
3849}
3850
Eric Laurent6c796322019-04-09 14:13:17 -07003851
3852status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3853{
3854 mEffects.moveEffects(ids, io);
3855 return NO_ERROR;
3856}
3857
Eric Laurentc75307b2015-03-17 15:29:32 -07003858bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3859{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003860 auto vs = toVolumeSource(stream, false);
3861 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003862}
3863
3864bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3865{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003866 auto vs = toVolumeSource(stream, false);
3867 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003868}
3869
Eric Laurente0720872014-03-11 09:30:41 -07003870bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003871{
3872 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003873 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003874 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003875 return true;
3876 }
3877 }
3878 return false;
3879}
3880
Eric Laurent275e8e92014-11-30 15:14:47 -08003881// Register a list of custom mixes with their attributes and format.
3882// When a mix is registered, corresponding input and output profiles are
3883// added to the remote submix hw module. The profile contains only the
3884// parameters (sampling rate, format...) specified by the mix.
3885// The corresponding input remote submix device is also connected.
3886//
3887// When a remote submix device is connected, the address is checked to select the
3888// appropriate profile and the corresponding input or output stream is opened.
3889//
3890// When capture starts, getInputForAttr() will:
3891// - 1 look for a mix matching the address passed in attribtutes tags if any
3892// - 2 if none found, getDeviceForInputSource() will:
3893// - 2.1 look for a mix matching the attributes source
3894// - 2.2 if none found, default to device selection by policy rules
3895// At this time, the corresponding output remote submix device is also connected
3896// and active playback use cases can be transferred to this mix if needed when reconnecting
3897// after AudioTracks are invalidated
3898//
3899// When playback starts, getOutputForAttr() will:
3900// - 1 look for a mix matching the address passed in attribtutes tags if any
3901// - 2 if none found, look for a mix matching the attributes usage
3902// - 3 if none found, default to device and output selection by policy rules.
3903
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003904status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003905{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003906 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3907 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003908 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003909 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003910 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003911 // examine each mix's route type
3912 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003913 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003914 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3915 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3916 ALOGE("Unsupported Policy Mix %zu of %zu: "
3917 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3918 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003919 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003920 break;
3921 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003922 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3923 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003924 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003925 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3926 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003927 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003928 rSubmixModule = mHwModules.getModuleFromName(
3929 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3930 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003931 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003932 i);
3933 res = INVALID_OPERATION;
3934 break;
3935 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003936 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003937
Eric Laurent97ac8712018-07-27 18:59:02 -07003938 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003939 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003940 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003941 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003942 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3943 } else {
3944 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3945 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003946 }
François Gaffie036e1e92015-03-19 10:16:24 +01003947
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003948 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003949 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003950 res = INVALID_OPERATION;
3951 break;
3952 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003953 audio_config_t outputConfig = mix.mFormat;
3954 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003955 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3956 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003957 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3958 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003959 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003960 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3961 audio_is_linear_pcm(outputConfig.format)
3962 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003963 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003964 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3965 audio_is_linear_pcm(inputConfig.format)
3966 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003967
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003968 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003969 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003970 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003971 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003972 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003973 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003974 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003975 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3976 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003977 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003978 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003979 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003980
3981 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3982 mix.mDeviceType, mix.mDeviceAddress,
3983 String8(), AUDIO_FORMAT_DEFAULT);
3984 if (device == nullptr) {
3985 res = INVALID_OPERATION;
3986 break;
3987 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003988
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003989 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003990 // First try to find an already opened output supporting the device
3991 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003992 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003993
Eric Laurentc529cf62020-04-17 18:19:10 -07003994 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003995 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003996 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003997 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003998 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003999 } else {
4000 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004001 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004002 }
4003 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004004 // If no output found, try to find a direct output profile supporting the device
4005 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4006 sp<HwModule> module = mHwModules[i];
4007 for (size_t j = 0;
4008 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4009 j++) {
4010 sp<IOProfile> profile = module->getOutputProfiles()[j];
4011 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4012 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4013 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004014 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004015 res = INVALID_OPERATION;
4016 } else {
4017 foundOutput = true;
4018 }
4019 }
4020 }
4021 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004022 if (res != NO_ERROR) {
4023 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004024 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004025 res = INVALID_OPERATION;
4026 break;
4027 } else if (!foundOutput) {
4028 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004029 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004030 res = INVALID_OPERATION;
4031 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004032 } else {
4033 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004034 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004035 }
Eric Laurentc722f302014-12-10 11:21:49 -08004036 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004037 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004038 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004039 if (audio_flags::audio_mix_ownership()) {
4040 // Only unregister mixes that were actually registered to not accidentally unregister
4041 // mixes that already existed previously.
4042 unregisterPolicyMixes(registeredMixes);
4043 registeredMixes.clear();
4044 } else {
4045 unregisterPolicyMixes(mixes);
4046 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004047 } else if (checkOutputs) {
4048 checkForDeviceAndOutputChanges();
4049 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004050 }
4051 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004052}
4053
4054status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4055{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004056 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004057 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004058 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004059 sp<HwModule> rSubmixModule;
4060 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004061 for (const auto& mix : mixes) {
4062 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004063
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004064 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004065 rSubmixModule = mHwModules.getModuleFromName(
4066 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4067 if (rSubmixModule == 0) {
4068 res = INVALID_OPERATION;
4069 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004070 }
4071 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004072
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004073 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004074
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004075 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004076 res = INVALID_OPERATION;
4077 continue;
4078 }
4079
Marvin Ramin0783e202024-03-05 12:45:50 +01004080 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004081 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004082 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4083 status_t currentRes =
4084 setDeviceConnectionStateInt(device,
4085 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4086 address.c_str(),
4087 "remote-submix",
4088 AUDIO_FORMAT_DEFAULT);
4089 if (!audio_flags::audio_mix_ownership()) {
4090 res = currentRes;
4091 }
4092 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004093 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004094 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004095 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004096 }
4097 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004098 }
jiabin5740f082019-08-19 15:08:30 -07004099 rSubmixModule->removeOutputProfile(address.c_str());
4100 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004101
Kevin Rocard153f92d2018-12-18 18:33:28 -08004102 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004103 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004104 res = INVALID_OPERATION;
4105 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004106 } else {
4107 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004108 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004109 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004110 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004111
4112 if (res == NO_ERROR && checkOutputs) {
4113 checkForDeviceAndOutputChanges();
4114 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004115 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004116 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004117}
4118
Marvin Raminbdefaf02023-11-01 09:10:32 +01004119status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4120 if (!audio_flags::audio_mix_test_api()) {
4121 return INVALID_OPERATION;
4122 }
4123
4124 _aidl_return.clear();
4125 _aidl_return.reserve(mPolicyMixes.size());
4126 for (const auto &policyMix: mPolicyMixes) {
4127 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4128 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4129 policyMix->mCbFlags);
4130 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004131 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004132 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004133 }
4134
Vlad Popaa5d73f32024-03-08 16:05:38 -08004135 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004136 return OK;
4137}
4138
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004139status_t AudioPolicyManager::updatePolicyMix(
4140 const AudioMix& mix,
4141 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4142 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4143 if (res == NO_ERROR) {
4144 checkForDeviceAndOutputChanges();
4145 updateCallAndOutputRouting();
4146 }
4147 return res;
4148}
4149
Mikhail Naganov100f0122018-11-29 11:22:16 -08004150void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4151{
4152 size_t i = 0;
4153 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4154 for (const auto& fmt : mManualSurroundFormats) {
4155 if (i++ != 0) dst->append(", ");
4156 std::string sfmt;
4157 FormatConverter::toString(fmt, sfmt);
4158 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4159 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4160 }
4161}
4162
Eric Laurentc529cf62020-04-17 18:19:10 -07004163// Returns true if all devices types match the predicate and are supported by one HW module
4164bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004165 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004166 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004167 const char *context,
4168 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004169 for (size_t i = 0; i < devices.size(); i++) {
4170 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004171 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004172 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004173 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004174 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004175 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004176 return false;
4177 }
4178 }
4179 return true;
4180}
4181
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004182void AudioPolicyManager::changeOutputDevicesMuteState(
4183 const AudioDeviceTypeAddrVector& devices) {
4184 ALOGVV("%s() num devices %zu", __func__, devices.size());
4185
4186 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4187 getSoftwareOutputsForDevices(devices);
4188
4189 for (size_t i = 0; i < outputs.size(); i++) {
4190 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4191 DeviceVector prevDevices = outputDesc->devices();
4192 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4193 }
4194}
4195
4196std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4197 const AudioDeviceTypeAddrVector& devices) const
4198{
4199 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4200 DeviceVector deviceDescriptors;
4201 for (size_t j = 0; j < devices.size(); j++) {
4202 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4203 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4204 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4205 ALOGE("%s: device type %#x address %s not supported or not an output device",
4206 __func__, devices[j].mType, devices[j].getAddress());
4207 continue;
4208 }
4209 deviceDescriptors.add(desc);
4210 }
4211 for (size_t i = 0; i < mOutputs.size(); i++) {
4212 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4213 continue;
4214 }
4215 outputs.push_back(mOutputs.valueAt(i));
4216 }
4217 return outputs;
4218}
4219
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004220status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004221 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004222 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004223 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4224 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004225 }
4226 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004227 if (res != NO_ERROR) {
4228 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4229 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004230 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004231
4232 checkForDeviceAndOutputChanges();
4233 updateCallAndOutputRouting();
4234
4235 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004236}
4237
4238status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4239 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004240 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4241 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004242 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004243 __FUNCTION__, uid);
4244 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004245 }
4246
Eric Laurentc529cf62020-04-17 18:19:10 -07004247 checkForDeviceAndOutputChanges();
4248 updateCallAndOutputRouting();
4249
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004250 return res;
4251}
4252
Eric Laurent2517af32020-11-25 15:31:27 +01004253
jiabin0a488932020-08-07 17:32:40 -07004254status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4255 device_role_t role,
4256 const AudioDeviceTypeAddrVector &devices) {
4257 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4258 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004259
Eric Laurentc529cf62020-04-17 18:19:10 -07004260 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004261 return BAD_VALUE;
4262 }
jiabin0a488932020-08-07 17:32:40 -07004263 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004264 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004265 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4266 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004267 return status;
4268 }
4269
4270 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004271
4272 bool forceVolumeReeval = false;
4273 // FIXME: workaround for truncated touch sounds
4274 // to be removed when the problem is handled by system UI
4275 uint32_t delayMs = 0;
4276 if (strategy == mCommunnicationStrategy) {
4277 forceVolumeReeval = true;
4278 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4279 updateInputRouting();
4280 }
4281 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004282
4283 return NO_ERROR;
4284}
4285
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004286void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4287 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004288{
4289 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004290 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004291 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004292 // Only apply special touch sound delay once
4293 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004294 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004295 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004296 for (size_t i = 0; i < mOutputs.size(); i++) {
4297 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4298 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004299 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4300 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004301 // As done in setDeviceConnectionState, we could also fix default device issue by
4302 // preventing the force re-routing in case of default dev that distinguishes on address.
4303 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004304 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004305 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004306 // If the device is using preferred mixer attributes, the output need to reopen
4307 // with default configuration when the new selected devices are different from
4308 // current routing devices.
4309 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4310 continue;
4311 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304312
4313 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4314 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004315 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004316 // Only apply special touch sound delay once
4317 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004318 }
4319 if (forceVolumeReeval && !newDevices.isEmpty()) {
4320 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4321 }
4322 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004323 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004324 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004325}
4326
Eric Laurent2517af32020-11-25 15:31:27 +01004327void AudioPolicyManager::updateInputRouting() {
4328 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304329 // Skip for hotword recording as the input device switch
4330 // is handled within sound trigger HAL
4331 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4332 continue;
4333 }
Eric Laurent2517af32020-11-25 15:31:27 +01004334 auto newDevice = getNewInputDevice(activeDesc);
4335 // Force new input selection if the new device can not be reached via current input
4336 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4337 setInputDevice(activeDesc->mIoHandle, newDevice);
4338 } else {
4339 closeInput(activeDesc->mIoHandle);
4340 }
4341 }
4342}
4343
Paul Wang5d7cdb52022-11-22 09:45:06 +00004344status_t
4345AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4346 device_role_t role,
4347 const AudioDeviceTypeAddrVector &devices) {
4348 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4349 dumpAudioDeviceTypeAddrVector(devices).c_str());
4350
Eric Laurent78fedbf2023-03-09 14:40:44 +01004351 if (!areAllDevicesSupported(
4352 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004353 return BAD_VALUE;
4354 }
4355 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4356 if (status != NO_ERROR) {
4357 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4358 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4359 return status;
4360 }
4361
4362 checkForDeviceAndOutputChanges();
4363
4364 bool forceVolumeReeval = false;
4365 // TODO(b/263479999): workaround for truncated touch sounds
4366 // to be removed when the problem is handled by system UI
4367 uint32_t delayMs = 0;
4368 if (strategy == mCommunnicationStrategy) {
4369 forceVolumeReeval = true;
4370 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4371 updateInputRouting();
4372 }
4373 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4374
4375 return NO_ERROR;
4376}
4377
4378status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4379 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004380{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004381 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004382
Paul Wang5d7cdb52022-11-22 09:45:06 +00004383 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004384 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004385 ALOGW_IF(status != NAME_NOT_FOUND,
4386 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004387 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004388 return status;
4389 }
4390
4391 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004392
4393 bool forceVolumeReeval = false;
4394 // FIXME: workaround for truncated touch sounds
4395 // to be removed when the problem is handled by system UI
4396 uint32_t delayMs = 0;
4397 if (strategy == mCommunnicationStrategy) {
4398 forceVolumeReeval = true;
4399 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4400 updateInputRouting();
4401 }
4402 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004403
4404 return NO_ERROR;
4405}
4406
jiabin0a488932020-08-07 17:32:40 -07004407status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4408 device_role_t role,
4409 AudioDeviceTypeAddrVector &devices) {
4410 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004411}
4412
Jiabin Huang3b98d322020-09-03 17:54:16 +00004413status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4414 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4415 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4416 dumpAudioDeviceTypeAddrVector(devices).c_str());
4417
Mikhail Naganov55773032020-10-01 15:08:13 -07004418 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004419 return BAD_VALUE;
4420 }
4421 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4422 ALOGW_IF(status != NO_ERROR,
4423 "Engine could not set preferred devices %s for audio source %d role %d",
4424 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4425
4426 return status;
4427}
4428
4429status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4430 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4431 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4432 dumpAudioDeviceTypeAddrVector(devices).c_str());
4433
Mikhail Naganov55773032020-10-01 15:08:13 -07004434 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004435 return BAD_VALUE;
4436 }
4437 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4438 ALOGW_IF(status != NO_ERROR,
4439 "Engine could not add preferred devices %s for audio source %d role %d",
4440 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4441
Eric Laurent2517af32020-11-25 15:31:27 +01004442 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004443 return status;
4444}
4445
4446status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4447 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4448{
4449 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4450 dumpAudioDeviceTypeAddrVector(devices).c_str());
4451
Eric Laurent78fedbf2023-03-09 14:40:44 +01004452 if (!areAllDevicesSupported(
4453 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004454 return BAD_VALUE;
4455 }
4456
4457 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4458 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004459 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004460 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004461 if (status == NO_ERROR) {
4462 updateInputRouting();
4463 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004464 return status;
4465}
4466
4467status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4468 device_role_t role) {
4469 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4470
4471 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004472 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004473 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004474 if (status == NO_ERROR) {
4475 updateInputRouting();
4476 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004477 return status;
4478}
4479
4480status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4481 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4482 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4483}
4484
Oscar Azucena90e77632019-11-27 17:12:28 -08004485status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004486 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004487 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004488 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4489 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004490 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004491 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4492 if (status != NO_ERROR) {
4493 ALOGE("%s() could not set device affinity for userId %d",
4494 __FUNCTION__, userId);
4495 return status;
4496 }
4497
4498 // reevaluate outputs for all devices
4499 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004500 changeOutputDevicesMuteState(devices);
4501 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4502 true /* skipDelays */);
4503 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004504
4505 return NO_ERROR;
4506}
4507
4508status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004509 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004510 AudioDeviceTypeAddrVector devices;
4511 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004512 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4513 if (status != NO_ERROR) {
4514 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4515 __FUNCTION__, userId);
4516 return status;
4517 }
4518
4519 // reevaluate outputs for all devices
4520 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004521 changeOutputDevicesMuteState(devices);
4522 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4523 true /* skipDelays */);
4524 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004525
4526 return NO_ERROR;
4527}
4528
Andy Hungc29d82b2018-10-05 12:23:17 -07004529void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004530{
Andy Hungc29d82b2018-10-05 12:23:17 -07004531 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004532 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004533 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004534 std::string stateLiteral;
4535 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004536 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004537 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4538 "communications", "media", "record", "dock", "system",
4539 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4540 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4541 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004542 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4543 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4544 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4545 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4546 dst->append(" (MANUAL: ");
4547 dumpManualSurroundFormats(dst);
4548 dst->append(")");
4549 }
4550 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004551 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004552 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4553 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004554 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004555 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004556
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004557 dst->append("\n");
4558 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4559 dst->append("\n");
4560 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004561 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004562 mOutputs.dump(dst);
4563 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004564 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004565 mAudioPatches.dump(dst);
4566 mPolicyMixes.dump(dst);
4567 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004568
Kevin Rocardb99cc752019-03-21 20:52:24 -07004569 dst->appendFormat(" AllowedCapturePolicies:\n");
4570 for (auto& policy : mAllowedCapturePolicies) {
4571 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4572 }
4573
jiabina84c3d32022-12-02 18:59:55 +00004574 dst->appendFormat(" Preferred mixer audio configuration:\n");
4575 for (const auto it : mPreferredMixerAttrInfos) {
4576 dst->appendFormat(" - device port id: %d\n", it.first);
4577 for (const auto preferredMixerInfoIt : it.second) {
4578 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4579 preferredMixerInfoIt.second->dump(dst);
4580 }
4581 }
4582
François Gaffiec005e562018-11-06 15:04:49 +01004583 dst->appendFormat("\nPolicy Engine dump:\n");
4584 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004585
4586 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4587 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4588 dst->appendFormat(" - device type: %s, driving stream %d\n",
4589 dumpDeviceTypes({it.first}).c_str(),
4590 mEngine->getVolumeGroupForAttributes(it.second));
4591 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004592}
4593
4594status_t AudioPolicyManager::dump(int fd)
4595{
4596 String8 result;
4597 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004598 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004599 return NO_ERROR;
4600}
4601
Kevin Rocardb99cc752019-03-21 20:52:24 -07004602status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4603{
4604 mAllowedCapturePolicies[uid] = capturePolicy;
4605 return NO_ERROR;
4606}
4607
Eric Laurente552edb2014-03-10 17:42:56 -07004608// This function checks for the parameters which can be offloaded.
4609// This can be enhanced depending on the capability of the DSP and policy
4610// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004611audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004612{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004613 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004614 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004615 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004616 offloadInfo.format,
4617 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4618 offloadInfo.has_video);
4619
jiabin2b9d5a12021-12-10 01:06:29 +00004620 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004621 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004622 }
4623
4624 // See if there is a profile to support this.
4625 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004626 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004627 offloadInfo.sample_rate,
4628 offloadInfo.format,
4629 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004630 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4631 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004632 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4633 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4634 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004635 if (profile == nullptr) {
4636 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4637 }
4638 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4639 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4640 }
4641 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004642}
4643
Michael Chana94fbb22018-04-24 14:31:19 +10004644bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4645 const audio_attributes_t& attributes) {
4646 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004647 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004648 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4649 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004650 config.sample_rate,
4651 config.format,
4652 config.channel_mask,
4653 output_flags,
4654 true /* directOnly */);
4655 ALOGV("%s() profile %sfound with name: %s, "
4656 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4657 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004658 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004659 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004660
4661 // also try the MSD module if compatible profile not found
4662 if (profile == nullptr) {
4663 profile = getMsdProfileForOutput(outputDevices,
4664 config.sample_rate,
4665 config.format,
4666 config.channel_mask,
4667 output_flags,
4668 true /* directOnly */);
4669 ALOGV("%s() MSD profile %sfound with name: %s, "
4670 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4671 __FUNCTION__, profile != 0 ? "" : "NOT ",
4672 (profile != 0 ? profile->getTagName().c_str() : "null"),
4673 config.sample_rate, config.format, config.channel_mask, output_flags);
4674 }
4675 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004676}
4677
jiabin2b9d5a12021-12-10 01:06:29 +00004678bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4679 bool durationIgnored) {
4680 if (mMasterMono) {
4681 return false; // no offloading if mono is set.
4682 }
4683
4684 // Check if offload has been disabled
4685 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4686 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4687 return false;
4688 }
4689
4690 // Check if stream type is music, then only allow offload as of now.
4691 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4692 {
4693 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4694 return false;
4695 }
4696
4697 //TODO: enable audio offloading with video when ready
4698 const bool allowOffloadWithVideo =
4699 property_get_bool("audio.offload.video", false /* default_value */);
4700 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4701 ALOGV("%s: has_video == true, returning false", __func__);
4702 return false;
4703 }
4704
4705 //If duration is less than minimum value defined in property, return false
4706 const int min_duration_secs = property_get_int32(
4707 "audio.offload.min.duration.secs", -1 /* default_value */);
4708 if (!durationIgnored) {
4709 if (min_duration_secs >= 0) {
4710 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4711 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4712 __func__, min_duration_secs);
4713 return false;
4714 }
4715 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4716 ALOGV("%s: Offload denied by duration < default min(=%u)",
4717 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4718 return false;
4719 }
4720 }
4721
4722 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4723 // creating an offloaded track and tearing it down immediately after start when audioflinger
4724 // detects there is an active non offloadable effect.
4725 // FIXME: We should check the audio session here but we do not have it in this context.
4726 // This may prevent offloading in rare situations where effects are left active by apps
4727 // in the background.
4728 if (mEffects.isNonOffloadableEffectEnabled()) {
4729 return false;
4730 }
4731
4732 return true;
4733}
4734
4735audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4736 const audio_config_t *config) {
4737 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4738 offloadInfo.format = config->format;
4739 offloadInfo.sample_rate = config->sample_rate;
4740 offloadInfo.channel_mask = config->channel_mask;
4741 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4742 offloadInfo.has_video = false;
4743 offloadInfo.is_streaming = false;
4744 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4745
4746 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4747 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4748 audio_flags_to_audio_output_flags(attr->flags, &flags);
4749 // only retain flags that will drive compressed offload or passthrough
4750 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4751 if (offloadPossible) {
4752 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4753 }
4754 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4755
Dorin Drimusfae3c642022-03-17 18:36:30 +01004756 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004757 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004758 DeviceVector outputDevices = engineOutputDevices;
4759 // the MSD module checks for different conditions and output devices
4760 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4761 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4762 continue;
4763 }
4764 outputDevices = getMsdAudioOutDevices();
4765 }
jiabin2b9d5a12021-12-10 01:06:29 +00004766 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004767 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004768 config->sample_rate, nullptr /*updatedSamplingRate*/,
4769 config->format, nullptr /*updatedFormat*/,
4770 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004771 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004772 continue;
4773 }
4774 // reject profiles not corresponding to a device currently available
4775 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4776 continue;
4777 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004778 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4779 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004780 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004781 != AUDIO_DIRECT_NOT_SUPPORTED) {
4782 // Already reports offload gapless supported. No need to report offload support.
4783 continue;
4784 }
4785 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4786 != AUDIO_OUTPUT_FLAG_NONE) {
4787 // If offload gapless is reported, no need to report offload support.
4788 directMode = (audio_direct_mode_t) ((directMode &
4789 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4790 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4791 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004792 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004793 }
4794 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004795 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004796 }
4797 }
4798 }
4799 return directMode;
4800}
4801
Dorin Drimusf2196d82022-01-03 12:11:18 +01004802status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4803 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004804 if (mEffects.isNonOffloadableEffectEnabled()) {
4805 return OK;
4806 }
jiabinf1c73972022-04-14 16:28:52 -07004807 DeviceVector devices;
4808 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004809 if (status != OK) {
4810 return status;
4811 }
4812 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4813 if (devices.empty()) {
4814 return OK; // no output devices for the attributes
4815 }
jiabinf1c73972022-04-14 16:28:52 -07004816 return getProfilesForDevices(devices, audioProfilesVector,
4817 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004818}
4819
jiabina84c3d32022-12-02 18:59:55 +00004820status_t AudioPolicyManager::getSupportedMixerAttributes(
4821 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4822 ALOGV("%s, portId=%d", __func__, portId);
4823 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4824 if (deviceDescriptor == nullptr) {
4825 ALOGE("%s the requested device is currently unavailable", __func__);
4826 return BAD_VALUE;
4827 }
jiabin96daffc2023-05-11 17:51:55 +00004828 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4829 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4830 deviceDescriptor->type());
4831 return BAD_VALUE;
4832 }
jiabina84c3d32022-12-02 18:59:55 +00004833 for (const auto& hwModule : mHwModules) {
4834 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4835 if (curProfile->supportsDevice(deviceDescriptor)) {
4836 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4837 }
4838 }
4839 }
4840 return NO_ERROR;
4841}
4842
4843status_t AudioPolicyManager::setPreferredMixerAttributes(
4844 const audio_attributes_t *attr,
4845 audio_port_handle_t portId,
4846 uid_t uid,
4847 const audio_mixer_attributes_t *mixerAttributes) {
4848 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4849 "mixerBehavior=%d}, uid=%d, portId=%u",
4850 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4851 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4852 mixerAttributes->mixer_behavior, uid, portId);
4853 if (attr->usage != AUDIO_USAGE_MEDIA) {
4854 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4855 return BAD_VALUE;
4856 }
4857 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4858 if (deviceDescriptor == nullptr) {
4859 ALOGE("%s the requested device is currently unavailable", __func__);
4860 return BAD_VALUE;
4861 }
4862 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4863 ALOGE("%s(%d), type=%d, is not a usb output device",
4864 __func__, portId, deviceDescriptor->type());
4865 return BAD_VALUE;
4866 }
4867
4868 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4869 audio_flags_to_audio_output_flags(attr->flags, &flags);
4870 flags = (audio_output_flags_t) (flags |
4871 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4872 sp<IOProfile> profile = nullptr;
4873 DeviceVector devices(deviceDescriptor);
4874 for (const auto& hwModule : mHwModules) {
4875 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4876 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004877 && curProfile->getCompatibilityScore(
4878 devices,
4879 mixerAttributes->config.sample_rate,
4880 nullptr /*updatedSamplingRate*/,
4881 mixerAttributes->config.format,
4882 nullptr /*updatedFormat*/,
4883 mixerAttributes->config.channel_mask,
4884 nullptr /*updatedChannelMask*/,
4885 flags,
4886 false /*exactMatchRequiredForInputFlags*/)
4887 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004888 profile = curProfile;
4889 break;
4890 }
4891 }
4892 }
4893 if (profile == nullptr) {
4894 ALOGE("%s, there is no compatible profile found", __func__);
4895 return BAD_VALUE;
4896 }
4897
4898 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4899 sp<PreferredMixerAttributesInfo>::make(
4900 uid, portId, profile, flags, *mixerAttributes);
4901 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4902 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4903
4904 // If 1) there is any client from the preferred mixer configuration owner that is currently
4905 // active and matches the strategy and 2) current output is on the preferred device and the
4906 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4907 // configuration.
4908 std::vector<audio_io_handle_t> outputsToReopen;
4909 for (size_t i = 0; i < mOutputs.size(); i++) {
4910 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004911 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4912 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004913 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004914 } else {
4915 for (const auto &client: output->getActiveClients()) {
4916 if (client->uid() == uid && client->strategy() == strategy) {
4917 client->setIsInvalid();
4918 outputsToReopen.push_back(output->mIoHandle);
4919 }
jiabina84c3d32022-12-02 18:59:55 +00004920 }
4921 }
4922 }
4923 }
4924 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4925 config.sample_rate = mixerAttributes->config.sample_rate;
4926 config.channel_mask = mixerAttributes->config.channel_mask;
4927 config.format = mixerAttributes->config.format;
4928 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004929 sp<SwAudioOutputDescriptor> desc =
4930 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4931 if (desc == nullptr) {
4932 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4933 continue;
4934 }
jiabin220eea12024-05-17 17:55:20 +00004935 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004936 }
4937
4938 return NO_ERROR;
4939}
4940
4941sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004942 audio_port_handle_t devicePortId,
4943 product_strategy_t strategy,
4944 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004945 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4946 if (it == mPreferredMixerAttrInfos.end()) {
4947 return nullptr;
4948 }
jiabind9a58d32023-06-01 17:57:30 +00004949 if (activeBitPerfectPreferred) {
4950 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004951 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004952 return info;
4953 }
4954 }
jiabina84c3d32022-12-02 18:59:55 +00004955 }
jiabind9a58d32023-06-01 17:57:30 +00004956 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4957 return strategyMatchedMixerAttrInfoIt == it->second.end()
4958 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004959}
4960
4961status_t AudioPolicyManager::getPreferredMixerAttributes(
4962 const audio_attributes_t *attr,
4963 audio_port_handle_t portId,
4964 audio_mixer_attributes_t* mixerAttributes) {
4965 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4966 portId, mEngine->getProductStrategyForAttributes(*attr));
4967 if (info == nullptr) {
4968 return NAME_NOT_FOUND;
4969 }
4970 *mixerAttributes = info->getMixerAttributes();
4971 return NO_ERROR;
4972}
4973
4974status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4975 audio_port_handle_t portId,
4976 uid_t uid) {
4977 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4978 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4979 if (preferredMixerAttrInfo == nullptr) {
4980 return NAME_NOT_FOUND;
4981 }
4982 if (preferredMixerAttrInfo->getUid() != uid) {
4983 ALOGE("%s, requested uid=%d, owned uid=%d",
4984 __func__, uid, preferredMixerAttrInfo->getUid());
4985 return PERMISSION_DENIED;
4986 }
4987 mPreferredMixerAttrInfos[portId].erase(strategy);
4988 if (mPreferredMixerAttrInfos[portId].empty()) {
4989 mPreferredMixerAttrInfos.erase(portId);
4990 }
4991
4992 // Reconfig existing output
4993 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4994 for (size_t i = 0; i < mOutputs.size(); i++) {
4995 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4996 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4997 }
4998 }
4999 for (const auto output : potentialOutputsToReopen) {
5000 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5001 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5002 preferredMixerAttrInfo->getFlags())) {
5003 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5004 }
5005 }
5006 return NO_ERROR;
5007}
5008
Eric Laurent6a94d692014-05-20 11:18:06 -07005009status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5010 audio_port_type_t type,
5011 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005012 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005013 unsigned int *generation)
5014{
jiabin19cdba52020-11-24 11:28:58 -08005015 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5016 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 return BAD_VALUE;
5018 }
5019 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005020 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 *num_ports = 0;
5022 }
5023
5024 size_t portsWritten = 0;
5025 size_t portsMax = *num_ports;
5026 *num_ports = 0;
5027 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005028 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5029 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005030 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005031 for (const auto& dev : mAvailableOutputDevices) {
5032 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005033 continue;
5034 }
5035 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005036 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005037 }
5038 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005039 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 }
5041 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005042 for (const auto& dev : mAvailableInputDevices) {
5043 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005044 continue;
5045 }
5046 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005047 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005048 }
5049 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005050 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 }
5052 }
5053 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5054 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5055 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5056 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5057 }
5058 *num_ports += mInputs.size();
5059 }
5060 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005061 size_t numOutputs = 0;
5062 for (size_t i = 0; i < mOutputs.size(); i++) {
5063 if (!mOutputs[i]->isDuplicated()) {
5064 numOutputs++;
5065 if (portsWritten < portsMax) {
5066 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5067 }
5068 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 }
Eric Laurent84c70242014-06-23 08:46:27 -07005070 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005071 }
5072 }
jiabina84c3d32022-12-02 18:59:55 +00005073
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005075 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005076 return NO_ERROR;
5077}
5078
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005079status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5080 std::vector<media::AudioPortFw>* _aidl_return) {
5081 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5082 audio_port_v7 port;
5083 dev->toAudioPort(&port);
5084 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5085 _aidl_return->push_back(std::move(aidlPort));
5086 return OK;
5087 };
5088
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005089 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005090 for (const auto& dev : module->getDeclaredDevices()) {
5091 if (role == media::AudioPortRole::NONE ||
5092 ((role == media::AudioPortRole::SOURCE)
5093 == audio_is_input_device(dev->type()))) {
5094 RETURN_STATUS_IF_ERROR(pushPort(dev));
5095 }
5096 }
5097 }
5098 return OK;
5099}
5100
jiabin19cdba52020-11-24 11:28:58 -08005101status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005102{
Eric Laurent99fcae42018-05-17 16:59:18 -07005103 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5104 return BAD_VALUE;
5105 }
5106 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5107 if (dev != 0) {
5108 dev->toAudioPort(port);
5109 return NO_ERROR;
5110 }
5111 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5112 if (dev != 0) {
5113 dev->toAudioPort(port);
5114 return NO_ERROR;
5115 }
5116 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5117 if (out != 0) {
5118 out->toAudioPort(port);
5119 return NO_ERROR;
5120 }
5121 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5122 if (in != 0) {
5123 in->toAudioPort(port);
5124 return NO_ERROR;
5125 }
5126 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005127}
5128
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005129status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5130 audio_patch_handle_t *handle,
5131 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005132{
François Gaffieafd4cea2019-11-18 15:50:22 +01005133 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005134 if (handle == NULL || patch == NULL) {
5135 return BAD_VALUE;
5136 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005137 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005138 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005139 return BAD_VALUE;
5140 }
5141 // only one source per audio patch supported for now
5142 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005143 return INVALID_OPERATION;
5144 }
Eric Laurent874c42872014-08-08 15:13:39 -07005145 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005146 return INVALID_OPERATION;
5147 }
Eric Laurent874c42872014-08-08 15:13:39 -07005148 for (size_t i = 0; i < patch->num_sinks; i++) {
5149 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5150 return INVALID_OPERATION;
5151 }
5152 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005153
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005154 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5155 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5156 if (srcDevice == nullptr || sinkDevice == nullptr) {
5157 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5158 return BAD_VALUE;
5159 }
5160 ALOGV("%s between source %s and sink %s", __func__,
5161 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5162 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5163 // Default attributes, default volume priority, not to infer with non raw audio patches.
5164 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5165 const struct audio_port_config *source = &patch->sources[0];
5166 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005167 new SourceClientDescriptor(
5168 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5169 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
5170 true);
5171 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005172
5173 status_t status =
5174 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5175
5176 if (status != NO_ERROR) {
5177 return INVALID_OPERATION;
5178 }
5179 mAudioSources.add(portId, sourceDesc);
5180 return NO_ERROR;
5181}
5182
5183status_t AudioPolicyManager::connectAudioSourceToSink(
5184 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5185 const struct audio_patch *patch,
5186 audio_patch_handle_t &handle,
5187 uid_t uid, uint32_t delayMs)
5188{
5189 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5190 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5191 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5192 return INVALID_OPERATION;
5193 }
5194 sourceDesc->connect(handle, sinkDevice);
5195 if (isMsdPatch(handle)) {
5196 return NO_ERROR;
5197 }
5198 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5199 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5200 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5201 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5202 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5203 goto FailurePatchAdded;
5204 }
5205 status = swOutput->start();
5206 if (status != NO_ERROR) {
5207 goto FailureSourceAdded;
5208 }
5209 swOutput->addClient(sourceDesc);
5210 status = startSource(swOutput, sourceDesc, &delayMs);
5211 if (status != NO_ERROR) {
5212 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5213 goto FailureSourceActive;
5214 }
5215 if (delayMs != 0) {
5216 usleep(delayMs * 1000);
5217 }
5218 return NO_ERROR;
5219
5220FailureSourceActive:
5221 swOutput->stop();
5222 releaseOutput(sourceDesc->portId());
5223FailureSourceAdded:
5224 sourceDesc->setSwOutput(nullptr);
5225FailurePatchAdded:
5226 releaseAudioPatchInternal(handle);
5227 return INVALID_OPERATION;
5228}
5229
5230status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5231 audio_patch_handle_t *handle,
5232 uid_t uid, uint32_t delayMs,
5233 const sp<SourceClientDescriptor>& sourceDesc)
5234{
5235 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 sp<AudioPatch> patchDesc;
5237 ssize_t index = mAudioPatches.indexOfKey(*handle);
5238
François Gaffieafd4cea2019-11-18 15:50:22 +01005239 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5240 patch->sources[0].role,
5241 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005242#if LOG_NDEBUG == 0
5243 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005244 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5245 patch->sinks[i].role,
5246 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005247 }
5248#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005249
5250 if (index >= 0) {
5251 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005252 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5253 __func__, mUidCached, patchDesc->getUid(), uid);
5254 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005255 return INVALID_OPERATION;
5256 }
5257 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005258 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 }
5260
5261 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005262 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005264 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005265 return BAD_VALUE;
5266 }
Eric Laurent84c70242014-06-23 08:46:27 -07005267 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5268 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 if (patchDesc != 0) {
5270 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005271 ALOGV("%s source id differs for patch current id %d new id %d",
5272 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005273 return BAD_VALUE;
5274 }
5275 }
Eric Laurent874c42872014-08-08 15:13:39 -07005276 DeviceVector devices;
5277 for (size_t i = 0; i < patch->num_sinks; i++) {
5278 // Only support mix to devices connection
5279 // TODO add support for mix to mix connection
5280 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005281 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005282 return INVALID_OPERATION;
5283 }
5284 sp<DeviceDescriptor> devDesc =
5285 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5286 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005287 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005288 return BAD_VALUE;
5289 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005290
jiabin66acc432024-02-06 00:57:36 +00005291 if (outputDesc->mProfile->getCompatibilityScore(
5292 DeviceVector(devDesc),
5293 patch->sources[0].sample_rate,
5294 nullptr, // updatedSamplingRate
5295 patch->sources[0].format,
5296 nullptr, // updatedFormat
5297 patch->sources[0].channel_mask,
5298 nullptr, // updatedChannelMask
5299 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005300 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005301 return INVALID_OPERATION;
5302 }
5303 devices.add(devDesc);
5304 }
5305 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005306 return INVALID_OPERATION;
5307 }
Eric Laurent874c42872014-08-08 15:13:39 -07005308
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005310 ALOGV("%s setting device %s on output %d",
5311 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305312 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005313 index = mAudioPatches.indexOfKey(*handle);
5314 if (index >= 0) {
5315 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005316 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005317 }
5318 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005319 patchDesc->setUid(uid);
5320 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005322 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 return INVALID_OPERATION;
5324 }
5325 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5326 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5327 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005328 // only one sink supported when connecting an input device to a mix
5329 if (patch->num_sinks > 1) {
5330 return INVALID_OPERATION;
5331 }
François Gaffie53615e22015-03-19 09:24:12 +01005332 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005333 if (inputDesc == NULL) {
5334 return BAD_VALUE;
5335 }
5336 if (patchDesc != 0) {
5337 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5338 return BAD_VALUE;
5339 }
5340 }
François Gaffie11d30102018-11-02 16:09:09 +01005341 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005342 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005343 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005344 return BAD_VALUE;
5345 }
5346
jiabin66acc432024-02-06 00:57:36 +00005347 if (inputDesc->mProfile->getCompatibilityScore(
5348 DeviceVector(device),
5349 patch->sinks[0].sample_rate,
5350 nullptr, /*updatedSampleRate*/
5351 patch->sinks[0].format,
5352 nullptr, /*updatedFormat*/
5353 patch->sinks[0].channel_mask,
5354 nullptr, /*updatedChannelMask*/
5355 // FIXME for the parameter type,
5356 // and the NONE
5357 (audio_output_flags_t)
5358 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005359 return INVALID_OPERATION;
5360 }
5361 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005362 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005363 device->toString().c_str(), inputDesc->mIoHandle);
5364 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005365 index = mAudioPatches.indexOfKey(*handle);
5366 if (index >= 0) {
5367 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005368 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005369 }
5370 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005371 patchDesc->setUid(uid);
5372 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005373 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005374 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005375 return INVALID_OPERATION;
5376 }
5377 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5378 // device to device connection
5379 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005380 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005381 return BAD_VALUE;
5382 }
5383 }
François Gaffie11d30102018-11-02 16:09:09 +01005384 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005385 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005386 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005387 return BAD_VALUE;
5388 }
Eric Laurent874c42872014-08-08 15:13:39 -07005389
Eric Laurent6a94d692014-05-20 11:18:06 -07005390 //update source and sink with our own data as the data passed in the patch may
5391 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005392 PatchBuilder patchBuilder;
5393 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005394
5395 // if first sink is to MSD, establish single MSD patch
5396 if (getMsdAudioOutDevices().contains(
5397 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5398 ALOGV("%s patching to MSD", __FUNCTION__);
5399 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5400 goto installPatch;
5401 }
5402
François Gaffieafd4cea2019-11-18 15:50:22 +01005403 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5404 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005405
Eric Laurent874c42872014-08-08 15:13:39 -07005406 for (size_t i = 0; i < patch->num_sinks; i++) {
5407 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005408 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005409 return INVALID_OPERATION;
5410 }
François Gaffie11d30102018-11-02 16:09:09 +01005411 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005412 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005413 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005414 return BAD_VALUE;
5415 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005416 audio_port_config sinkPortConfig = {};
5417 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5418 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005419
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005420 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5421 // volume management purpose (tracking activity)
5422 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5423 // in config XML to reach the sink so that is can be declared as available.
5424 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005425 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005426 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005427 // take care of dynamic routing for SwOutput selection,
5428 audio_attributes_t attributes = sourceDesc->attributes();
5429 audio_stream_type_t stream = sourceDesc->stream();
5430 audio_attributes_t resultAttr;
5431 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5432 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005433 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5434 config.channel_mask =
5435 (audio_channel_mask_get_representation(sourceMask)
5436 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5437 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005438 config.format = sourceDesc->config().format;
5439 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5440 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5441 bool isRequestedDeviceForExclusiveUse = false;
5442 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005443 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005444 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005445 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5446 &stream, sourceDesc->uid(), &config, &flags,
5447 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005448 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005449 if (output == AUDIO_IO_HANDLE_NONE) {
5450 ALOGV("%s no output for device %s",
5451 __FUNCTION__, sinkDevice->toString().c_str());
5452 return INVALID_OPERATION;
5453 }
5454 outputDesc = mOutputs.valueFor(output);
5455 if (outputDesc->isDuplicated()) {
5456 ALOGE("%s output is duplicated", __func__);
5457 return INVALID_OPERATION;
5458 }
François Gaffie7e39df22022-04-26 12:48:49 +02005459 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5460 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005461 } else {
5462 // Same for "raw patches" aka created from createAudioPatch API
5463 SortedVector<audio_io_handle_t> outputs =
5464 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5465 // if the sink device is reachable via an opened output stream, request to
5466 // go via this output stream by adding a second source to the patch
5467 // description
5468 output = selectOutput(outputs);
5469 if (output == AUDIO_IO_HANDLE_NONE) {
5470 ALOGE("%s no output available for internal patch sink", __func__);
5471 return INVALID_OPERATION;
5472 }
5473 outputDesc = mOutputs.valueFor(output);
5474 if (outputDesc->isDuplicated()) {
5475 ALOGV("%s output for device %s is duplicated",
5476 __func__, sinkDevice->toString().c_str());
5477 return INVALID_OPERATION;
5478 }
François Gaffie7e39df22022-04-26 12:48:49 +02005479 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005480 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005481 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005482 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005483 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005484 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005485 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5486 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005487 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5488 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005489 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005490 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005491 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005492 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005493 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005494 return INVALID_OPERATION;
5495 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005496 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005497 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005498 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005499 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005500 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005501 srcMixPortConfig.ext.mix.usecase.stream =
5502 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005503 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5504 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005505 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005506 }
Eric Laurent83b88082014-06-20 18:31:16 -07005507 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005508 }
5509 // TODO: check from routing capabilities in config file and other conflicting patches
5510
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005511installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005512 status_t status = installPatch(
5513 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005514 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005515 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005516 return INVALID_OPERATION;
5517 }
5518 } else {
5519 return BAD_VALUE;
5520 }
5521 } else {
5522 return BAD_VALUE;
5523 }
5524 return NO_ERROR;
5525}
5526
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005527status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005528{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005529 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005530 ssize_t index = mAudioPatches.indexOfKey(handle);
5531
5532 if (index < 0) {
5533 return BAD_VALUE;
5534 }
5535 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005536 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5537 __func__, mUidCached, patchDesc->getUid(), uid);
5538 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005539 return INVALID_OPERATION;
5540 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005541 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5542 for (size_t i = 0; i < mAudioSources.size(); i++) {
5543 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5544 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5545 portId = sourceDesc->portId();
5546 break;
5547 }
5548 }
5549 return portId != AUDIO_PORT_HANDLE_NONE ?
5550 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005551}
Eric Laurent6a94d692014-05-20 11:18:06 -07005552
François Gaffieafd4cea2019-11-18 15:50:22 +01005553status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005554 uint32_t delayMs,
5555 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005556{
5557 ALOGV("%s patch %d", __func__, handle);
5558 if (mAudioPatches.indexOfKey(handle) < 0) {
5559 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5560 return BAD_VALUE;
5561 }
5562 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005563 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005564 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005565 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005566 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005567 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005568 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005569 return BAD_VALUE;
5570 }
5571
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305572 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005573 getNewOutputDevices(outputDesc, true /*fromCache*/),
5574 true,
5575 0,
5576 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005577 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5578 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005579 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005580 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005581 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005582 return BAD_VALUE;
5583 }
5584 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005585 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005586 true,
5587 NULL);
5588 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005589 status_t status =
5590 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5591 ALOGV("%s patch panel returned %d patchHandle %d",
5592 __func__, status, patchDesc->getAfHandle());
5593 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005594 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005595 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005596 // SW or HW Bridge
5597 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5598 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005599 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005600 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5601 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5602 outputDesc = sourceDesc->swOutput().promote();
5603 }
5604 if (outputDesc == nullptr) {
5605 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5606 // releaseOutput has already called closeOutput in case of direct output
5607 return NO_ERROR;
5608 }
François Gaffie7e39df22022-04-26 12:48:49 +02005609 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005610 // While using a HwBridge, force reconsidering device only if not reusing an existing
5611 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005612 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005613 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5614 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5615 // Reconsider device only for cases:
5616 // 1 / Active Output
5617 // 2 / Inactive Output previously hosting HwBridge
5618 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5619 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5620 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305621 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005622 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5623 outputDesc->devices(),
5624 force,
5625 0,
5626 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005627 } else {
5628 return BAD_VALUE;
5629 }
5630 } else {
5631 return BAD_VALUE;
5632 }
5633 return NO_ERROR;
5634}
5635
5636status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5637 struct audio_patch *patches,
5638 unsigned int *generation)
5639{
François Gaffie53615e22015-03-19 09:24:12 +01005640 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005641 return BAD_VALUE;
5642 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005643 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005644 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005645}
5646
Eric Laurente1715a42014-05-20 11:30:42 -07005647status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005648{
Eric Laurente1715a42014-05-20 11:30:42 -07005649 ALOGV("setAudioPortConfig()");
5650
5651 if (config == NULL) {
5652 return BAD_VALUE;
5653 }
5654 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5655 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005656 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5657 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005658 }
5659
Eric Laurenta121f902014-06-03 13:32:54 -07005660 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005661 if (config->type == AUDIO_PORT_TYPE_MIX) {
5662 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005663 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005664 if (outputDesc == NULL) {
5665 return BAD_VALUE;
5666 }
Eric Laurent84c70242014-06-23 08:46:27 -07005667 ALOG_ASSERT(!outputDesc->isDuplicated(),
5668 "setAudioPortConfig() called on duplicated output %d",
5669 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005670 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005671 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005672 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005673 if (inputDesc == NULL) {
5674 return BAD_VALUE;
5675 }
Eric Laurenta121f902014-06-03 13:32:54 -07005676 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005677 } else {
5678 return BAD_VALUE;
5679 }
5680 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5681 sp<DeviceDescriptor> deviceDesc;
5682 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5683 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5684 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5685 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5686 } else {
5687 return BAD_VALUE;
5688 }
5689 if (deviceDesc == NULL) {
5690 return BAD_VALUE;
5691 }
Eric Laurenta121f902014-06-03 13:32:54 -07005692 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005693 } else {
5694 return BAD_VALUE;
5695 }
5696
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005697 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005698 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5699 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005700 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005701 audioPortConfig->toAudioPortConfig(&newConfig, config);
5702 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005703 }
Eric Laurenta121f902014-06-03 13:32:54 -07005704 if (status != NO_ERROR) {
5705 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005706 }
Eric Laurente1715a42014-05-20 11:30:42 -07005707
5708 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005709}
5710
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005711void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5712{
Eric Laurentd60560a2015-04-10 11:31:20 -07005713 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005714 clearAudioPatches(uid);
5715 clearSessionRoutes(uid);
5716}
5717
Eric Laurent6a94d692014-05-20 11:18:06 -07005718void AudioPolicyManager::clearAudioPatches(uid_t uid)
5719{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005720 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005721 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005722 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005723 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005724 }
5725 }
5726}
5727
François Gaffiec005e562018-11-06 15:04:49 +01005728void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005729{
François Gaffiec005e562018-11-06 15:04:49 +01005730 // Take the first attributes following the product strategy as it is used to retrieve the routed
5731 // device. All attributes wihin a strategy follows the same "routing strategy"
5732 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5733 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005734 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005735 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005736 for (size_t j = 0; j < mOutputs.size(); j++) {
5737 if (mOutputs.keyAt(j) == ouptutToSkip) {
5738 continue;
5739 }
5740 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005741 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005742 continue;
5743 }
5744 // If the default device for this strategy is on another output mix,
5745 // invalidate all tracks in this strategy to force re connection.
5746 // Otherwise select new device on the output mix.
5747 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005748 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005749 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005750 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005751 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005752 // If the device is using preferred mixer attributes, the output need to reopen
5753 // with default configuration when the new selected devices are different from
5754 // current routing devices.
5755 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5756 continue;
5757 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305758 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005759 }
5760 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005761 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005762}
5763
5764void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5765{
5766 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005767 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005768 for (size_t i = 0; i < mOutputs.size(); i++) {
5769 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005770 for (const auto& client : outputDesc->getClientIterable()) {
5771 if (client->hasPreferredDevice() && client->uid() == uid) {
5772 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005773 auto clientStrategy = client->strategy();
5774 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5775 end(affectedStrategies)) {
5776 continue;
5777 }
5778 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005779 }
5780 }
5781 }
5782 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005783 for (const auto& strategy : affectedStrategies) {
5784 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005785 }
5786
5787 // remove input routes associated with this uid
5788 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005789 for (size_t i = 0; i < mInputs.size(); i++) {
5790 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005791 for (const auto& client : inputDesc->getClientIterable()) {
5792 if (client->hasPreferredDevice() && client->uid() == uid) {
5793 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5794 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005795 }
5796 }
5797 }
5798 // reroute inputs if necessary
5799 SortedVector<audio_io_handle_t> inputsToClose;
5800 for (size_t i = 0; i < mInputs.size(); i++) {
5801 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005802 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005803 inputsToClose.add(inputDesc->mIoHandle);
5804 }
5805 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005806 for (const auto& input : inputsToClose) {
5807 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005808 }
5809}
5810
Eric Laurentd60560a2015-04-10 11:31:20 -07005811void AudioPolicyManager::clearAudioSources(uid_t uid)
5812{
5813 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005814 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5815 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005816 stopAudioSource(mAudioSources.keyAt(i));
5817 }
5818 }
5819}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005820
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005821status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5822 audio_io_handle_t *ioHandle,
5823 audio_devices_t *device)
5824{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005825 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5826 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005827 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005828 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5829 if (deviceDesc == nullptr) {
5830 return INVALID_OPERATION;
5831 }
5832 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005833
François Gaffiedf372692015-03-19 10:43:27 +01005834 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005835}
5836
Eric Laurentd60560a2015-04-10 11:31:20 -07005837status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005838 const audio_attributes_t *attributes,
5839 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005840 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005841{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005842 ALOGV("%s", __FUNCTION__);
5843 *portId = AUDIO_PORT_HANDLE_NONE;
5844
5845 if (source == NULL || attributes == NULL || portId == NULL) {
5846 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5847 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005848 return BAD_VALUE;
5849 }
5850
Eric Laurentd60560a2015-04-10 11:31:20 -07005851 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5852 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005853 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5854 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005855 return INVALID_OPERATION;
5856 }
5857
François Gaffie11d30102018-11-02 16:09:09 +01005858 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005859 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005860 String8(source->ext.device.address),
5861 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005862 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005863 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005864 return BAD_VALUE;
5865 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005866
jiabin4ef93452019-09-10 14:29:54 -07005867 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005868
François Gaffieaaac0fd2018-11-22 17:56:39 +01005869 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005870 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005871 mEngine->getStreamTypeForAttributes(*attributes),
5872 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005873 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005874
5875 status_t status = connectAudioSource(sourceDesc);
5876 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005877 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005878 }
5879 return status;
5880}
5881
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005882status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005883{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005884 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005885
5886 // make sure we only have one patch per source.
5887 disconnectAudioSource(sourceDesc);
5888
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005889 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005890 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5891 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5892 sourceDesc->srcDevice()->type(),
5893 String8(sourceDesc->srcDevice()->address().c_str()),
5894 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005895 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005896 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005897 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005898 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005899 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5900 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5901 return INVALID_OPERATION;
5902 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005903 PatchBuilder patchBuilder;
5904 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5905 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005906
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005907 return connectAudioSourceToSink(
5908 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005909}
5910
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005911status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005912{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005913 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5914 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005915 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005916 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005917 return BAD_VALUE;
5918 }
5919 status_t status = disconnectAudioSource(sourceDesc);
5920
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005921 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005922 return status;
5923}
5924
Andy Hung2ddee192015-12-18 17:34:44 -08005925status_t AudioPolicyManager::setMasterMono(bool mono)
5926{
5927 if (mMasterMono == mono) {
5928 return NO_ERROR;
5929 }
5930 mMasterMono = mono;
5931 // if enabling mono we close all offloaded devices, which will invalidate the
5932 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5933 // for recreating the new AudioTrack as non-offloaded PCM.
5934 //
5935 // If disabling mono, we leave all tracks as is: we don't know which clients
5936 // and tracks are able to be recreated as offloaded. The next "song" should
5937 // play back offloaded.
5938 if (mMasterMono) {
5939 Vector<audio_io_handle_t> offloaded;
5940 for (size_t i = 0; i < mOutputs.size(); ++i) {
5941 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5942 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5943 offloaded.push(desc->mIoHandle);
5944 }
5945 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005946 for (const auto& handle : offloaded) {
5947 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005948 }
5949 }
5950 // update master mono for all remaining outputs
5951 for (size_t i = 0; i < mOutputs.size(); ++i) {
5952 updateMono(mOutputs.keyAt(i));
5953 }
5954 return NO_ERROR;
5955}
5956
5957status_t AudioPolicyManager::getMasterMono(bool *mono)
5958{
5959 *mono = mMasterMono;
5960 return NO_ERROR;
5961}
5962
Eric Laurentac9cef52017-06-09 15:46:26 -07005963float AudioPolicyManager::getStreamVolumeDB(
5964 audio_stream_type_t stream, int index, audio_devices_t device)
5965{
jiabin9a3361e2019-10-01 09:38:30 -07005966 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005967}
5968
jiabin81772902018-04-02 17:52:27 -07005969status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5970 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005971 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005972{
Kriti Dang6537def2021-03-02 13:46:59 +01005973 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5974 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005975 return BAD_VALUE;
5976 }
Kriti Dang6537def2021-03-02 13:46:59 +01005977 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5978 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005979
5980 size_t formatsWritten = 0;
5981 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005982
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005983 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005984 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5985 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005986 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005987 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005988 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005989 bool formatEnabled = true;
5990 switch (forceUse) {
5991 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005992 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005993 break;
5994 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5995 formatEnabled = false;
5996 break;
5997 default: // AUTO or ALWAYS => true
5998 break;
jiabin81772902018-04-02 17:52:27 -07005999 }
6000 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6001 }
jiabin81772902018-04-02 17:52:27 -07006002 }
6003 return NO_ERROR;
6004}
6005
Kriti Dang6537def2021-03-02 13:46:59 +01006006status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6007 audio_format_t *surroundFormats) {
6008 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6009 return BAD_VALUE;
6010 }
6011 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6012 __func__, *numSurroundFormats, surroundFormats);
6013
6014 size_t formatsWritten = 0;
6015 size_t formatsMax = *numSurroundFormats;
6016 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6017
6018 // Return formats from all device profiles that have already been resolved by
6019 // checkOutputsForDevice().
6020 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6021 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6022 audio_devices_t deviceType = device->type();
6023 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6024 // returns formats reported by HDMI devices.
6025 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6026 continue;
6027 }
6028 // Formats reported by sink devices
6029 std::unordered_set<audio_format_t> formatset;
6030 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6031 formatset.insert(it->second.begin(), it->second.end());
6032 }
6033
6034 // Formats hard-coded in the in policy configuration file (if any).
6035 FormatVector encodedFormats = device->encodedFormats();
6036 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6037 // Filter the formats which are supported by the vendor hardware.
6038 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006039 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006040 formats.insert(*it);
6041 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006042 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006043 if (pair.second.count(*it) != 0) {
6044 formats.insert(pair.first);
6045 break;
6046 }
6047 }
6048 }
6049 }
6050 }
6051 *numSurroundFormats = formats.size();
6052 for (const auto& format: formats) {
6053 if (formatsWritten < formatsMax) {
6054 surroundFormats[formatsWritten++] = format;
6055 }
6056 }
6057 return NO_ERROR;
6058}
6059
jiabin81772902018-04-02 17:52:27 -07006060status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6061{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006062 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006063 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6064 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006065 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006066 return BAD_VALUE;
6067 }
6068
Mikhail Naganov100f0122018-11-29 11:22:16 -08006069 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6070 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006071 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006072 return INVALID_OPERATION;
6073 }
6074
Mikhail Naganov100f0122018-11-29 11:22:16 -08006075 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006076 return NO_ERROR;
6077 }
6078
Mikhail Naganov100f0122018-11-29 11:22:16 -08006079 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006080 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006081 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006082 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006083 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006084 }
6085 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006086 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006087 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006088 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006089 }
6090 }
6091
6092 sp<SwAudioOutputDescriptor> outputDesc;
6093 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006094 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6095 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006096 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6097 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006098 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006099 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006100 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6101 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6102 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006103 name.c_str(),
6104 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006105 if (status != NO_ERROR) {
6106 continue;
6107 }
6108 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6109 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6110 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006111 name.c_str(),
6112 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006113 profileUpdated |= (status == NO_ERROR);
6114 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006115 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006116 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006117 AUDIO_DEVICE_IN_HDMI);
6118 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6119 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006120 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006121 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006122 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6123 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6124 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006125 name.c_str(),
6126 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006127 if (status != NO_ERROR) {
6128 continue;
6129 }
6130 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6131 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6132 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006133 name.c_str(),
6134 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006135 profileUpdated |= (status == NO_ERROR);
6136 }
6137
jiabin81772902018-04-02 17:52:27 -07006138 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006139 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006140 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006141 }
6142
6143 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6144}
6145
Eric Laurent5ada82e2019-08-29 17:53:54 -07006146void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006147{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006148 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006149 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006150 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006151 }
6152}
6153
jiabin6012f912018-11-02 17:06:30 -07006154bool AudioPolicyManager::isHapticPlaybackSupported()
6155{
6156 for (const auto& hwModule : mHwModules) {
6157 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6158 for (const auto &outProfile : outputProfiles) {
6159 struct audio_port audioPort;
6160 outProfile->toAudioPort(&audioPort);
6161 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6162 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6163 return true;
6164 }
6165 }
6166 }
6167 }
6168 return false;
6169}
6170
Carter Hsu325a8eb2022-01-19 19:56:51 +08006171bool AudioPolicyManager::isUltrasoundSupported()
6172{
6173 bool hasUltrasoundOutput = false;
6174 bool hasUltrasoundInput = false;
6175 for (const auto& hwModule : mHwModules) {
6176 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6177 if (!hasUltrasoundOutput) {
6178 for (const auto &outProfile : outputProfiles) {
6179 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6180 hasUltrasoundOutput = true;
6181 break;
6182 }
6183 }
6184 }
6185
6186 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6187 if (!hasUltrasoundInput) {
6188 for (const auto &inputProfile : inputProfiles) {
6189 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6190 hasUltrasoundInput = true;
6191 break;
6192 }
6193 }
6194 }
6195
6196 if (hasUltrasoundOutput && hasUltrasoundInput)
6197 return true;
6198 }
6199 return false;
6200}
6201
Atneya Nair698f5ef2022-12-15 16:15:09 -08006202bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6203{
6204 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6205 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6206 for (const auto& hwModule : mHwModules) {
6207 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6208 for (const auto &inputProfile : inputProfiles) {
6209 if ((inputProfile->getFlags() & mask) == mask) {
6210 return true;
6211 }
6212 }
6213 }
6214 return false;
6215}
6216
Eric Laurent8340e672019-11-06 11:01:08 -08006217bool AudioPolicyManager::isCallScreenModeSupported()
6218{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006219 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006220}
6221
6222
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006223status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006224{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006225 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006226 if (!sourceDesc->isConnected()) {
6227 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6228 return NO_ERROR;
6229 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006230 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6231 if (swOutput != 0) {
6232 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006233 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006234 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006235 }
jiabinbce0c1d2020-10-05 11:20:18 -07006236 if (releaseOutput(sourceDesc->portId())) {
6237 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6238 // no need to release audio patch here but just return NO_ERROR.
6239 return NO_ERROR;
6240 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006241 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006242 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006243 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006244 // close Hwoutput and remove from mHwOutputs
6245 } else {
6246 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6247 }
6248 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006249 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006250 sourceDesc->disconnect();
6251 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006252}
6253
François Gaffiec005e562018-11-06 15:04:49 +01006254sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6255 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006256{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006257 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006258 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006259 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006260 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006261 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6262 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006263 source = sourceDesc;
6264 break;
6265 }
6266 }
6267 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006268}
6269
Eric Laurentb4f42a92022-01-17 17:37:31 +01006270bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006271 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006272 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006273{
6274 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6275 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006276 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006277 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006278 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6279 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6280 return false;
6281 }
6282 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6283 return false;
6284 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006285 }
6286
Eric Laurentd332bc82023-08-04 11:45:23 +02006287 // The caller can have the audio config criteria ignored by either passing a null ptr or
6288 // the AUDIO_CONFIG_INITIALIZER value.
6289 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006290 // some positional channel masks and PCM format and for stereo if low latency performance
6291 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006292
6293 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006294 static const bool stereo_spatialization_enabled =
6295 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006296 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006297 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006298 ? audio_channel_mask_contains_stereo(config->channel_mask)
6299 : audio_is_channel_mask_spatialized(config->channel_mask);
6300 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006301 return false;
6302 }
6303 if (!audio_is_linear_pcm(config->format)) {
6304 return false;
6305 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006306 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6307 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6308 return false;
6309 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006310 }
6311
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006312 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006313 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006314 if (profile == nullptr) {
6315 return false;
6316 }
6317
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006318 return true;
6319}
6320
Shunkai Yao4c3af932024-04-26 04:12:21 +00006321// The Spatializer output is compatible with Haptic use cases if:
6322// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6323// with client if client haptic channel bits were set, or
6324// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6325// including the haptic bits or creating the HapticGenerator effect for same session.
6326bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6327 const audio_config_t* config, audio_session_t sessionId) const {
6328 const auto clientHapticChannel =
6329 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6330 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6331 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6332
6333 if (threadOutputHapticChannel) {
6334 // check format and sampleRate match if client haptic channel mask exist
6335 if (clientHapticChannel) {
6336 return mSpatializerOutput->getFormat() == config->format &&
6337 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6338 }
6339 return true;
6340 } else {
6341 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6342 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6343 // HapticGenerator effect for this session) are not supported.
6344 return clientHapticChannel == 0 &&
6345 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6346 }
6347}
6348
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006349void AudioPolicyManager::checkVirtualizerClientRoutes() {
6350 std::set<audio_stream_type_t> streamsToInvalidate;
6351 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006352 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6353 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006354 audio_attributes_t attr = client->attributes();
6355 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6356 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6357 audio_config_base_t clientConfig = client->config();
6358 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006359 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006360 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006361 streamsToInvalidate.insert(client->stream());
6362 }
6363 }
6364 }
6365
jiabinc44b3462022-12-08 12:52:31 -08006366 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006367}
6368
Eric Laurente191d1b2022-04-15 11:59:25 +02006369
6370bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6371 const sp<SwAudioOutputDescriptor>& outputDesc) {
6372 if (outputDesc->isDuplicated()) {
6373 return false;
6374 }
6375 DeviceVector devices = outputDesc->supportedDevices();
6376 for (size_t i = 0; i < mOutputs.size(); i++) {
6377 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6378 if (desc == outputDesc || desc->isDuplicated()) {
6379 continue;
6380 }
6381 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6382 if (!sharedDevices.isEmpty()
6383 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6384 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6385 return false;
6386 }
6387 }
6388 return true;
6389}
6390
6391
Eric Laurentfa0f6742021-08-17 18:39:44 +02006392status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006393 const audio_attributes_t *attr,
6394 audio_io_handle_t *output) {
6395 *output = AUDIO_IO_HANDLE_NONE;
6396
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006397 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6398 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6399 audio_config_t *configPtr = nullptr;
6400 audio_config_t config;
6401 if (mixerConfig != nullptr) {
6402 config = audio_config_initializer(mixerConfig);
6403 configPtr = &config;
6404 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006405 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006406 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006407 return BAD_VALUE;
6408 }
6409
6410 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006411 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006412 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006413 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006414 return BAD_VALUE;
6415 }
6416
Eric Laurente191d1b2022-04-15 11:59:25 +02006417 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006418 for (size_t i = 0; i < mOutputs.size(); i++) {
6419 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006420 if (!desc->isDuplicated()
6421 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6422 spatializerOutputs.push_back(desc);
6423 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006424 }
6425 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006426 mSpatializerOutput.clear();
6427 bool outputsChanged = false;
6428 for (const auto& desc : spatializerOutputs) {
6429 if (desc->mProfile == profile
6430 && (configPtr == nullptr
6431 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6432 mSpatializerOutput = desc;
6433 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6434 } else {
6435 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6436 " and devices %s", __func__, desc->mIoHandle,
6437 configPtr != nullptr ? configPtr->channel_mask : 0,
6438 devices.toString().c_str());
6439 closeOutput(desc->mIoHandle);
6440 outputsChanged = true;
6441 }
Eric Laurent39095982021-08-24 18:29:27 +02006442 }
6443
Eric Laurente191d1b2022-04-15 11:59:25 +02006444 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006445 sp<SwAudioOutputDescriptor> desc =
6446 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006447 if (desc != nullptr) {
6448 mSpatializerOutput = desc;
6449 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006450 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006451 }
6452
6453 checkVirtualizerClientRoutes();
6454
Eric Laurente191d1b2022-04-15 11:59:25 +02006455 if (outputsChanged) {
6456 mPreviousOutputs = mOutputs;
6457 mpClientInterface->onAudioPortListUpdate();
6458 }
6459
6460 if (mSpatializerOutput == nullptr) {
6461 ALOGV("%s could not open spatializer output with requested config", __func__);
6462 return BAD_VALUE;
6463 }
Eric Laurent39095982021-08-24 18:29:27 +02006464 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006465 ALOGV("%s returning new spatializer output %d", __func__, *output);
6466 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006467}
6468
Eric Laurentfa0f6742021-08-17 18:39:44 +02006469status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6470 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006471 return INVALID_OPERATION;
6472 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006473 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006474 return BAD_VALUE;
6475 }
Eric Laurent39095982021-08-24 18:29:27 +02006476
Eric Laurente191d1b2022-04-15 11:59:25 +02006477 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6478 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6479 closeOutput(mSpatializerOutput->mIoHandle);
6480 //from now on mSpatializerOutput is null
6481 checkVirtualizerClientRoutes();
6482 }
Eric Laurent39095982021-08-24 18:29:27 +02006483
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006484 return NO_ERROR;
6485}
6486
Eric Laurente552edb2014-03-10 17:42:56 -07006487// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006488// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006489// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006490uint32_t AudioPolicyManager::nextAudioPortGeneration()
6491{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006492 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006493}
6494
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006495AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006496 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006497 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006498 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006499 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006500 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006501 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006502 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006503 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006504 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006505 mAudioPortGeneration(1),
6506 mBeaconMuteRefCount(0),
6507 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006508 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006509 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006510 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006511 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006512{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006513}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006514
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006515status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006516 if (mEngine == nullptr) {
6517 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006518 }
6519 mEngine->setObserver(this);
6520 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006521 if (status != NO_ERROR) {
6522 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6523 return status;
6524 }
François Gaffie2110e042015-03-24 08:41:51 +01006525
jiabin29230182023-04-04 21:02:36 +00006526 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6527 // at the end of this function.
6528 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006529 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6530 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6531
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006532 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006533 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006534 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006535
Eric Laurent3a4311c2014-03-17 12:00:47 -07006536 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006537 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6538 defaultOutputDevice == nullptr ||
6539 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6540 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6541 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006542 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006543 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006544 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006545
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006546 // Silence ALOGV statements
6547 property_set("log.tag." LOG_TAG, "D");
6548
Eric Laurente552edb2014-03-10 17:42:56 -07006549 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006550 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006551}
6552
Eric Laurente0720872014-03-11 09:30:41 -07006553AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006554{
Eric Laurente552edb2014-03-10 17:42:56 -07006555 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006556 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006557 }
6558 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006559 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006560 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006561 mAvailableOutputDevices.clear();
6562 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006563 mOutputs.clear();
6564 mInputs.clear();
6565 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006566 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006567 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006568}
6569
Eric Laurente0720872014-03-11 09:30:41 -07006570status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006571{
Eric Laurent87ffa392015-05-22 10:32:38 -07006572 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006573}
6574
Eric Laurente552edb2014-03-10 17:42:56 -07006575// ---
6576
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006577void AudioPolicyManager::onNewAudioModulesAvailable()
6578{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006579 DeviceVector newDevices;
6580 onNewAudioModulesAvailableInt(&newDevices);
6581 if (!newDevices.empty()) {
6582 nextAudioPortGeneration();
6583 mpClientInterface->onAudioPortListUpdate();
6584 }
6585}
6586
6587void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6588{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006589 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006590 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6591 continue;
6592 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006593 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006594 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6595 handle != AUDIO_MODULE_HANDLE_NONE) {
6596 hwModule->setHandle(handle);
6597 } else {
6598 ALOGW("could not load HW module %s", hwModule->getName());
6599 continue;
6600 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006601 }
6602 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006603 // open all output streams needed to access attached devices.
6604 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006605 // This also validates mAvailableOutputDevices list
6606 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6607 if (!outProfile->canOpenNewIo()) {
6608 ALOGE("Invalid Output profile max open count %u for profile %s",
6609 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6610 continue;
6611 }
6612 if (!outProfile->hasSupportedDevices()) {
6613 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6614 continue;
6615 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006616 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6617 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006618 mTtsOutputAvailable = true;
6619 }
6620
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006621 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006622 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006623 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006624 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6625 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006626 } else {
6627 // choose first device present in profile's SupportedDevices also part of
6628 // mAvailableOutputDevices.
6629 if (availProfileDevices.isEmpty()) {
6630 continue;
6631 }
6632 supportedDevice = availProfileDevices.itemAt(0);
6633 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006634 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006635 continue;
6636 }
6637 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6638 mpClientInterface);
6639 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006640 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6641 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006642 AUDIO_STREAM_DEFAULT,
6643 AUDIO_OUTPUT_FLAG_NONE, &output);
6644 if (status != NO_ERROR) {
6645 ALOGW("Cannot open output stream for devices %s on hw module %s",
6646 supportedDevice->toString().c_str(), hwModule->getName());
6647 continue;
6648 }
6649 for (const auto &device : availProfileDevices) {
6650 // give a valid ID to an attached device once confirmed it is reachable
6651 if (!device->isAttached()) {
6652 device->attach(hwModule);
6653 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006654 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006655 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006656 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6657 }
6658 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006659 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006660 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6661 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006662 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006663 }
Eric Laurent39095982021-08-24 18:29:27 +02006664 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006665 outputDesc->close();
6666 } else {
6667 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306668 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006669 DeviceVector(supportedDevice),
6670 true,
6671 0,
6672 NULL);
6673 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006674 }
6675 // open input streams needed to access attached devices to validate
6676 // mAvailableInputDevices list
6677 for (const auto& inProfile : hwModule->getInputProfiles()) {
6678 if (!inProfile->canOpenNewIo()) {
6679 ALOGE("Invalid Input profile max open count %u for profile %s",
6680 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6681 continue;
6682 }
6683 if (!inProfile->hasSupportedDevices()) {
6684 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6685 continue;
6686 }
6687 // chose first device present in profile's SupportedDevices also part of
6688 // available input devices
6689 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006690 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006691 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006692 ALOGV("%s: Input device list is empty! for profile %s",
6693 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006694 continue;
6695 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00006696 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6697 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006698
6699 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6700 status_t status = inputDesc->open(nullptr,
6701 availProfileDevices.itemAt(0),
6702 AUDIO_SOURCE_MIC,
6703 AUDIO_INPUT_FLAG_NONE,
6704 &input);
6705 if (status != NO_ERROR) {
6706 ALOGW("Cannot open input stream for device %s on hw module %s",
6707 availProfileDevices.toString().c_str(),
6708 hwModule->getName());
6709 continue;
6710 }
6711 for (const auto &device : availProfileDevices) {
6712 // give a valid ID to an attached device once confirmed it is reachable
6713 if (!device->isAttached()) {
6714 device->attach(hwModule);
6715 device->importAudioPortAndPickAudioProfile(inProfile, true);
6716 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006717 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006718 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6719 }
6720 }
6721 inputDesc->close();
6722 }
6723 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006724
6725 // Check if spatializer outputs can be closed until used.
6726 // mOutputs vector never contains duplicated outputs at this point.
6727 std::vector<audio_io_handle_t> outputsClosed;
6728 for (size_t i = 0; i < mOutputs.size(); i++) {
6729 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6730 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6731 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6732 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006733 nextAudioPortGeneration();
6734 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6735 if (index >= 0) {
6736 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6737 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6738 patchDesc->getAfHandle(), 0);
6739 mAudioPatches.removeItemsAt(index);
6740 mpClientInterface->onAudioPatchListUpdate();
6741 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006742 desc->close();
6743 }
6744 }
6745 for (auto output : outputsClosed) {
6746 removeOutput(output);
6747 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006748}
6749
Eric Laurent98e38192018-02-15 18:31:53 -08006750void AudioPolicyManager::addOutput(audio_io_handle_t output,
6751 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006752{
Eric Laurent1c333e22014-05-20 10:48:17 -07006753 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006754 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006755 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006756 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006757 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006758}
6759
François Gaffie53615e22015-03-19 09:24:12 +01006760void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6761{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006762 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6763 ALOGV("%s: removing primary output", __func__);
6764 mPrimaryOutput = nullptr;
6765 }
François Gaffie53615e22015-03-19 09:24:12 +01006766 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006767 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006768}
6769
Eric Laurent98e38192018-02-15 18:31:53 -08006770void AudioPolicyManager::addInput(audio_io_handle_t input,
6771 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006772{
Eric Laurent1c333e22014-05-20 10:48:17 -07006773 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006774 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006775}
Eric Laurente552edb2014-03-10 17:42:56 -07006776
François Gaffie11d30102018-11-02 16:09:09 +01006777status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006778 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006779 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006780{
François Gaffie11d30102018-11-02 16:09:09 +01006781 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006782 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006783 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006784
François Gaffie11d30102018-11-02 16:09:09 +01006785 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006786 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006787 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006788 }
Eric Laurente552edb2014-03-10 17:42:56 -07006789
Eric Laurent3b73df72014-03-11 09:06:29 -07006790 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006791 // first call getAudioPort to get the supported attributes from the HAL
6792 struct audio_port_v7 port = {};
6793 device->toAudioPort(&port);
6794 status_t status = mpClientInterface->getAudioPort(&port);
6795 if (status == NO_ERROR) {
6796 device->importAudioPort(port);
6797 }
6798
6799 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006800 for (size_t i = 0; i < mOutputs.size(); i++) {
6801 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006802 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006803 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006804 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6805 mOutputs.keyAt(i), device->toString().c_str());
6806 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006807 }
6808 }
6809 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006810 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006811 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006812 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6813 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006814 if (profile->supportsDevice(device)) {
6815 profiles.add(profile);
6816 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6817 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006818 }
6819 }
6820 }
6821
Eric Laurent7b279bb2015-12-14 10:18:23 -08006822 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006823
Eric Laurente552edb2014-03-10 17:42:56 -07006824 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006825 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006826 return BAD_VALUE;
6827 }
6828
6829 // open outputs for matching profiles if needed. Direct outputs are also opened to
6830 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6831 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006832 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006833
6834 // nothing to do if one output is already opened for this profile
6835 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006836 for (j = 0; j < outputs.size(); j++) {
6837 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006838 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006839 // matching profile: save the sample rates, format and channel masks supported
6840 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006841 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006842 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006843 }
Eric Laurente552edb2014-03-10 17:42:56 -07006844 break;
6845 }
6846 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006847 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006848 continue;
6849 }
6850
Eric Laurent3974e3b2017-12-07 17:58:43 -08006851 if (!profile->canOpenNewIo()) {
6852 ALOGW("Max Output number %u already opened for this profile %s",
6853 profile->maxOpenCount, profile->getTagName().c_str());
6854 continue;
6855 }
6856
Eric Laurent83efe1c2017-07-09 16:51:08 -07006857 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006858 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006859 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6860 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006861 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006862 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006863 profiles.removeAt(profile_index);
6864 profile_index--;
6865 } else {
6866 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006867 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006868 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006869 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6870 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006871 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006872 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006873
François Gaffie11d30102018-11-02 16:09:09 +01006874 if (device_distinguishes_on_address(deviceType)) {
6875 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6876 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306877 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6878 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006879 }
Eric Laurente552edb2014-03-10 17:42:56 -07006880 ALOGV("checkOutputsForDevice(): adding output %d", output);
6881 }
6882 }
6883
6884 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006885 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006886 return BAD_VALUE;
6887 }
Eric Laurentd4692962014-05-05 18:13:44 -07006888 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006889 // check if one opened output is not needed any more after disconnecting one device
6890 for (size_t i = 0; i < mOutputs.size(); i++) {
6891 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006892 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006893 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006894 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006895 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006896 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006897 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006898 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6899 mOutputs.keyAt(i));
6900 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006901 }
Eric Laurente552edb2014-03-10 17:42:56 -07006902 }
6903 }
Eric Laurentd4692962014-05-05 18:13:44 -07006904 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006905 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006906 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6907 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006908 if (!profile->supportsDevice(device)) {
6909 continue;
6910 }
6911 ALOGV("checkOutputsForDevice(): "
6912 "clearing direct output profile %zu on module %s",
6913 j, hwModule->getName());
6914 profile->clearAudioProfiles();
6915 if (!profile->hasDynamicAudioProfile()) {
6916 continue;
6917 }
6918 // When a device is disconnected, if there is an IOProfile that contains dynamic
6919 // profiles and supports the disconnected device, call getAudioPort to repopulate
6920 // the capabilities of the devices that is supported by the IOProfile.
6921 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6922 if (supportedDevice == device ||
6923 !mAvailableOutputDevices.contains(supportedDevice)) {
6924 continue;
6925 }
6926 struct audio_port_v7 port;
6927 supportedDevice->toAudioPort(&port);
6928 status_t status = mpClientInterface->getAudioPort(&port);
6929 if (status == NO_ERROR) {
6930 supportedDevice->importAudioPort(port);
6931 }
Eric Laurente552edb2014-03-10 17:42:56 -07006932 }
6933 }
6934 }
6935 }
6936 return NO_ERROR;
6937}
6938
François Gaffie11d30102018-11-02 16:09:09 +01006939status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006940 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006941{
François Gaffie11d30102018-11-02 16:09:09 +01006942 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006943 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006944 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006945 }
6946
Eric Laurentd4692962014-05-05 18:13:44 -07006947 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07006948 sp<AudioInputDescriptor> desc;
6949
jiabinbf5f4262023-04-12 21:48:34 +00006950 // first call getAudioPort to get the supported attributes from the HAL
6951 struct audio_port_v7 port = {};
6952 device->toAudioPort(&port);
6953 status_t status = mpClientInterface->getAudioPort(&port);
6954 if (status == NO_ERROR) {
6955 device->importAudioPort(port);
6956 }
6957
Eric Laurent0dd51852019-04-19 18:18:58 -07006958 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006959 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006960 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006961 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006962 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006963 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006964 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006965
François Gaffie11d30102018-11-02 16:09:09 +01006966 if (profile->supportsDevice(device)) {
6967 profiles.add(profile);
6968 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6969 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006970 }
6971 }
6972 }
6973
Eric Laurent0dd51852019-04-19 18:18:58 -07006974 if (profiles.isEmpty()) {
6975 ALOGW("%s: No input profile available for device %s",
6976 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006977 return BAD_VALUE;
6978 }
6979
6980 // open inputs for matching profiles if needed. Direct inputs are also opened to
6981 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6982 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6983
Eric Laurent1c333e22014-05-20 10:48:17 -07006984 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006985
Eric Laurentd4692962014-05-05 18:13:44 -07006986 // nothing to do if one input is already opened for this profile
6987 size_t input_index;
6988 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6989 desc = mInputs.valueAt(input_index);
6990 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006991 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006992 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006993 }
Eric Laurentd4692962014-05-05 18:13:44 -07006994 break;
6995 }
6996 }
6997 if (input_index != mInputs.size()) {
6998 continue;
6999 }
7000
Eric Laurent3974e3b2017-12-07 17:58:43 -08007001 if (!profile->canOpenNewIo()) {
7002 ALOGW("Max Input number %u already opened for this profile %s",
7003 profile->maxOpenCount, profile->getTagName().c_str());
7004 continue;
7005 }
7006
Eric Laurentc71b11b2024-06-03 12:54:53 +00007007 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007008 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00007009 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007010
Eric Laurentcf2c0212014-07-25 16:20:43 -07007011 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007012 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007013 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007014 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007015 mpClientInterface->setParameters(input, String8(param));
7016 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007017 }
jiabin12537fc2023-10-12 17:56:08 +00007018 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007019 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007020 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08007021 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007022 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007023 }
7024
Eric Laurent0dd51852019-04-19 18:18:58 -07007025 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007026 addInput(input, desc);
7027 }
7028 } // endif input != 0
7029
Eric Laurentcf2c0212014-07-25 16:20:43 -07007030 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08007031 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01007032 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007033 profiles.removeAt(profile_index);
7034 profile_index--;
7035 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007036 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007037 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007038 }
Eric Laurentd4692962014-05-05 18:13:44 -07007039 ALOGV("checkInputsForDevice(): adding input %d", input);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007040
7041 if (checkCloseInput(desc)) {
7042 ALOGV("%s closing input %d", __func__, input);
7043 closeInput(input);
7044 }
Eric Laurentd4692962014-05-05 18:13:44 -07007045 }
7046 } // end scan profiles
7047
7048 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007049 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007050 return BAD_VALUE;
7051 }
7052 } else {
7053 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007054 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007055 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007056 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007057 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007058 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007059 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007060 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08007061 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
7062 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007063 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007064 }
7065 }
7066 }
7067 } // end disconnect
7068
7069 return NO_ERROR;
7070}
7071
7072
Eric Laurente0720872014-03-11 09:30:41 -07007073void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007074{
7075 ALOGV("closeOutput(%d)", output);
7076
François Gaffie1c878552018-11-22 16:53:21 +01007077 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7078 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007079 ALOGW("closeOutput() unknown output %d", output);
7080 return;
7081 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007082 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007083 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007084
Eric Laurente552edb2014-03-10 17:42:56 -07007085 // look for duplicated outputs connected to the output being removed.
7086 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007087 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7088 if (dupOutput->isDuplicated() &&
7089 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7090 sp<SwAudioOutputDescriptor> remainingOutput =
7091 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007092 // As all active tracks on duplicated output will be deleted,
7093 // and as they were also referenced on the other output, the reference
7094 // count for their stream type must be adjusted accordingly on
7095 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007096 const bool wasActive = remainingOutput->isActive();
7097 // Note: no-op on the closing output where all clients has already been set inactive
7098 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007099 // stop() will be a no op if the output is still active but is needed in case all
7100 // active streams refcounts where cleared above
7101 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007102 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007103 }
Eric Laurente552edb2014-03-10 17:42:56 -07007104 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7105 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7106
7107 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007108 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007109 }
7110 }
7111
Eric Laurent05b90f82014-08-27 15:32:29 -07007112 nextAudioPortGeneration();
7113
François Gaffie1c878552018-11-22 16:53:21 +01007114 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007115 if (index >= 0) {
7116 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007117 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7118 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007119 mAudioPatches.removeItemsAt(index);
7120 mpClientInterface->onAudioPatchListUpdate();
7121 }
7122
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007123 if (closingOutputWasActive) {
7124 closingOutput->stop();
7125 }
François Gaffie1c878552018-11-22 16:53:21 +01007126 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007127 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007128 for (const auto device : closingOutput->devices()) {
7129 device->setPreferredConfig(nullptr);
7130 }
7131 }
Eric Laurente552edb2014-03-10 17:42:56 -07007132
François Gaffie53615e22015-03-19 09:24:12 +01007133 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007134 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007135 if (closingOutput == mSpatializerOutput) {
7136 mSpatializerOutput.clear();
7137 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007138
7139 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7140 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007141 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007142 bool directOutputOpen = false;
7143 for (size_t i = 0; i < mOutputs.size(); i++) {
7144 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7145 directOutputOpen = true;
7146 break;
7147 }
7148 }
7149 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007150 ALOGV("no direct outputs open, reset MSD patches");
7151 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7152 // how output devices for patching are resolved. Avoid by caching and reusing the
7153 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7154 // devices to patch to. This may be complicated by the fact that devices may become
7155 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007156 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007157 }
7158 }
jiabin220eea12024-05-17 17:55:20 +00007159
7160 if (closingOutput->mPreferredAttrInfo != nullptr) {
7161 closingOutput->mPreferredAttrInfo->resetActiveClient();
7162 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007163}
7164
7165void AudioPolicyManager::closeInput(audio_io_handle_t input)
7166{
7167 ALOGV("closeInput(%d)", input);
7168
7169 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7170 if (inputDesc == NULL) {
7171 ALOGW("closeInput() unknown input %d", input);
7172 return;
7173 }
7174
Eric Laurent6a94d692014-05-20 11:18:06 -07007175 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007176
François Gaffie11d30102018-11-02 16:09:09 +01007177 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007178 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007179 if (index >= 0) {
7180 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007181 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7182 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007183 mAudioPatches.removeItemsAt(index);
7184 mpClientInterface->onAudioPatchListUpdate();
7185 }
7186
François Gaffie6ebbce02023-07-19 13:27:53 +02007187 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007188 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007189 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007190
François Gaffie11d30102018-11-02 16:09:09 +01007191 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7192 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007193 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007194 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007195 }
Eric Laurente552edb2014-03-10 17:42:56 -07007196}
7197
François Gaffie11d30102018-11-02 16:09:09 +01007198SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7199 const DeviceVector &devices,
7200 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007201{
7202 SortedVector<audio_io_handle_t> outputs;
7203
François Gaffie11d30102018-11-02 16:09:09 +01007204 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007205 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007206 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007207 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007208 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007209 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007210 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007211 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007212 outputs.add(openOutputs.keyAt(i));
7213 }
7214 }
7215 return outputs;
7216}
7217
Mikhail Naganov37977152018-07-11 15:54:44 -07007218void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7219{
7220 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7221 // output is suspended before any tracks are moved to it
7222 checkA2dpSuspend();
7223 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007224 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007225 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007226 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007227 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007228 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7229 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7230 // configuration changes will ultimately be rerouted correctly. We can still avoid
7231 // unnecessary rerouting by caching and reusing the arguments to
7232 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7233 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007234 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007235 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007236 // an event that changed routing likely occurred, inform upper layers
7237 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007238}
7239
François Gaffiec005e562018-11-06 15:04:49 +01007240bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7241 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007242{
François Gaffiec005e562018-11-06 15:04:49 +01007243 return mEngine->getProductStrategyForAttributes(lAttr) ==
7244 mEngine->getProductStrategyForAttributes(rAttr);
7245}
7246
Francois Gaffieff1eb522020-05-06 18:37:04 +02007247void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7248{
7249 for (size_t i = 0; i < mAudioSources.size(); i++) {
7250 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7251 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007252 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007253 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007254 connectAudioSource(sourceDesc);
7255 }
7256 }
7257}
7258
7259void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7260{
7261 for (size_t i = 0; i < mAudioSources.size(); i++) {
7262 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7263 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7264 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7265 disconnectAudioSource(sourceDesc);
7266 }
7267 }
7268}
7269
François Gaffiec005e562018-11-06 15:04:49 +01007270void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7271{
7272 auto psId = mEngine->getProductStrategyForAttributes(attr);
7273
7274 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7275 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007276
François Gaffie11d30102018-11-02 16:09:09 +01007277 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7278 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007279
Eric Laurentc209fe42020-06-05 18:11:23 -07007280 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007281 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007282 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007283 // take into account dynamic audio policies related changes: if a client is now associated
7284 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007285 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007286 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7287 if (desc->isDuplicated()) {
7288 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007289 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007290 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7291 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7292 continue;
7293 }
7294 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007295 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007296 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7297 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7298 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007299 if (status != OK) {
7300 continue;
7301 }
yucliuf4de36d2020-09-14 14:57:56 -07007302 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007303 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007304 maxLatency = desc->latency();
7305 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007306 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007307 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007308 }
7309 }
7310
Eric Laurent56ed8842022-11-15 16:04:41 +01007311 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007312 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7313 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007314 for (audio_io_handle_t srcOut : srcOutputs) {
7315 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007316 if (desc == nullptr) continue;
7317
7318 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007319 maxLatency = desc->latency();
7320 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007321
Eric Laurent56ed8842022-11-15 16:04:41 +01007322 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007323 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007324 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007325 // a client on a non direct outputs has necessarily a linear PCM format
7326 // so we can call selectOutput() safely
7327 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7328 client->flags(),
7329 client->config().format,
7330 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007331 client->config().sample_rate,
7332 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007333 if (newOutput != srcOut) {
7334 invalidate = true;
7335 break;
7336 }
7337 } else {
7338 sp<IOProfile> profile = getProfileForOutput(newDevices,
7339 client->config().sample_rate,
7340 client->config().format,
7341 client->config().channel_mask,
7342 client->flags(),
7343 true /* directOnly */);
7344 if (profile != desc->mProfile) {
7345 invalidate = true;
7346 break;
7347 }
7348 }
7349 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007350 // mute strategy while moving tracks from one output to another
7351 if (invalidate) {
7352 invalidatedOutputs.push_back(desc);
7353 if (desc->isStrategyActive(psId)) {
7354 setStrategyMute(psId, true, desc);
7355 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7356 newDevices.types());
7357 }
Eric Laurente552edb2014-03-10 17:42:56 -07007358 }
François Gaffiec005e562018-11-06 15:04:49 +01007359 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007360 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007361 connectAudioSource(source);
7362 }
Eric Laurente552edb2014-03-10 17:42:56 -07007363 }
7364
Eric Laurent56ed8842022-11-15 16:04:41 +01007365 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7366 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7367 std::to_string(srcOutputs[0]).c_str(),
7368 std::to_string(dstOutputs[0]).c_str());
7369
François Gaffiec005e562018-11-06 15:04:49 +01007370 // Move effects associated to this stream from previous output to new output
7371 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007372 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007373 }
François Gaffiec005e562018-11-06 15:04:49 +01007374 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007375 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007376 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007377 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007378 desc->setTracksInvalidatedStatusByStrategy(psId);
7379 }
Eric Laurente552edb2014-03-10 17:42:56 -07007380 }
7381 }
7382}
7383
Eric Laurente0720872014-03-11 09:30:41 -07007384void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007385{
François Gaffiec005e562018-11-06 15:04:49 +01007386 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7387 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7388 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007389 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007390 }
Eric Laurente552edb2014-03-10 17:42:56 -07007391}
7392
Kevin Rocard153f92d2018-12-18 18:33:28 -08007393void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007394 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007395 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007396 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007397 for (size_t i = 0; i < mOutputs.size(); i++) {
7398 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7399 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007400 sp<AudioPolicyMix> primaryMix;
7401 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007402 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007403 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7404 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7405 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007406 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7407 for (auto &secondaryMix : secondaryMixes) {
7408 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7409 if (outputDesc != nullptr &&
7410 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7411 secondaryDescs.push_back(outputDesc);
7412 }
7413 }
7414
jiabinc44b3462022-12-08 12:52:31 -08007415 if (status != OK &&
7416 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7417 // When it failed to query secondary output, only invalidate the client that is not
7418 // MMAP. The reason is that MMAP stream will not support secondary output.
7419 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007420 } else if (!std::equal(
7421 client->getSecondaryOutputs().begin(),
7422 client->getSecondaryOutputs().end(),
7423 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007424 if (!audio_is_linear_pcm(client->config().format)) {
7425 // If the format is not PCM, the tracks should be invalidated to get correct
7426 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007427 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007428 } else {
7429 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7430 std::vector<audio_io_handle_t> secondaryOutputIds;
7431 for (const auto &secondaryDesc: secondaryDescs) {
7432 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7433 weakSecondaryDescs.push_back(secondaryDesc);
7434 }
7435 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7436 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007437 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007438 }
7439 }
7440 }
jiabin10a03f12021-05-07 23:46:28 +00007441 if (!trackSecondaryOutputs.empty()) {
7442 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7443 }
jiabinc44b3462022-12-08 12:52:31 -08007444 if (!clientsToInvalidate.empty()) {
7445 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7446 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007447 }
7448}
7449
Eric Laurent2517af32020-11-25 15:31:27 +01007450bool AudioPolicyManager::isScoRequestedForComm() const {
7451 AudioDeviceTypeAddrVector devices;
7452 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7453 for (const auto &device : devices) {
7454 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7455 return true;
7456 }
7457 }
7458 return false;
7459}
7460
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007461bool AudioPolicyManager::isHearingAidUsedForComm() const {
7462 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7463 true /*fromCache*/);
7464 for (const auto &device : devices) {
7465 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7466 return true;
7467 }
7468 }
7469 return false;
7470}
7471
7472
Eric Laurente0720872014-03-11 09:30:41 -07007473void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007474{
François Gaffie53615e22015-03-19 09:24:12 +01007475 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007476 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007477 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007478 return;
7479 }
7480
Eric Laurent3a4311c2014-03-17 12:00:47 -07007481 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007482 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7483 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007484 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007485
7486 // if suspended, restore A2DP output if:
7487 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007488 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007489 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007490 //
Eric Laurentf732e072016-08-03 19:30:28 -07007491 // if not suspended, suspend A2DP output if:
7492 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007493 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007494 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007495 //
7496 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007497 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007498 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007499 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007500 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007501
7502 mpClientInterface->restoreOutput(a2dpOutput);
7503 mA2dpSuspended = false;
7504 }
7505 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007506 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007507 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007508 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007509 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007510
7511 mpClientInterface->suspendOutput(a2dpOutput);
7512 mA2dpSuspended = true;
7513 }
7514 }
7515}
7516
François Gaffie11d30102018-11-02 16:09:09 +01007517DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7518 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007519{
François Gaffiedb1755b2023-09-01 11:50:35 +02007520 if (outputDesc == nullptr) {
7521 return DeviceVector{};
7522 }
François Gaffie11d30102018-11-02 16:09:09 +01007523
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007524 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007525 if (index >= 0) {
7526 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007527 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007528 ALOGV("%s device %s forced by patch %d", __func__,
7529 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7530 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007531 }
7532 }
7533
Dean Wheatley514b4312020-06-17 21:45:00 +10007534 // Do not retrieve engine device for outputs through MSD
7535 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7536 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7537 return outputDesc->devices();
7538 }
7539
Eric Laurent97ac8712018-07-27 18:59:02 -07007540 // Honor explicit routing requests only if no client using default routing is active on this
7541 // input: a specific app can not force routing for other apps by setting a preferred device.
7542 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007543 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007544 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007545 if (device != nullptr) {
7546 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007547 }
7548
François Gaffiea807ef92018-11-05 10:44:33 +01007549 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7550 // of setForceUse / Default Bus device here
7551 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7552 if (device != nullptr) {
7553 return DeviceVector(device);
7554 }
7555
François Gaffiedb1755b2023-09-01 11:50:35 +02007556 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007557 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7558 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307559 auto hasStreamActive = [&](auto stream) {
7560 return hasStream(streams, stream) && isStreamActive(stream, 0);
7561 };
Eric Laurent484e9272018-06-07 17:29:23 -07007562
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307563 auto doGetOutputDevicesForVoice = [&]() {
7564 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007565 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307566 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007567 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7568 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307569 };
7570
7571 // With low-latency playing on speaker, music on WFD, when the first low-latency
7572 // output is stopped, getNewOutputDevices checks for a product strategy
7573 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007574 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307575 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7576 // stream is associated to the output descriptor.
7577 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7578 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7579 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7580 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007581 // Retrieval of devices for voice DL is done on primary output profile, cannot
7582 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007583 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007584 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7585 break;
7586 }
Eric Laurente552edb2014-03-10 17:42:56 -07007587 }
François Gaffiec005e562018-11-06 15:04:49 +01007588 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007589 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007590}
7591
François Gaffie11d30102018-11-02 16:09:09 +01007592sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7593 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007594{
François Gaffie11d30102018-11-02 16:09:09 +01007595 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007596
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007597 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007598 if (index >= 0) {
7599 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007600 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007601 ALOGV("getNewInputDevice() device %s forced by patch %d",
7602 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7603 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007604 }
7605 }
7606
Eric Laurent97ac8712018-07-27 18:59:02 -07007607 // Honor explicit routing requests only if no client using default routing is active on this
7608 // input: a specific app can not force routing for other apps by setting a preferred device.
7609 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007610 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7611 if (device != nullptr) {
7612 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007613 }
7614
Eric Laurentdc95a252018-04-12 12:46:56 -07007615 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007616 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007617 audio_attributes_t attributes;
7618 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007619 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007620 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7621 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007622 attributes = topClient->attributes();
7623 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007624 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007625 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007626 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7627 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007628 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007629 }
7630
Francois Gaffie716e1432019-01-14 16:58:59 +01007631 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7632 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007633 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007634 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007635 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007636 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007637
Eric Laurente552edb2014-03-10 17:42:56 -07007638 return device;
7639}
7640
Eric Laurent794fde22016-03-11 09:50:45 -08007641bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7642 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007643 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007644}
7645
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007646status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007647 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007648 if (devices == nullptr) {
7649 return BAD_VALUE;
7650 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007651
Andy Hung6d23c0f2022-02-16 09:37:15 -08007652 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007653 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7654 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007655 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007656 for (const auto& device : curDevices) {
7657 devices->push_back(device->getDeviceTypeAddr());
7658 }
7659 return NO_ERROR;
7660}
7661
Eric Laurente0720872014-03-11 09:30:41 -07007662void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007663 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007664 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007665 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007666 updateDevicesAndOutputs();
7667 break;
7668 default:
7669 break;
7670 }
7671}
7672
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007673uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007674
7675 // skip beacon mute management if a dedicated TTS output is available
7676 if (mTtsOutputAvailable) {
7677 return 0;
7678 }
7679
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007680 switch(event) {
7681 case STARTING_OUTPUT:
7682 mBeaconMuteRefCount++;
7683 break;
7684 case STOPPING_OUTPUT:
7685 if (mBeaconMuteRefCount > 0) {
7686 mBeaconMuteRefCount--;
7687 }
7688 break;
7689 case STARTING_BEACON:
7690 mBeaconPlayingRefCount++;
7691 break;
7692 case STOPPING_BEACON:
7693 if (mBeaconPlayingRefCount > 0) {
7694 mBeaconPlayingRefCount--;
7695 }
7696 break;
7697 }
7698
7699 if (mBeaconMuteRefCount > 0) {
7700 // any playback causes beacon to be muted
7701 return setBeaconMute(true);
7702 } else {
7703 // no other playback: unmute when beacon starts playing, mute when it stops
7704 return setBeaconMute(mBeaconPlayingRefCount == 0);
7705 }
7706}
7707
7708uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7709 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7710 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7711 // keep track of muted state to avoid repeating mute/unmute operations
7712 if (mBeaconMuted != mute) {
7713 // mute/unmute AUDIO_STREAM_TTS on all outputs
7714 ALOGV("\t muting %d", mute);
7715 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007716 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7717 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7718 ALOGV("\t no tts volume source available");
7719 return 0;
7720 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007721 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007722 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007723 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007724 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007725 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007726 maxLatency = latency;
7727 }
7728 }
7729 mBeaconMuted = mute;
7730 return maxLatency;
7731 }
7732 return 0;
7733}
7734
Eric Laurente0720872014-03-11 09:30:41 -07007735void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007736{
François Gaffiec005e562018-11-06 15:04:49 +01007737 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007738 mPreviousOutputs = mOutputs;
7739}
7740
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007741uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007742 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007743 uint32_t delayMs)
7744{
7745 // mute/unmute strategies using an incompatible device combination
7746 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7747 // if unmuting, unmute only after the specified delay
7748 if (outputDesc->isDuplicated()) {
7749 return 0;
7750 }
7751
7752 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007753 DeviceVector devices = outputDesc->devices();
7754 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007755
François Gaffiec005e562018-11-06 15:04:49 +01007756 auto productStrategies = mEngine->getOrderedProductStrategies();
7757 for (const auto &productStrategy : productStrategies) {
7758 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7759 DeviceVector curDevices =
7760 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7761 curDevices = curDevices.filter(outputDesc->supportedDevices());
7762 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007763 bool doMute = false;
7764
François Gaffiec005e562018-11-06 15:04:49 +01007765 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007766 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007767 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7768 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007769 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007770 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007771 }
Eric Laurent99401132014-05-07 19:48:15 -07007772 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007773 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007774 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007775 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007776 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007777 continue;
7778 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307779 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007780 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7781 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7782 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007783 if (mute) {
7784 // FIXME: should not need to double latency if volume could be applied
7785 // immediately by the audioflinger mixer. We must account for the delay
7786 // between now and the next time the audioflinger thread for this output
7787 // will process a buffer (which corresponds to one buffer size,
7788 // usually 1/2 or 1/4 of the latency).
7789 if (muteWaitMs < desc->latency() * 2) {
7790 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007791 }
7792 }
7793 }
7794 }
7795 }
7796 }
7797
Eric Laurent99401132014-05-07 19:48:15 -07007798 // temporary mute output if device selection changes to avoid volume bursts due to
7799 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007800 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007801 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007802
Eric Laurentdc462862016-07-19 12:29:53 -07007803 if (muteWaitMs < tempMuteWaitMs) {
7804 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007805 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007806
7807 // If recommended duration is defined, replace temporary mute duration to avoid
7808 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7809 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7810 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7811 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7812 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7813
François Gaffieaaac0fd2018-11-22 17:56:39 +01007814 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7815 // make sure that we do not start the temporary mute period too early in case of
7816 // delayed device change
7817 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7818 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007819 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007820 }
7821 }
7822
Eric Laurente552edb2014-03-10 17:42:56 -07007823 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7824 if (muteWaitMs > delayMs) {
7825 muteWaitMs -= delayMs;
7826 usleep(muteWaitMs * 1000);
7827 return muteWaitMs;
7828 }
7829 return 0;
7830}
7831
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307832uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7833 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007834 const DeviceVector &devices,
7835 bool force,
7836 int delayMs,
7837 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007838 bool requiresMuteCheck, bool requiresVolumeCheck,
7839 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007840{
jiabin3ff8d7d2022-12-13 06:27:44 +00007841 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307842 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7843 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7844 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007845 uint32_t muteWaitMs;
7846
7847 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307848 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007849 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307850 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007851 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007852 return muteWaitMs;
7853 }
Eric Laurente552edb2014-03-10 17:42:56 -07007854
7855 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007856 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007857 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007858 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007859
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307860 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7861 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007862
7863 if (!filteredDevices.isEmpty()) {
7864 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007865 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007866
7867 // if the outputs are not materially active, there is no need to mute.
7868 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007869 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007870 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307871 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7872 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007873 muteWaitMs = 0;
7874 }
Eric Laurente552edb2014-03-10 17:42:56 -07007875
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007876 bool outputRouted = outputDesc->isRouted();
7877
Eric Laurent79ea9582020-06-11 18:49:24 -07007878 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7879 // output profile or if new device is not supported AND previous device(s) is(are) still
7880 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007881 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307882 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7883 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007884 // restore previous device after evaluating strategy mute state
7885 outputDesc->setDevices(prevDevices);
7886 return muteWaitMs;
7887 }
7888
Eric Laurente552edb2014-03-10 17:42:56 -07007889 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007890 // the requested device is AUDIO_DEVICE_NONE
7891 // OR the requested device is the same as current device
7892 // AND force is not specified
7893 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007894 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007895 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307896 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7897 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7898 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007899 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307900 ALOGV("%s %s setting same device on routed output, force apply volumes",
7901 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007902 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7903 }
Eric Laurente552edb2014-03-10 17:42:56 -07007904 return muteWaitMs;
7905 }
7906
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307907 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7908 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007909
Eric Laurente552edb2014-03-10 17:42:56 -07007910 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007911 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007912 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007913 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007914 PatchBuilder patchBuilder;
7915 patchBuilder.addSource(outputDesc);
7916 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7917 for (const auto &filteredDevice : filteredDevices) {
7918 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007919 }
7920
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007921 // Add half reported latency to delayMs when muteWaitMs is null in order
7922 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007923 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7924 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7925 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007926 }
Eric Laurente552edb2014-03-10 17:42:56 -07007927
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007928 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7929 if (!skipMuteDelay) {
7930 // update stream volumes according to new device
7931 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7932 }
Eric Laurente552edb2014-03-10 17:42:56 -07007933
7934 return muteWaitMs;
7935}
7936
Eric Laurentc75307b2015-03-17 15:29:32 -07007937status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007938 int delayMs,
7939 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007940{
Eric Laurent6a94d692014-05-20 11:18:06 -07007941 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007942 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7943 return INVALID_OPERATION;
7944 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007945 if (patchHandle) {
7946 index = mAudioPatches.indexOfKey(*patchHandle);
7947 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007948 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007949 }
7950 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007951 return INVALID_OPERATION;
7952 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007953 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007954 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007955 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007956 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007957 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007958 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007959 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007960 return status;
7961}
7962
7963status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007964 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007965 bool force,
7966 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007967{
7968 status_t status = NO_ERROR;
7969
Eric Laurent1f2f2232014-06-02 12:01:23 -07007970 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007971 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7972 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007973
François Gaffie11d30102018-11-02 16:09:09 +01007974 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007975 PatchBuilder patchBuilder;
7976 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007977 // AUDIO_SOURCE_HOTWORD is for internal use only:
7978 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007979 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7980 auto result = usecase;
7981 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7982 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7983 }
7984 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007985 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007986 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007987 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007988 }
7989 }
7990 return status;
7991}
7992
Eric Laurent6a94d692014-05-20 11:18:06 -07007993status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7994 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007995{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007996 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007997 ssize_t index;
7998 if (patchHandle) {
7999 index = mAudioPatches.indexOfKey(*patchHandle);
8000 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008001 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008002 }
8003 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008004 return INVALID_OPERATION;
8005 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008006 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008007 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008008 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008009 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008010 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008011 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008012 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008013 return status;
8014}
8015
François Gaffie11d30102018-11-02 16:09:09 +01008016sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008017 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008018 audio_format_t& format,
8019 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008020 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008021{
8022 // Choose an input profile based on the requested capture parameters: select the first available
8023 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008024 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008025
Atneya Nair0f0a8032022-12-12 16:20:12 -08008026 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8027 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8028 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8029
8030 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008031
jiabin2fd710d2022-05-02 23:20:22 +00008032 for (;;) {
8033 sp<IOProfile> firstInexact = nullptr;
8034 uint32_t updatedSamplingRate = 0;
8035 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8036 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8037 for (const auto& hwModule : mHwModules) {
8038 for (const auto& profile : hwModule->getInputProfiles()) {
8039 // profile->log();
8040 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008041 if (profile->getCompatibilityScore(
8042 DeviceVector(device),
8043 samplingRate,
8044 &updatedSamplingRate,
8045 format,
8046 &updatedFormat,
8047 channelMask,
8048 &updatedChannelMask,
8049 // FIXME ugly cast
8050 (audio_output_flags_t) flags,
8051 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8052 samplingRate = updatedSamplingRate;
8053 format = updatedFormat;
8054 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008055 return profile;
8056 }
jiabin66acc432024-02-06 00:57:36 +00008057 if (firstInexact == nullptr
8058 && profile->getCompatibilityScore(
8059 DeviceVector(device),
8060 samplingRate,
8061 &updatedSamplingRate,
8062 format,
8063 &updatedFormat,
8064 channelMask,
8065 &updatedChannelMask,
8066 // FIXME ugly cast
8067 (audio_output_flags_t) flags,
8068 false /*exactMatchRequiredForInputFlags*/)
8069 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008070 firstInexact = profile;
8071 }
8072 }
8073 }
8074
8075 if (firstInexact != nullptr) {
8076 samplingRate = updatedSamplingRate;
8077 format = updatedFormat;
8078 channelMask = updatedChannelMask;
8079 return firstInexact;
8080 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8081 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8082 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8083 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8084 flags = AUDIO_INPUT_FLAG_NONE;
8085 } else { // fail
8086 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8087 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8088 samplingRate, format, channelMask, oriFlags);
8089 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008090 }
8091 }
jiabin2fd710d2022-05-02 23:20:22 +00008092
8093 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008094}
8095
Vlad Popa87e0e582024-05-20 18:49:20 -07008096float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8097 VolumeSource volumeSource,
8098 int index,
8099 const DeviceTypeSet &deviceTypes)
8100{
8101 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8102 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8103 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8104
8105 if (com_android_media_audio_abs_volume_index_fix()) {
8106 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8107 mAbsoluteVolumeDrivingStreams.end()) {
8108 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8109 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8110 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8111 ALOGD("%s: no group matching with %s", __FUNCTION__,
8112 toString(attributesToDriveAbs).c_str());
8113 return volumeDb;
8114 }
8115
8116 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8117 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8118 if (vsToDriveAbs == volumeSource) {
8119 // attenuation is applied by the abs volume controller
8120 return volumeDbMax;
8121 } else {
8122 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8123 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8124 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8125 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8126 curvesAbs.getVolumeIndexMax());
8127 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8128 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8129 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8130 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8131 return newVolumeDb;
8132 }
8133 }
8134 return volumeDb;
8135 } else {
8136 return volumeDb;
8137 }
8138}
8139
François Gaffieaaac0fd2018-11-22 17:56:39 +01008140float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8141 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008142 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008143 const DeviceTypeSet& deviceTypes,
8144 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008145{
Vlad Popa87e0e582024-05-20 18:49:20 -07008146 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008147 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8148 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8149
8150 if (!computeInternalInteraction) {
8151 return volumeDb;
8152 }
8153
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008154 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8155 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8156 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8157 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008158 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8159 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8160 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8161 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8162 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008163 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008164 mOutputs.isActive(ringVolumeSrc, 0)) {
8165 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008166 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8167 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008168 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008169 }
8170
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008171 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008172 if ((volumeSource != callVolumeSrc && (isInCall() ||
8173 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008174 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008175 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8176 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008177 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8178 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8179 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008180 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008181 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008182 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008183 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008184 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8185 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008186 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008187 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8188 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8189 // programmatically muted.
8190 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8191 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8192 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008193 bool exemptFromCapping =
8194 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8195 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008196 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8197 volumeSource, volumeDb);
8198 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008199 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8200 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8201 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008202 }
8203 }
Eric Laurente552edb2014-03-10 17:42:56 -07008204 // if a headset is connected, apply the following rules to ring tones and notifications
8205 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008206 // - always attenuate notifications volume by 6dB
8207 // - attenuate ring tones volume by 6dB unless music is not playing and
8208 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008209 // - if music is playing, always limit the volume to current music volume,
8210 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008211 if (!Intersection(deviceTypes,
8212 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8213 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008214 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8215 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008216 ((volumeSource == alarmVolumeSrc ||
8217 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008218 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8219 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8220 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008221 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8222 curves.canBeMuted()) {
8223
Eric Laurente552edb2014-03-10 17:42:56 -07008224 // when the phone is ringing we must consider that music could have been paused just before
8225 // by the music application and behave as if music was active if the last music track was
8226 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008227 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8228 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008229 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008230 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008231 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8232 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008233 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008234 float musicVolDb = computeVolume(musicCurves,
8235 musicVolumeSrc,
8236 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008237 musicDevice,
8238 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008239 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8240 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8241 if (volumeDb > minVolDb) {
8242 volumeDb = minVolDb;
8243 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008244 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008245 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8246 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008247 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8248 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8249 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8250 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008251 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008252 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008253 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8254 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008255 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8256 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008257 }
8258 }
jiabin9a3361e2019-10-01 09:38:30 -07008259 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008260 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008261 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008262 }
8263 }
8264
François Gaffie43c73442018-11-08 08:21:55 +01008265 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008266}
8267
Eric Laurent3839bc02018-07-10 18:33:34 -07008268int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008269 VolumeSource fromVolumeSource,
8270 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008271{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008272 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008273 return srcIndex;
8274 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008275 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8276 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008277 float minSrc = (float)srcCurves.getVolumeIndexMin();
8278 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8279 float minDst = (float)dstCurves.getVolumeIndexMin();
8280 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008281
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008282 // preserve mute request or correct range
8283 if (srcIndex < minSrc) {
8284 if (srcIndex == 0) {
8285 return 0;
8286 }
8287 srcIndex = minSrc;
8288 } else if (srcIndex > maxSrc) {
8289 srcIndex = maxSrc;
8290 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008291 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8292}
8293
François Gaffieaaac0fd2018-11-22 17:56:39 +01008294status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8295 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008296 int index,
8297 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008298 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008299 int delayMs,
8300 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008301{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008302 // do not change actual attributes volume if the attributes is muted
8303 if (outputDesc->isMuted(volumeSource)) {
8304 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8305 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008306 return NO_ERROR;
8307 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008308
Eric Laurentae6e88c2024-01-10 14:42:57 +01008309 bool isVoiceVolSrc;
8310 bool isBtScoVolSrc;
8311 if (!isVolumeConsistentForCalls(
8312 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008313 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008314 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008315 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008316 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008317
jiabin9a3361e2019-10-01 09:38:30 -07008318 if (deviceTypes.empty()) {
8319 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008320 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008321 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008322 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008323 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008324
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008325 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8326 ALOGE("invalid volume index range");
8327 return BAD_VALUE;
8328 }
8329
jiabin9a3361e2019-10-01 09:38:30 -07008330 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8331 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008332 // Force VoIP volume to max for bluetooth SCO device except if muted
8333 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008334 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008335 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008336 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008337 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008338 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8339 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008340
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008341 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008342 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008343 }
Eric Laurente552edb2014-03-10 17:42:56 -07008344 return NO_ERROR;
8345}
8346
Eric Laurentae6e88c2024-01-10 14:42:57 +01008347void AudioPolicyManager::setVoiceVolume(
8348 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8349 float voiceVolume;
8350 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8351 // by the headset
8352 if (isVoiceVolSrc) {
8353 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8354 } else {
8355 voiceVolume = index == 0 ? 0.0 : 1.0;
8356 }
8357 if (voiceVolume != mLastVoiceVolume) {
8358 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8359 mLastVoiceVolume = voiceVolume;
8360 }
8361}
8362
8363bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8364 const DeviceTypeSet& deviceTypes,
8365 bool& isVoiceVolSrc,
8366 bool& isBtScoVolSrc,
8367 const char* caller) {
8368 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8369 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8370 const bool isScoRequested = isScoRequestedForComm();
8371 const bool isHAUsed = isHearingAidUsedForComm();
8372
8373 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8374 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8375
8376 if ((callVolSrc != btScoVolSrc) &&
8377 ((isVoiceVolSrc && isScoRequested) ||
8378 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8379 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8380 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8381 volumeSource, isScoRequested ? " " : " not ");
8382 return false;
8383 }
8384 return true;
8385}
8386
Eric Laurentc75307b2015-03-17 15:29:32 -07008387void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008388 const DeviceTypeSet& deviceTypes,
8389 int delayMs,
8390 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008391{
jiabincd510522020-01-22 09:40:55 -08008392 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008393 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8394 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8395 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008396 curves.getVolumeIndex(deviceTypes),
8397 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008398 }
8399}
8400
François Gaffiec005e562018-11-06 15:04:49 +01008401void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8402 bool on,
8403 const sp<AudioOutputDescriptor>& outputDesc,
8404 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008405 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008406{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008407 std::vector<VolumeSource> sourcesToMute;
8408 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8409 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8410 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008411 VolumeSource source = toVolumeSource(attributes, false);
8412 if ((source != VOLUME_SOURCE_NONE) &&
8413 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8414 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008415 sourcesToMute.push_back(source);
8416 }
Eric Laurente552edb2014-03-10 17:42:56 -07008417 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008418 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008419 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008420 }
8421
Eric Laurente552edb2014-03-10 17:42:56 -07008422}
8423
François Gaffieaaac0fd2018-11-22 17:56:39 +01008424void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8425 bool on,
8426 const sp<AudioOutputDescriptor>& outputDesc,
8427 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008428 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008429{
jiabin9a3361e2019-10-01 09:38:30 -07008430 if (deviceTypes.empty()) {
8431 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008432 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008433 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008434 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008435 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008436 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008437 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008438 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8439 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008440 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008441 }
8442 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008443 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8444 // ignored
8445 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008446 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008447 if (!outputDesc->isMuted(volumeSource)) {
8448 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008449 return;
8450 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008451 if (outputDesc->decMuteCount(volumeSource) == 0) {
8452 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008453 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008454 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008455 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008456 delayMs);
8457 }
8458 }
8459}
8460
François Gaffie53615e22015-03-19 09:24:12 +01008461bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8462{
François Gaffiec005e562018-11-06 15:04:49 +01008463 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008464 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8465 return true;
8466 }
8467
8468 // has known usage?
8469 switch (paa->usage) {
8470 case AUDIO_USAGE_UNKNOWN:
8471 case AUDIO_USAGE_MEDIA:
8472 case AUDIO_USAGE_VOICE_COMMUNICATION:
8473 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8474 case AUDIO_USAGE_ALARM:
8475 case AUDIO_USAGE_NOTIFICATION:
8476 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8477 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8478 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8479 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8480 case AUDIO_USAGE_NOTIFICATION_EVENT:
8481 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8482 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8483 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8484 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008485 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008486 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008487 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008488 case AUDIO_USAGE_EMERGENCY:
8489 case AUDIO_USAGE_SAFETY:
8490 case AUDIO_USAGE_VEHICLE_STATUS:
8491 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008492 break;
8493 default:
8494 return false;
8495 }
8496 return true;
8497}
8498
François Gaffie2110e042015-03-24 08:41:51 +01008499audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8500{
8501 return mEngine->getForceUse(usage);
8502}
8503
Eric Laurent96d1dda2022-03-14 17:14:19 +01008504bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008505 return isStateInCall(mEngine->getPhoneState());
8506}
8507
Eric Laurent96d1dda2022-03-14 17:14:19 +01008508bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008509 return is_state_in_call(state);
8510}
8511
Eric Laurentf9cccec2022-11-16 19:12:00 +01008512bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008513 audio_mode_t mode = mEngine->getPhoneState();
8514 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008515 || (mode == AUDIO_MODE_CALL_SCREEN)
8516 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008517}
8518
Eric Laurentf9cccec2022-11-16 19:12:00 +01008519bool AudioPolicyManager::isInCallOrScreening() const {
8520 audio_mode_t mode = mEngine->getPhoneState();
8521 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8522}
8523
Eric Laurentd60560a2015-04-10 11:31:20 -07008524void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8525{
8526 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008527 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008528 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008529 sourceDesc->sinkDevice()->equals(deviceDesc))
8530 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008531 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008532 }
8533 }
8534
8535 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8536 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8537 bool release = false;
8538 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8539 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8540 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8541 source->ext.device.type == deviceDesc->type()) {
8542 release = true;
8543 }
8544 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008545 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008546 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8547 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8548 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008549 sink->ext.device.type == deviceDesc->type() &&
8550 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8551 || strncmp(sink->ext.device.address, address,
8552 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008553 release = true;
8554 }
8555 }
8556 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008557 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8558 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008559 }
8560 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008561
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008562 mInputs.clearSessionRoutesForDevice(deviceDesc);
8563
Francois Gaffie716e1432019-01-14 16:58:59 +01008564 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008565}
8566
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008567void AudioPolicyManager::modifySurroundFormats(
8568 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008569 std::unordered_set<audio_format_t> enforcedSurround(
8570 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008571 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008572 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008573 allSurround.insert(pair.first);
8574 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8575 }
Phil Burk09bc4612016-02-24 15:58:15 -08008576
8577 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8578 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008579 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008580 // This is the resulting set of formats depending on the surround mode:
8581 // 'all surround' = allSurround
8582 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8583 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8584 // 'manual surround' = mManualSurroundFormats
8585 // AUTO: formats v 'enforced surround'
8586 // ALWAYS: formats v 'all surround' v 'enforced surround'
8587 // NEVER: formats ^ 'non-surround'
8588 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008589
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008590 std::unordered_set<audio_format_t> formatSet;
8591 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8592 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008593 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008594 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008595 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008596 formatSet.insert(*formatIter);
8597 }
8598 }
8599 } else {
8600 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8601 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008602 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008603
jiabin81772902018-04-02 17:52:27 -07008604 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008605 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008606 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8607 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8608 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008609 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008610 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8611 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8612 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008613 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008614 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008615 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008616 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008617 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008618 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008619}
8620
jiabin06e4bab2019-07-29 10:13:34 -07008621void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8622 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008623 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8624 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8625
8626 // If NEVER, then remove support for channelMasks > stereo.
8627 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008628 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8629 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008630 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008631 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008632 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008633 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008634 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008635 }
8636 }
jiabin81772902018-04-02 17:52:27 -07008637 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8638 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8639 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008640 bool supports5dot1 = false;
8641 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008642 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008643 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8644 supports5dot1 = true;
8645 break;
8646 }
8647 }
8648 // If not then add 5.1 support.
8649 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008650 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008651 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008652 }
Phil Burk09bc4612016-02-24 15:58:15 -08008653 }
8654}
8655
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008656void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008657 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008658 const sp<IOProfile>& profile) {
8659 if (!profile->hasDynamicAudioProfile()) {
8660 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008661 }
François Gaffie112b0af2015-11-19 16:13:25 +01008662
jiabin12537fc2023-10-12 17:56:08 +00008663 audio_port_v7 devicePort;
8664 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008665
jiabin12537fc2023-10-12 17:56:08 +00008666 audio_port_v7 mixPort;
8667 profile->toAudioPort(&mixPort);
8668 mixPort.ext.mix.handle = ioHandle;
8669
8670 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8671 if (status != NO_ERROR) {
8672 ALOGE("%s failed to query the attributes of the mix port", __func__);
8673 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008674 }
jiabin12537fc2023-10-12 17:56:08 +00008675
8676 std::set<audio_format_t> supportedFormats;
8677 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8678 supportedFormats.insert(mixPort.audio_profiles[i].format);
8679 }
8680 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8681 mReportedFormatsMap[devDesc] = formats;
8682
8683 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8684 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8685 modifySurroundFormats(devDesc, &formats);
8686 size_t modifiedNumProfiles = 0;
8687 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8688 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8689 formats.end()) {
8690 // Skip the format that is not present after modifying surround formats.
8691 continue;
8692 }
8693 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8694 sizeof(struct audio_profile));
8695 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8696 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8697 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8698 modifySurroundChannelMasks(&channels);
8699 std::copy(channels.begin(), channels.end(),
8700 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8701 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8702 }
8703 mixPort.num_audio_profiles = modifiedNumProfiles;
8704 }
8705 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008706}
Eric Laurentd60560a2015-04-10 11:31:20 -07008707
Mikhail Naganovdc769682018-05-04 15:34:08 -07008708status_t AudioPolicyManager::installPatch(const char *caller,
8709 audio_patch_handle_t *patchHandle,
8710 AudioIODescriptorInterface *ioDescriptor,
8711 const struct audio_patch *patch,
8712 int delayMs)
8713{
8714 ssize_t index = mAudioPatches.indexOfKey(
8715 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8716 *patchHandle : ioDescriptor->getPatchHandle());
8717 sp<AudioPatch> patchDesc;
8718 status_t status = installPatch(
8719 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8720 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008721 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008722 }
8723 return status;
8724}
8725
8726status_t AudioPolicyManager::installPatch(const char *caller,
8727 ssize_t index,
8728 audio_patch_handle_t *patchHandle,
8729 const struct audio_patch *patch,
8730 int delayMs,
8731 uid_t uid,
8732 sp<AudioPatch> *patchDescPtr)
8733{
8734 sp<AudioPatch> patchDesc;
8735 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8736 if (index >= 0) {
8737 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008738 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008739 }
8740
8741 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8742 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8743 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8744 if (status == NO_ERROR) {
8745 if (index < 0) {
8746 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008747 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008748 } else {
8749 patchDesc->mPatch = *patch;
8750 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008751 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008752 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008753 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008754 }
8755 nextAudioPortGeneration();
8756 mpClientInterface->onAudioPatchListUpdate();
8757 }
8758 if (patchDescPtr) *patchDescPtr = patchDesc;
8759 return status;
8760}
8761
jiabinbce0c1d2020-10-05 11:20:18 -07008762bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8763{
8764 const TrackClientVector activeClients = output->getActiveClients();
8765 if (activeClients.empty()) {
8766 return true;
8767 }
8768 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8769 if (index < 0) {
8770 ALOGE("%s, no audio patch found while there are active clients on output %d",
8771 __func__, output->getId());
8772 return false;
8773 }
8774 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8775 DeviceVector routedDevices;
8776 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8777 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8778 patchDesc->mPatch.sinks[i].id);
8779 if (device == nullptr) {
8780 ALOGE("%s, no audio device found with id(%d)",
8781 __func__, patchDesc->mPatch.sinks[i].id);
8782 return false;
8783 }
8784 routedDevices.add(device);
8785 }
8786 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008787 if (client->isInvalid()) {
8788 // No need to take care about invalidated clients.
8789 continue;
8790 }
jiabinbce0c1d2020-10-05 11:20:18 -07008791 sp<DeviceDescriptor> preferredDevice =
8792 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8793 if (mEngine->getOutputDevicesForAttributes(
8794 client->attributes(), preferredDevice, false) == routedDevices) {
8795 return false;
8796 }
8797 }
8798 return true;
8799}
8800
8801sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008802 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008803 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8804 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008805{
8806 for (const auto& device : devices) {
8807 // TODO: This should be checking if the profile supports the device combo.
8808 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008809 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8810 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008811 return nullptr;
8812 }
8813 }
8814 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8815 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008816 status_t status = desc->open(halConfig, mixerConfig, devices,
8817 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008818 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008819 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008820 return nullptr;
8821 }
jiabin14b50cc2023-12-13 19:01:52 +00008822 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8823 auto portConfig = desc->getConfig();
8824 for (const auto& device : devices) {
8825 device->setPreferredConfig(&portConfig);
8826 }
8827 }
jiabinbce0c1d2020-10-05 11:20:18 -07008828
8829 // Here is where the out_set_parameters() for card & device gets called
8830 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8831 const audio_devices_t deviceType = device->type();
8832 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008833 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008834 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8835 mpClientInterface->setParameters(output, String8(param));
8836 free(param);
8837 }
jiabin12537fc2023-10-12 17:56:08 +00008838 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008839 if (!profile->hasValidAudioProfile()) {
8840 ALOGW("%s() missing param", __func__);
8841 desc->close();
8842 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008843 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8844 // Reopen the output with the best audio profile picked by APM when the profile supports
8845 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008846 desc->close();
8847 output = AUDIO_IO_HANDLE_NONE;
8848 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8849 profile->pickAudioProfile(
8850 config.sample_rate, config.channel_mask, config.format);
8851 config.offload_info.sample_rate = config.sample_rate;
8852 config.offload_info.channel_mask = config.channel_mask;
8853 config.offload_info.format = config.format;
8854
jiabina84c3d32022-12-02 18:59:55 +00008855 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008856 if (status != NO_ERROR) {
8857 return nullptr;
8858 }
8859 }
8860
8861 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008862 setOutputDevices(__func__, desc,
8863 devices,
8864 true,
8865 0,
8866 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008867 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8868 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8869
jiabinbce0c1d2020-10-05 11:20:18 -07008870 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8871 sp<AudioPolicyMix> policyMix;
8872 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8873 policyMix->setOutput(desc);
8874 desc->mPolicyMix = policyMix;
8875 } else {
8876 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008877 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008878 }
8879
baek.kim -61c20122022-07-27 10:05:32 +00008880 } else if (hasPrimaryOutput() && speaker != nullptr
8881 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008882 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8883 // no duplicated output for:
8884 // - direct outputs
8885 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008886 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008887 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8888
8889 //TODO: configure audio effect output stage here
8890
8891 // open a duplicating output thread for the new output and the primary output
8892 sp<SwAudioOutputDescriptor> dupOutputDesc =
8893 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8894 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8895 if (status == NO_ERROR) {
8896 // add duplicated output descriptor
8897 addOutput(duplicatedOutput, dupOutputDesc);
8898 } else {
8899 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8900 mPrimaryOutput->mIoHandle, output);
8901 desc->close();
8902 removeOutput(output);
8903 nextAudioPortGeneration();
8904 return nullptr;
8905 }
8906 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008907 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8908 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8909 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008910 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008911 }
jiabinbce0c1d2020-10-05 11:20:18 -07008912 return desc;
8913}
8914
jiabinf1c73972022-04-14 16:28:52 -07008915status_t AudioPolicyManager::getDevicesForAttributes(
8916 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8917 // Devices are determined in the following precedence:
8918 //
8919 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8920 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8921 //
8922 // If no such dynamic policy then
8923 // 2) Devices containing an active client using setPreferredDevice
8924 // with same strategy as the attributes.
8925 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8926 //
8927 // If no corresponding active client with setPreferredDevice then
8928 // 3) Devices associated with the strategy determined by the attributes
8929 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8930 //
8931 // See related getOutputForAttrInt().
8932
8933 // check dynamic policies but only for primary descriptors (secondary not used for audible
8934 // audio routing, only used for duplication for playback capture)
8935 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008936 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008937 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008938 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8939 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8940 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008941 if (status != OK) {
8942 return status;
8943 }
8944
8945 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8946 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8947 // as they are unaffected by device/stream volume
8948 // (per SwAudioOutputDescriptor::isFixedVolume()).
8949 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8950 ) {
8951 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8952 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8953 devices.add(deviceDesc);
8954 } else {
8955 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8956 // which selects setPreferredDevice if active. This means forVolume call
8957 // will take an active setPreferredDevice, if such exists.
8958
8959 devices = mEngine->getOutputDevicesForAttributes(
8960 attr, nullptr /* preferredDevice */, false /* fromCache */);
8961 }
8962
8963 if (forVolume) {
8964 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8965 // for single volume control in AudioService (such relationship should exist if
8966 // SPEAKER_SAFE is present).
8967 //
8968 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8969 DeviceVector speakerSafeDevices =
8970 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8971 if (!speakerSafeDevices.isEmpty()) {
8972 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8973 devices.remove(speakerSafeDevices);
8974 }
8975 }
8976
8977 return NO_ERROR;
8978}
8979
8980status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8981 AudioProfileVector& audioProfiles,
8982 uint32_t flags,
8983 bool isInput) {
8984 for (const auto& hwModule : mHwModules) {
8985 // the MSD module checks for different conditions
8986 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8987 continue;
8988 }
8989 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8990 : hwModule->getOutputProfiles();
8991 for (const auto& profile : ioProfiles) {
8992 if (!profile->areAllDevicesSupported(devices) ||
8993 !profile->isCompatibleProfileForFlags(
8994 flags, false /*exactMatchRequiredForInputFlags*/)) {
8995 continue;
8996 }
8997 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8998 }
8999 }
9000
9001 if (!isInput) {
9002 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9003 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9004 if (msdModule != nullptr) {
9005 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9006 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9007 for (const auto &profile: msdModule->getOutputProfiles()) {
9008 if (!profile->asAudioPort()->isDirectOutput()) {
9009 continue;
9010 }
9011 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9012 }
9013 } else {
9014 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9015 }
9016 }
9017 }
9018
9019 return NO_ERROR;
9020}
9021
jiabin3ff8d7d2022-12-13 06:27:44 +00009022sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9023 const audio_config_t *config,
9024 audio_output_flags_t flags,
9025 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009026 closeOutput(outputDesc->mIoHandle);
9027 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9028 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9029 if (preferredOutput == nullptr) {
9030 ALOGE("%s failed to reopen output device=%d, caller=%s",
9031 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009032 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009033 return preferredOutput;
9034}
9035
9036void AudioPolicyManager::reopenOutputsWithDevices(
9037 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9038 for (const auto& [output, devices] : outputsToReopen) {
9039 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9040 closeOutput(output);
9041 openOutputWithProfileAndDevice(desc->mProfile, devices);
9042 }
jiabina84c3d32022-12-02 18:59:55 +00009043}
9044
jiabinc44b3462022-12-08 12:52:31 -08009045PortHandleVector AudioPolicyManager::getClientsForStream(
9046 audio_stream_type_t streamType) const {
9047 PortHandleVector clients;
9048 for (size_t i = 0; i < mOutputs.size(); ++i) {
9049 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9050 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9051 }
9052 return clients;
9053}
9054
9055void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9056 PortHandleVector clients;
9057 for (auto stream : streams) {
9058 PortHandleVector clientsForStream = getClientsForStream(stream);
9059 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9060 }
9061 mpClientInterface->invalidateTracks(clients);
9062}
9063
jiabin220eea12024-05-17 17:55:20 +00009064void AudioPolicyManager::updateClientsInternalMute(
9065 const sp<android::SwAudioOutputDescriptor> &desc) {
9066 if (!desc->isBitPerfect() ||
9067 !com::android::media::audioserver::
9068 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9069 // This is only used for bit perfect output now.
9070 return;
9071 }
9072 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9073 bool bitPerfectClientInternalMute = false;
9074 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9075 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9076 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9077 bitPerfectClient = client;
9078 continue;
9079 }
9080 bool muted = false;
9081 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9082 // System sound is muted.
9083 muted = true;
9084 } else {
9085 bitPerfectClientInternalMute = true;
9086 }
9087 if (client->setInternalMute(muted)) {
9088 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9089 if (!result.ok()) {
9090 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9091 continue;
9092 }
9093 media::TrackInternalMuteInfo info;
9094 info.portId = result.value();
9095 info.muted = client->getInternalMute();
9096 clientsInternalMute.push_back(std::move(info));
9097 }
9098 }
9099 if (bitPerfectClient != nullptr &&
9100 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9101 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9102 if (result.ok()) {
9103 media::TrackInternalMuteInfo info;
9104 info.portId = result.value();
9105 info.muted = bitPerfectClient->getInternalMute();
9106 clientsInternalMute.push_back(std::move(info));
9107 } else {
9108 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9109 __func__, bitPerfectClient->portId());
9110 }
9111 }
9112 if (!clientsInternalMute.empty()) {
9113 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9114 status != NO_ERROR) {
9115 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9116 }
9117 }
9118}
9119
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009120} // namespace android