blob: 7ec5f484410d4e35c03915ab811efb36b8d88da5 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700377 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700378 } // end if is output device
379
Eric Laurente552edb2014-03-10 17:42:56 -0700380 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700381 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100382 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700383 switch (state)
384 {
385 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700386 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100388 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700389 return INVALID_OPERATION;
390 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700391
392 if (mAvailableInputDevices.add(device) < 0) {
393 return NO_MEMORY;
394 }
395
François Gaffie44481e72016-04-20 07:49:57 +0200396 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
397 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200399
Eric Laurent0dd51852019-04-19 18:18:58 -0700400 if (checkInputsForDevice(device, state) != NO_ERROR) {
401 mAvailableInputDevices.remove(device);
402
jiabinc0048632023-04-27 22:04:31 +0000403 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100404
405 mHwModules.cleanUpForDevice(device);
406
Eric Laurentd4692962014-05-05 18:13:44 -0700407 return INVALID_OPERATION;
408 }
409
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700413 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700414 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100415 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700416 return INVALID_OPERATION;
417 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700420
jiabinc0048632023-04-27 22:04:31 +0000421 // Notify the HAL to prepare to disconnect device
422 broadcastDeviceConnectionState(
423 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700424
François Gaffie11d30102018-11-02 16:09:09 +0100425 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700426
427 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100428
jiabinc0048632023-04-27 22:04:31 +0000429 // Set Disconnect to HALs
430 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
431
Kriti Dangef6be8f2020-11-05 11:58:19 +0100432 // remove device from mReportedFormatsMap cache
433 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700434 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700435
436 default:
François Gaffie11d30102018-11-02 16:09:09 +0100437 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700438 return BAD_VALUE;
439 }
440
Eric Laurent736a1022019-03-27 18:28:46 -0700441 // Propagate device availability to Engine
442 setEngineDeviceConnectionState(device, state);
443
Eric Laurent0dd51852019-04-19 18:18:58 -0700444 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700445 // As the input device list can impact the output device selection, update
446 // getDeviceForStrategy() cache
447 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700448
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100449 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200450 // Reconnect Audio Source
451 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
452 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
453 checkAudioSourceForAttributes(attributes);
454 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700455 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100456 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700457 }
458
Eric Laurentb52c1522014-05-20 11:27:36 -0700459 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700460 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700461 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700462
François Gaffie11d30102018-11-02 16:09:09 +0100463 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700464 return BAD_VALUE;
465}
466
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100467status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
468 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800469 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700470 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
471 devDescr->setName(device_name);
472 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100473}
474
Eric Laurent736a1022019-03-27 18:28:46 -0700475void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
476 audio_policy_dev_state_t state) {
477
478 // the Engine does not have to know about remote submix devices used by dynamic audio policies
479 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
480 return;
481 }
482 mEngine->setDeviceConnectionState(device, state);
483}
484
485
Eric Laurente0720872014-03-11 09:30:41 -0700486audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100487 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700488{
Eric Laurent634b7142016-04-20 13:48:02 -0700489 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800490 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
491 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700492 (strlen(device_address) != 0)/*matchAddress*/);
493
494 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100495 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700496 device, device_address);
497 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
498 }
François Gaffie53615e22015-03-19 09:24:12 +0100499
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 DeviceVector *deviceVector;
501
Eric Laurente552edb2014-03-10 17:42:56 -0700502 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700503 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700504 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700505 deviceVector = &mAvailableInputDevices;
506 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100507 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700509 }
Eric Laurent634b7142016-04-20 13:48:02 -0700510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 return (deviceVector->getDevice(
512 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700513 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800514}
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
517 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 const char *device_name,
519 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800521 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
522 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800524 // connect/disconnect only 1 device at a time
525 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
526
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700528 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800530 // Nothing to do: device is not connected
531 return NO_ERROR;
532 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800534
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700535 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800536 // configure codecs.
537 // Handle two specific cases by sending a set parameter to
538 // configure A2DP codecs. No need to toggle device state.
539 // Case 1: A2DP active device switches from primary to primary
540 // module
541 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100542 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700543 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
545 if (availablePrimaryOutputDevices().contains(devDesc) &&
546 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 bool isA2dp = audio_is_a2dp_out_device(device);
548 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
549 : String8(AudioParameter::keyReconfigLeSupported);
550 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100552 int isReconfigSupported;
553 repliedParameters.getInt(supportKey, isReconfigSupported);
554 if (isReconfigSupported) {
555 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
556 : String8(AudioParameter::keyReconfigLe);
557 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800558 param.add(key, String8("true"));
559 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
560 devDesc->setEncodedFormat(encodedFormat);
561 return NO_ERROR;
562 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700563 }
564 }
cnx421bd2dcc42020-07-11 14:58:44 +0800565 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000566 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800567 for (size_t i = 0; i < mOutputs.size(); i++) {
568 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000569 // mute media strategies to avoid sending the music tail into
570 // the earpiece or headset.
571 if (desc->isStrategyActive(musicStrategy)) {
572 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
573 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
574 tempRecommendedMuteDuration : desc->latency() * 4;
575 if (muteWaitMs < tempMuteDurationMs) {
576 muteWaitMs = tempMuteDurationMs;
577 }
578 }
cnx421bd2dcc42020-07-11 14:58:44 +0800579 setStrategyMute(musicStrategy, true, desc);
580 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
581 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
582 nullptr, true /*fromCache*/).types());
583 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000584 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
585 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
586 // happens after the actual device switch.
587 if (muteWaitMs > 0) {
588 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
589 usleep(muteWaitMs * 1000);
590 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800591 // Toggle the device state: UNAVAILABLE -> AVAILABLE
592 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100593 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800594 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800595 device_address, device_name,
596 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800597 if (status != NO_ERROR) {
598 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
599 status);
600 return status;
601 }
602
603 status = setDeviceConnectionState(device,
604 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800605 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800606 if (status != NO_ERROR) {
607 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
608 status);
609 return status;
610 }
611
612 return NO_ERROR;
613}
614
Pattydd807582021-11-04 21:01:03 +0800615status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
616 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800617{
Pattydd807582021-11-04 21:01:03 +0800618 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800619 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800620 std::unordered_set<audio_format_t> formatSet;
621 sp<HwModule> primaryModule =
622 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700623 if (primaryModule == nullptr) {
624 ALOGE("%s() unable to get primary module", __func__);
625 return NO_INIT;
626 }
Pattydd807582021-11-04 21:01:03 +0800627
628 DeviceTypeSet audioDeviceSet;
629
630 switch(device) {
631 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
632 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
633 break;
634 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800635 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
636 break;
637 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
638 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800639 break;
640 default:
641 ALOGE("%s() device type 0x%08x not supported", __func__, device);
642 return BAD_VALUE;
643 }
644
jiabin9a3361e2019-10-01 09:38:30 -0700645 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800646 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800647 for (const auto& device : declaredDevices) {
648 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800649 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800650 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800651 return status;
652}
653
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100654DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
655{
656 DeviceVector rxSinkdevices{};
657 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
658 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
659 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
660 auto rxSinkDevice = rxSinkdevices.itemAt(0);
661 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
662 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
663 // retrieve Rx Source device descriptor
664 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
665 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
666
667 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
668 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
669 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
670 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
671 return DeviceVector(rxSinkDevice);
672 }
673 }
674 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
675 // the device returned is not necessarily reachable via this output
676 // (filter later by setOutputDevices())
677 return getNewOutputDevices(mPrimaryOutput, fromCache);
678}
679
680status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
681{
François Gaffiedb1755b2023-09-01 11:50:35 +0200682 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100683 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
684 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
685 }
686 return INVALID_OPERATION;
687}
688
689status_t AudioPolicyManager::updateCallRoutingInternal(
690 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691{
692 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100693 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700694 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200695 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700696 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100697 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700698 }
François Gaffie11d30102018-11-02 16:09:09 +0100699
Francois Gaffie716e1432019-01-14 16:58:59 +0100700 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100701 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200702
703 disconnectTelephonyAudioSource(mCallRxSourceClient);
704 disconnectTelephonyAudioSource(mCallTxSourceClient);
705
706 if (rxDevices.isEmpty()) {
707 ALOGW("%s() no selected output device", __func__);
708 return INVALID_OPERATION;
709 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000710 if (txSourceDevice == nullptr) {
711 ALOGE("%s() selected input device not available", __func__);
712 return INVALID_OPERATION;
713 }
François Gaffiec005e562018-11-06 15:04:49 +0100714
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100715 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100716 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700717
François Gaffie9eb18552018-11-05 10:33:26 +0100718 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700719 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100720 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700721 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100722 // retrieve Rx Source and Tx Sink device descriptors
723 sp<DeviceDescriptor> rxSourceDevice =
724 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
725 String8(),
726 AUDIO_FORMAT_DEFAULT);
727 sp<DeviceDescriptor> txSinkDevice =
728 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
729 String8(),
730 AUDIO_FORMAT_DEFAULT);
731
732 // RX and TX Telephony device are declared by Primary Audio HAL
733 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
734 (telephonyRxModule->getHalVersionMajor() >= 3)) {
735 if (rxSourceDevice == 0 || txSinkDevice == 0) {
736 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100737 ALOGE("%s() no telephony Tx and/or RX device", __func__);
738 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100739 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100740 // createAudioPatchInternal now supports both HW / SW bridging
741 createRxPatch = true;
742 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100743 } else {
744 // If the RX device is on the primary HW module, then use legacy routing method for
745 // voice calls via setOutputDevice() on primary output.
746 // Otherwise, create two audio patches for TX and RX path.
747 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
748 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700749 // If the TX device is also on the primary HW module, setOutputDevice() will take care
750 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100751 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
752 (txSinkDevice != 0);
753 }
754 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
755 // Otherwise, create two audio patches for TX and RX path.
756 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200757 if (!hasPrimaryOutput()) {
758 ALOGW("%s() no primary output available", __func__);
759 return INVALID_OPERATION;
760 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530761 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700762 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200763 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800764 // If the TX device is on the primary HW module but RX device is
765 // on other HW module, SinkMetaData of telephony input should handle it
766 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700767 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700768 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100769 // terminate active capture if on the same HW module as the call TX source device
770 // FIXME: would be better to refine to only inputs whose profile connects to the
771 // call TX device but this information is not in the audio patch and logic here must be
772 // symmetric to the one in startInput()
773 for (const auto& activeDesc : mInputs.getActiveInputs()) {
774 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
775 closeActiveClients(activeDesc);
776 }
777 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200778 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800779 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100780 if (waitMs != nullptr) {
781 *waitMs = muteWaitMs;
782 }
783 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800784}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700785
Mikhail Naganov100f0122018-11-29 11:22:16 -0800786bool AudioPolicyManager::isDeviceOfModule(
787 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
788 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
789 if (module != 0) {
790 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
791 .indexOf(devDesc) != NAME_NOT_FOUND
792 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
793 .indexOf(devDesc) != NAME_NOT_FOUND;
794 }
795 return false;
796}
797
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200798void AudioPolicyManager::connectTelephonyRxAudioSource()
799{
Francois Gaffie601801d2021-06-22 13:27:39 +0200800 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200801 const struct audio_port_config source = {
802 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
803 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
804 };
805 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100806
807 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
808 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
809 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
810 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200811 ALOGE_IF(mCallRxSourceClient == nullptr,
812 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200813}
814
Francois Gaffie601801d2021-06-22 13:27:39 +0200815void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200816{
Francois Gaffie601801d2021-06-22 13:27:39 +0200817 if (clientDesc == nullptr) {
818 return;
819 }
820 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
821 "%s error stopping audio source", __func__);
822 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200823}
824
825void AudioPolicyManager::connectTelephonyTxAudioSource(
826 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
827 uint32_t delayMs)
828{
Francois Gaffie601801d2021-06-22 13:27:39 +0200829 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200830 if (srcDevice == nullptr || sinkDevice == nullptr) {
831 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
832 return;
833 }
834 PatchBuilder patchBuilder;
835 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
836 ALOGV("%s between source %s and sink %s", __func__,
837 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200839 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
840
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200841 struct audio_port_config source = {};
842 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100843 mCallTxSourceClient = new SourceClientDescriptor(
844 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
845 mCommunnicationStrategy, toVolumeSource(aa), true);
846 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
847
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200848 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
849 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200850 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
851 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200852 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
853 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200855 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200856}
857
Eric Laurente0720872014-03-11 09:30:41 -0700858void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700859{
860 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100861 // store previous phone state for management of sonification strategy below
862 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100863 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100864
865 if (mEngine->setPhoneState(state) != NO_ERROR) {
866 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700867 return;
868 }
François Gaffie2110e042015-03-24 08:41:51 +0100869 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700870 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700871 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700872 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800873 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
875
François Gaffie2110e042015-03-24 08:41:51 +0100876 /**
877 * Switching to or from incall state or switching between telephony and VoIP lead to force
878 * routing command.
879 */
Eric Laurent74b71512019-11-06 17:21:57 -0800880 bool force = ((isStateInCall(oldState) != isStateInCall(state))
881 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700882
883 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700884 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700885
Eric Laurente552edb2014-03-10 17:42:56 -0700886 int delayMs = 0;
887 if (isStateInCall(state)) {
888 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100889 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
890 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700891 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700892 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700893 // mute media and sonification strategies and delay device switch by the largest
894 // latency of any output where either strategy is active.
895 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100896 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
897 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
898 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700899 (delayMs < (int)desc->latency()*2)) {
900 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700901 }
François Gaffiec005e562018-11-06 15:04:49 +0100902 setStrategyMute(musicStrategy, true, desc);
903 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
904 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
905 nullptr, true /*fromCache*/).types());
906 setStrategyMute(sonificationStrategy, true, desc);
907 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
908 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
909 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700910 }
911 }
912
François Gaffiedb1755b2023-09-01 11:50:35 +0200913 if (state == AUDIO_MODE_IN_CALL) {
914 (void)updateCallRouting(false /*fromCache*/, delayMs);
915 } else {
916 if (oldState == AUDIO_MODE_IN_CALL) {
917 disconnectTelephonyAudioSource(mCallRxSourceClient);
918 disconnectTelephonyAudioSource(mCallTxSourceClient);
919 }
920 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100921 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
922 // force routing command to audio hardware when ending call
923 // even if no device change is needed
924 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
925 rxDevices = mPrimaryOutput->devices();
926 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530927 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700928 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700929 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700930
jiabin3ff8d7d2022-12-13 06:27:44 +0000931 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700932 // reevaluate routing on all outputs in case tracks have been started during the call
933 for (size_t i = 0; i < mOutputs.size(); i++) {
934 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100935 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000936 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
937 && desc->mPreferredAttrInfo != nullptr) {
938 // If the output is using preferred mixer attributes and the audio mode is not normal,
939 // the output need to reopen with default configuration.
940 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
941 continue;
942 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200943 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
944 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530945 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200946 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700947 }
948 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000949 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700950
Eric Laurent96d1dda2022-03-14 17:14:19 +0100951 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
952
Eric Laurente552edb2014-03-10 17:42:56 -0700953 if (isStateInCall(state)) {
954 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700955 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800956 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700957 }
958
959 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100960 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
961 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700962}
963
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700964audio_mode_t AudioPolicyManager::getPhoneState() {
965 return mEngine->getPhoneState();
966}
967
Eric Laurente0720872014-03-11 09:30:41 -0700968void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100969 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700970{
François Gaffie2110e042015-03-24 08:41:51 +0100971 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700972 if (config == mEngine->getForceUse(usage)) {
973 return;
974 }
Eric Laurente552edb2014-03-10 17:42:56 -0700975
François Gaffie2110e042015-03-24 08:41:51 +0100976 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
977 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
978 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
François Gaffie2110e042015-03-24 08:41:51 +0100980 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
981 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
982 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700983
984 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700985 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800986
Eric Laurent22fcda22019-05-17 16:28:47 -0700987 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
988 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800989 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700990 }
991
Eric Laurentdc462862016-07-19 12:29:53 -0700992 //FIXME: workaround for truncated touch sounds
993 // to be removed when the problem is handled by system UI
994 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700995 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
996 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
997 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700998
999 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001000 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001001}
1002
Eric Laurente0720872014-03-11 09:30:41 -07001003void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001004{
1005 ALOGV("setSystemProperty() property %s, value %s", property, value);
1006}
1007
Dorin Drimusecc9f422022-03-09 17:57:40 +01001008// Find an MSD output profile compatible with the parameters passed.
1009// When "directOnly" is set, restrict search to profiles for direct outputs.
1010sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1011 const DeviceVector& devices,
1012 uint32_t samplingRate,
1013 audio_format_t format,
1014 audio_channel_mask_t channelMask,
1015 audio_output_flags_t flags,
1016 bool directOnly)
1017{
1018 flags = getRelevantFlags(flags, directOnly);
1019
1020 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1021 if (msdModule != nullptr) {
1022 // for the msd module check if there are patches to the output devices
1023 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1024 HwModuleCollection modules;
1025 modules.add(msdModule);
1026 return searchCompatibleProfileHwModules(
1027 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1028 flags, directOnly);
1029 }
1030 }
1031 return nullptr;
1032}
1033
Michael Chana94fbb22018-04-24 14:31:19 +10001034// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1035// search to profiles for direct outputs.
1036sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001037 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001038 uint32_t samplingRate,
1039 audio_format_t format,
1040 audio_channel_mask_t channelMask,
1041 audio_output_flags_t flags,
1042 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001043{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001044 flags = getRelevantFlags(flags, directOnly);
1045
1046 return searchCompatibleProfileHwModules(
1047 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1048}
1049
1050audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1051 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001052 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001053 // only retain flags that will drive the direct output profile selection
1054 // if explicitly requested
1055 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001056 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001057 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1058 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001059 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001060 return flags;
1061}
Eric Laurent861a6282015-05-18 15:40:16 -07001062
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1064 const HwModuleCollection& hwModules,
1065 const DeviceVector& devices,
1066 uint32_t samplingRate,
1067 audio_format_t format,
1068 audio_channel_mask_t channelMask,
1069 audio_output_flags_t flags,
1070 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001071 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001072 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001073 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001074 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001075 samplingRate, NULL /*updatedSamplingRate*/,
1076 format, NULL /*updatedFormat*/,
1077 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001078 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001079 continue;
1080 }
1081 // reject profiles not corresponding to a device currently available
1082 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1083 continue;
1084 }
1085 // reject profiles if connected device does not support codec
1086 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1087 continue;
1088 }
1089 if (!directOnly) {
1090 return curProfile;
1091 }
1092
1093 // when searching for direct outputs, if several profiles are compatible, give priority
1094 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001095 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001096 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001097 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001098 }
1099 profile = curProfile;
1100 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1101 break;
1102 }
Eric Laurente552edb2014-03-10 17:42:56 -07001103 }
1104 }
Eric Laurent861a6282015-05-18 15:40:16 -07001105 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001106}
1107
Eric Laurentfa0f6742021-08-17 18:39:44 +02001108sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001109 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001110{
1111 for (const auto& hwModule : mHwModules) {
1112 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001113 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001114 continue;
1115 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001116 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001117 // reject profiles not corresponding to a device currently available
1118 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1119 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1120 continue;
1121 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001122 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1123 != devices.size()) {
1124 continue;
1125 }
1126 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001127 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1128 return curProfile;
1129 }
1130 }
1131 return nullptr;
1132}
1133
Eric Laurentf4e63452017-11-06 19:31:46 +00001134audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001135{
François Gaffiec005e562018-11-06 15:04:49 +01001136 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001137
1138 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1139 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1140 // format, flags, etc. This may result in some discrepancy for functions that utilize
1141 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1142 // and AudioSystem::getOutputSamplingRate().
1143
François Gaffie11d30102018-11-02 16:09:09 +01001144 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001145 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1146 if (stream == AUDIO_STREAM_MUSIC &&
1147 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1148 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1149 }
1150 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001151
François Gaffie11d30102018-11-02 16:09:09 +01001152 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1153 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001154 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001155}
1156
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001157status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1158 const audio_attributes_t *srcAttr,
1159 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001160{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001161 if (srcAttr != NULL) {
1162 if (!isValidAttributes(srcAttr)) {
1163 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1164 __func__,
1165 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1166 srcAttr->tags);
1167 return BAD_VALUE;
1168 }
1169 *dstAttr = *srcAttr;
1170 } else {
1171 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1172 ALOGE("%s: invalid stream type", __func__);
1173 return BAD_VALUE;
1174 }
François Gaffiec005e562018-11-06 15:04:49 +01001175 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001176 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001177
1178 // Only honor audibility enforced when required. The client will be
1179 // forced to reconnect if the forced usage changes.
1180 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001181 dstAttr->flags = static_cast<audio_flags_mask_t>(
1182 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001183 }
1184
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001185 return NO_ERROR;
1186}
1187
Kevin Rocard153f92d2018-12-18 18:33:28 -08001188status_t AudioPolicyManager::getOutputForAttrInt(
1189 audio_attributes_t *resultAttr,
1190 audio_io_handle_t *output,
1191 audio_session_t session,
1192 const audio_attributes_t *attr,
1193 audio_stream_type_t *stream,
1194 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001195 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001196 audio_output_flags_t *flags,
1197 audio_port_handle_t *selectedDeviceId,
1198 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001199 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001200 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001201 bool *isSpatialized,
1202 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001203{
François Gaffiec005e562018-11-06 15:04:49 +01001204 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001205 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001206 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001207 const sp<DeviceDescriptor> requestedDevice =
1208 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1209
Eric Laurent8a1095a2019-11-08 14:44:16 -08001210 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001211 *isSpatialized = false;
1212
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001213 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1214 if (status != NO_ERROR) {
1215 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001216 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001217 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001218 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001219 }
François Gaffiec005e562018-11-06 15:04:49 +01001220 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001221
François Gaffiec005e562018-11-06 15:04:49 +01001222 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1223 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001224
Oscar Azucena873d10f2023-01-12 18:34:42 -08001225 bool usePrimaryOutputFromPolicyMixes = false;
1226
Kevin Rocard153f92d2018-12-18 18:33:28 -08001227 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1228 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1229 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001230 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001231 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1232 .channel_mask = config->channel_mask,
1233 .format = config->format,
1234 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001235 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001236 mAvailableOutputDevices, requestedDevice, primaryMix,
1237 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001238 if (status != OK) {
1239 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001240 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001241
Kevin Rocard153f92d2018-12-18 18:33:28 -08001242 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001243 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1244 && !audio_is_linear_pcm(config->format)) {
1245 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001246 return BAD_VALUE;
1247 }
1248 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001249 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1251 primaryMix->mDeviceAddress,
1252 AUDIO_FORMAT_DEFAULT);
1253 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001254 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001255 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1256 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001257 // if a direct output can be opened to deliver the track's multi-channel content to the
1258 // output rather than being downmixed by the primary output, then use this direct
1259 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1260 // mix.
1261 bool tryDirectForChannelMask = policyDesc != nullptr
1262 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1263 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001264 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001265 audio_io_handle_t newOutput;
1266 status = openDirectOutput(
1267 *stream, session, config,
1268 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001269 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001270 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001271 policyDesc = mOutputs.valueFor(newOutput);
1272 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001273 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001274 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001275 policyDesc = nullptr;
1276 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001277 }
1278 if (policyDesc != nullptr) {
1279 policyDesc->mPolicyMix = primaryMix;
1280 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001281 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1282 : AUDIO_PORT_HANDLE_NONE;
1283 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1284 // Remove direct flag as it is not on a direct output.
1285 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1286 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001287
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001288 ALOGV("getOutputForAttr() returns output %d", *output);
1289 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1290 *outputType = API_OUT_MIX_PLAYBACK;
1291 } else {
1292 *outputType = API_OUTPUT_LEGACY;
1293 }
1294 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001295 } else {
1296 if (policyMixDevice != nullptr) {
1297 ALOGE("%s, try to use primary mix but no output found", __func__);
1298 return INVALID_OPERATION;
1299 }
1300 // Fallback to default engine selection as the selected primary mix device is not
1301 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001302 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001303 }
François Gaffiec005e562018-11-06 15:04:49 +01001304 // Virtual sources must always be dynamicaly or explicitly routed
1305 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1306 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1307 return BAD_VALUE;
1308 }
1309 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1310 // in order to let the choice of the order to future vendor engine
1311 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001312
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001313 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001314 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001315 }
1316
Nadav Barb2f18162018-07-18 13:01:53 +03001317 // Set incall music only if device was explicitly set, and fallback to the device which is
1318 // chosen by the engine if not.
1319 // FIXME: provide a more generic approach which is not device specific and move this back
1320 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001321 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001322 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001323 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001324 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001325 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001326 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001327 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001328 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001329 }
1330 }
1331
François Gaffiec005e562018-11-06 15:04:49 +01001332 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1333 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1334 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001335
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001336 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001337 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001338 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001339 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001340 ALOGV("%s() Using MSD devices %s instead of devices %s",
1341 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001342 } else {
1343 *output = AUDIO_IO_HANDLE_NONE;
1344 }
1345 }
1346 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001347 sp<PreferredMixerAttributesInfo> info = nullptr;
1348 if (outputDevices.size() == 1) {
1349 info = getPreferredMixerAttributesInfo(
1350 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001351 mEngine->getProductStrategyForAttributes(*resultAttr),
1352 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001353 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1354 // and it is currently active.
1355 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001356 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001357 info = nullptr;
1358 }
jiabin220eea12024-05-17 17:55:20 +00001359 if (com::android::media::audioserver::
1360 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1361 if (info != nullptr && info->getUid() == uid &&
1362 info->configMatches(*config) &&
1363 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1364 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1365 [this, &outputDevices](audio_usage_t usage) {
1366 return mOutputs.isUsageActiveOnDevice(
1367 usage, outputDevices[0]); }))) {
1368 // Bit-perfect request is not allowed when the phone mode is not normal or
1369 // there is any higher priority user case active.
1370 return INVALID_OPERATION;
1371 }
1372 }
jiabina84c3d32022-12-02 18:59:55 +00001373 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001374 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001375 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001376 // The client will be active if the client is currently preferred mixer owner and the
1377 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001378 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001379 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001380 && info->getUid() == uid
1381 && *output != AUDIO_IO_HANDLE_NONE
1382 // When bit-perfect output is selected for the preferred mixer attributes owner,
1383 // only need to consider the config matches.
1384 && mOutputs.valueFor(*output)->isConfigurationMatched(
1385 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001386
1387 if (*isBitPerfect) {
1388 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1389 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001390 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001391 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001392 AudioProfileVector profiles;
1393 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1394 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001395 const auto channels = profiles[0]->getChannels();
1396 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1397 config->channel_mask = *channels.begin();
1398 }
1399 const auto sampleRates = profiles[0]->getSampleRates();
1400 if (!sampleRates.empty() &&
1401 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1402 config->sample_rate = *sampleRates.begin();
1403 }
jiabinf1c73972022-04-14 16:28:52 -07001404 config->format = profiles[0]->getFormat();
1405 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001406 return INVALID_OPERATION;
1407 }
Paul McLeanaa981192015-03-21 09:55:15 -07001408
François Gaffiec005e562018-11-06 15:04:49 +01001409 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001410 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001411 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001412 *selectedDeviceId = outputDevice->getId();
1413 break;
1414 }
1415 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001416
Eric Laurent8a1095a2019-11-08 14:44:16 -08001417 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1418 *outputType = API_OUTPUT_TELEPHONY_TX;
1419 } else {
1420 *outputType = API_OUTPUT_LEGACY;
1421 }
1422
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001423 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1424
1425 return NO_ERROR;
1426}
1427
1428status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1429 audio_io_handle_t *output,
1430 audio_session_t session,
1431 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001432 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001433 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001434 audio_output_flags_t *flags,
1435 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001436 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001437 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001438 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001439 bool *isSpatialized,
1440 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001441{
1442 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1443 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1444 return INVALID_OPERATION;
1445 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001446 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001447 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001448 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001449 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001450 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001451 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001452 const sp<DeviceDescriptor> requestedDevice =
1453 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1454
1455 // Prevent from storing invalid requested device id in clients
1456 const audio_port_handle_t sanitizedRequestedPortId =
1457 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1458 *selectedDeviceId = sanitizedRequestedPortId;
1459
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001460 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001461 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001462 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1463 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001464 if (status != NO_ERROR) {
1465 return status;
1466 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001467 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001468 if (secondaryOutputs != nullptr) {
1469 for (auto &secondaryMix : secondaryMixes) {
1470 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1471 if (outputDesc != nullptr &&
1472 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1473 secondaryOutputs->push_back(outputDesc->mIoHandle);
1474 weakSecondaryOutputDescs.push_back(outputDesc);
1475 }
1476 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001477 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001478
Eric Laurent8fc147b2018-07-22 19:13:55 -07001479 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001480 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001481 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001482 };
jiabin4ef93452019-09-10 14:29:54 -07001483 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001484
Eric Laurentc209fe42020-06-05 18:11:23 -07001485 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001486 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001487 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001488 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001489 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001490 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001491 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001492 std::move(weakSecondaryOutputDescs),
1493 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001494 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001495
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001496 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1497 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001498
Eric Laurente83b55d2014-11-14 10:06:21 -08001499 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001500}
1501
Eric Laurentc529cf62020-04-17 18:19:10 -07001502status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1503 audio_session_t session,
1504 const audio_config_t *config,
1505 audio_output_flags_t flags,
1506 const DeviceVector &devices,
1507 audio_io_handle_t *output) {
1508
1509 *output = AUDIO_IO_HANDLE_NONE;
1510
1511 // skip direct output selection if the request can obviously be attached to a mixed output
1512 // and not explicitly requested
1513 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1514 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1515 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1516 return NAME_NOT_FOUND;
1517 }
1518
1519 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1520 // This prevents creating an offloaded track and tearing it down immediately after start
1521 // when audioflinger detects there is an active non offloadable effect.
1522 // FIXME: We should check the audio session here but we do not have it in this context.
1523 // This may prevent offloading in rare situations where effects are left active by apps
1524 // in the background.
1525 sp<IOProfile> profile;
1526 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1527 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1528 profile = getProfileForOutput(
1529 devices, config->sample_rate, config->format, config->channel_mask,
1530 flags, true /* directOnly */);
1531 }
1532
1533 if (profile == nullptr) {
1534 return NAME_NOT_FOUND;
1535 }
1536
1537 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1538 for (size_t i = 0; i < mOutputs.size(); i++) {
1539 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1540 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1541 // reuse direct output if currently open by the same client
1542 // and configured with same parameters
1543 if ((config->sample_rate == desc->getSamplingRate()) &&
1544 (config->format == desc->getFormat()) &&
1545 (config->channel_mask == desc->getChannelMask()) &&
1546 (session == desc->mDirectClientSession)) {
1547 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001548 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001549 mOutputs.keyAt(i), session);
1550 *output = mOutputs.keyAt(i);
1551 return NO_ERROR;
1552 }
1553 }
1554 }
1555
1556 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001557 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1558 return NAME_NOT_FOUND;
1559 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1560 // MMAP gracefully handles lack of an exclusive track resource by mixing
1561 // above the audio framework. For AAudio to know that the limit is reached,
1562 // return an error.
1563 return NAME_NOT_FOUND;
1564 } else {
1565 // Close outputs on this profile, if available, to free resources for this request
1566 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1567 const auto desc = mOutputs.valueAt(i);
1568 if (desc->mProfile == profile) {
1569 closeOutput(desc->mIoHandle);
1570 }
1571 }
1572 }
1573 }
1574
1575 // Unable to close streams to find free resources for this request
1576 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001577 return NAME_NOT_FOUND;
1578 }
1579
Atneya Nairb16666a2023-12-11 20:18:33 -08001580 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001581
Michael Chan6fb34492020-12-08 15:44:49 +11001582 // An MSD patch may be using the only output stream that can service this request. Release
1583 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001584 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001585
Eric Laurentf1f22e72021-07-13 14:04:14 +02001586 status_t status =
1587 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001588
1589 // only accept an output with the requested parameters
1590 if (status != NO_ERROR ||
1591 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1592 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1593 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1594 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1595 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1596 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1597 config->channel_mask, outputDesc->getChannelMask());
1598 if (*output != AUDIO_IO_HANDLE_NONE) {
1599 outputDesc->close();
1600 }
1601 // fall back to mixer output if possible when the direct output could not be open
1602 if (audio_is_linear_pcm(config->format) &&
1603 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1604 return NAME_NOT_FOUND;
1605 }
1606 *output = AUDIO_IO_HANDLE_NONE;
1607 return BAD_VALUE;
1608 }
1609 outputDesc->mDirectOpenCount = 1;
1610 outputDesc->mDirectClientSession = session;
1611
1612 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001613 setOutputDevices(__func__, outputDesc,
1614 devices,
1615 true,
1616 0,
1617 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001618 mPreviousOutputs = mOutputs;
1619 ALOGV("%s returns new direct output %d", __func__, *output);
1620 mpClientInterface->onAudioPortListUpdate();
1621 return NO_ERROR;
1622}
1623
François Gaffie11d30102018-11-02 16:09:09 +01001624audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1625 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001626 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001627 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001628 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001629 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001630 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001631 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001632 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001633{
Andy Hungc88b0642018-04-27 15:42:35 -07001634 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001635
jiabine375d412019-02-26 12:54:53 -08001636 // Discard haptic channel mask when forcing muting haptic channels.
1637 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001638 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1639 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001640
Eric Laurente552edb2014-03-10 17:42:56 -07001641 // open a direct output if required by specified parameters
1642 //force direct flag if offload flag is set: offloading implies a direct output stream
1643 // and all common behaviors are driven by checking only the direct flag
1644 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001645 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1646 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001647 }
Nadav Bar766fb022018-01-07 12:18:03 +02001648 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1649 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001650 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001651
1652 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1653
Eric Laurente83b55d2014-11-14 10:06:21 -08001654 // only allow deep buffering for music stream type
1655 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001656 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001657 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001658 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001659 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1660 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001661 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001662 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001663 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001664 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001665 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001666 audio_is_linear_pcm(config->format) &&
1667 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001668 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001669 AUDIO_OUTPUT_FLAG_DIRECT);
1670 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001671 }
Eric Laurente552edb2014-03-10 17:42:56 -07001672
Carter Hsua3abb402021-10-26 11:11:20 +08001673 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1674 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1675 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1676 }
1677
Eric Laurentf9230d52024-01-26 18:49:09 +01001678 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001679 // was specified and offload or direct playback is not explicitly requested, and there is no
1680 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001681 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001682 if (mSpatializerOutput != nullptr &&
1683 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1684 prefMixerConfigInfo == nullptr &&
1685 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1686 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001687 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001688 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001689 }
1690
Eric Laurentc529cf62020-04-17 18:19:10 -07001691 audio_config_t directConfig = *config;
1692 directConfig.channel_mask = channelMask;
1693 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1694 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001695 return output;
1696 }
1697
Eric Laurent14cbfca2016-03-17 09:42:16 -07001698 // A request for HW A/V sync cannot fallback to a mixed output because time
1699 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001700 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001701 return AUDIO_IO_HANDLE_NONE;
1702 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001703 // A request for Tuner cannot fallback to a mixed output
1704 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1705 return AUDIO_IO_HANDLE_NONE;
1706 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001707
Eric Laurente552edb2014-03-10 17:42:56 -07001708 // ignoring channel mask due to downmix capability in mixer
1709
1710 // open a non direct output
1711
1712 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001713 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001714 // get which output is suitable for the specified stream. The actual
1715 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001716 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001717 if (prefMixerConfigInfo != nullptr) {
1718 for (audio_io_handle_t outputHandle : outputs) {
1719 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1720 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1721 output = outputHandle;
1722 break;
1723 }
1724 }
1725 if (output == AUDIO_IO_HANDLE_NONE) {
1726 // No output open with the preferred profile. Open a new one.
1727 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1728 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1729 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1730 config.format = prefMixerConfigInfo->getConfigBase().format;
1731 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1732 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1733 &config, prefMixerConfigInfo->getFlags());
1734 if (preferredOutput == nullptr) {
1735 ALOGE("%s failed to open output with preferred mixer config", __func__);
1736 } else {
1737 output = preferredOutput->mIoHandle;
1738 }
1739 }
1740 } else {
1741 // at this stage we should ignore the DIRECT flag as no direct output could be
1742 // found earlier
1743 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001744 if (com::android::media::audioserver::
1745 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1746 // If the preferred mixer attributes is null, do not select the bit-perfect output
1747 // unless the bit-perfect output is the only output.
1748 // The bit-perfect output can exist while the passed in preferred mixer attributes
1749 // info is null when it is a high priority client. The high priority clients are
1750 // ringtone or alarm, which is not a bit-perfect use case.
1751 size_t i = 0;
1752 while (i < outputs.size() && outputs.size() > 1) {
1753 auto desc = mOutputs.valueFor(outputs[i]);
1754 // The output descriptor must not be null here.
1755 if (desc->isBitPerfect()) {
1756 outputs.removeItemsAt(i);
1757 } else {
1758 i += 1;
1759 }
1760 }
1761 }
jiabina84c3d32022-12-02 18:59:55 +00001762 output = selectOutput(
1763 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1764 }
Eric Laurente552edb2014-03-10 17:42:56 -07001765 }
François Gaffie11d30102018-11-02 16:09:09 +01001766 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001767 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001768 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001769
Eric Laurente552edb2014-03-10 17:42:56 -07001770 return output;
1771}
1772
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001773sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001774 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1775 mAvailableInputDevices);
1776 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1777}
1778
1779DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1780 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1781 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001782}
1783
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001784const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001786 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1787 if (msdModule != 0) {
1788 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1789 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1790 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1791 const struct audio_port_config *source = &patch->mPatch.sources[j];
1792 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1793 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001794 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001795 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001796 }
1797 }
1798 }
1799 return msdPatches;
1800}
1801
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001802bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1803 ssize_t index = mAudioPatches.indexOfKey(handle);
1804 if (index < 0) {
1805 return false;
1806 }
1807 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1808 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1809 if (msdModule == nullptr) {
1810 return false;
1811 }
1812 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1813 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1814 return true;
1815 }
1816 index = getMsdOutputPatches().indexOfKey(handle);
1817 if (index < 0) {
1818 return false;
1819 }
1820 return true;
1821}
1822
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001823status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1824 const InputProfileCollection &inputProfiles,
1825 const OutputProfileCollection &outputProfiles,
1826 const sp<DeviceDescriptor> &sourceDevice,
1827 const sp<DeviceDescriptor> &sinkDevice,
1828 AudioProfileVector& sourceProfiles,
1829 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001830 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001831 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 return NO_INIT;
1833 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001834 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001835 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 return NO_INIT;
1837 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001838 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1840 inProfile->supportsDevice(sourceDevice)) {
1841 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 }
1843 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001845 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001846 outProfile->supportsDevice(sinkDevice)) {
1847 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001848 }
1849 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001850 return NO_ERROR;
1851}
1852
1853status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1854 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1855 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1856{
Dean Wheatley16809da2022-12-09 14:55:46 +11001857 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1858 static const std::vector<audio_format_t> formatsOrder = {{
1859 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001860 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1861 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001862 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1863 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1864 // preferred).
1865 std::vector<audio_channel_mask_t> masks = {{
1866 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1867 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1868 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1869 // insert index masks (higher counts most preferred) as preferred over position masks
1870 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1871 masks.insert(
1872 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1873 }
1874 return masks;
1875 }();
1876
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001878 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1879 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001880 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001881 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1882 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001883 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 }
1885 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1886 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1887 sinkConfig->format = bestSinkConfig.format;
1888 // For encoded streams force direct flag to prevent downstream mixing.
1889 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1890 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001891 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1892 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001893 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001894 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1895 // raw and IEC61937 framed streams.
1896 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1897 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1898 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1900 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001901 sourceConfig->channel_mask =
1902 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1903 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1904 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001905 sourceConfig->format = bestSinkConfig.format;
1906 // Copy input stream directly without any processing (e.g. resampling).
1907 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1908 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1909 if (hwAvSync) {
1910 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1911 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1912 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1913 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1914 }
1915 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1916 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1917 sinkConfig->config_mask |= config_mask;
1918 sourceConfig->config_mask |= config_mask;
1919 return NO_ERROR;
1920}
1921
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001922PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1923 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001924{
1925 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001926 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1927 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1928 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1929 if (deviceModule == nullptr) {
1930 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1931 return patchBuilder;
1932 }
1933 const InputProfileCollection inputProfiles = msdIsSource ?
1934 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1935 const OutputProfileCollection outputProfiles = msdIsSource ?
1936 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1937
1938 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1939 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1940 device : getMsdAudioOutDevices().itemAt(0);
1941 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1942
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1944 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001945 AudioProfileVector sourceProfiles;
1946 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001947 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1948 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001949 for (auto hwAvSync : { true, false }) {
1950 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1951 sourceProfiles, sinkProfiles) != NO_ERROR) {
1952 continue;
1953 }
1954 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1955 &sinkConfig) == NO_ERROR) {
1956 // Found a matching config. Re-create PatchBuilder with this config.
1957 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1958 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001959 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001960 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001961 " supporting PCM format conversion.", __func__);
1962 return patchBuilder;
1963}
1964
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001965status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001966 DeviceVector devices;
1967 if (outputDevices != nullptr && outputDevices->size() > 0) {
1968 devices.add(*outputDevices);
1969 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001970 // Use media strategy for unspecified output device. This should only
1971 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1972 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001973 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001974 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001975 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001976 }
Michael Chan6fb34492020-12-08 15:44:49 +11001977 std::vector<PatchBuilder> patchesToCreate;
1978 for (auto i = 0u; i < devices.size(); ++i) {
1979 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001980 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001981 }
1982 // Retain only the MSD patches associated with outputDevices request.
1983 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001984 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001985 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1986 auto retainedPatch = false;
1987 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1988 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1989 patchesToRemove.removeItemsAt(i);
1990 retainedPatch = true;
1991 break;
1992 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001993 }
Michael Chan6fb34492020-12-08 15:44:49 +11001994 if (retainedPatch) {
1995 it = patchesToCreate.erase(it);
1996 continue;
1997 }
1998 ++it;
1999 }
2000 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2001 return NO_ERROR;
2002 }
2003 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2004 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002005 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002006 }
Michael Chan6fb34492020-12-08 15:44:49 +11002007 status_t status = NO_ERROR;
2008 for (const auto &p : patchesToCreate) {
2009 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2010 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2011 char message[256];
2012 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2013 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2014 currStatus == NO_ERROR ? "Success" : "Error",
2015 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2016 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2017 if (currStatus == NO_ERROR) {
2018 ALOGD("%s", message);
2019 } else {
2020 ALOGE("%s", message);
2021 if (status == NO_ERROR) {
2022 status = currStatus;
2023 }
2024 }
2025 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002026 return status;
2027}
2028
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002029void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2030 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002031 for (size_t i = 0; i < msdPatches.size(); i++) {
2032 const auto& patch = msdPatches[i];
2033 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2034 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2035 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2036 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2037 releaseAudioPatch(patch->getHandle(), mUidCached);
2038 break;
2039 }
2040 }
2041 }
2042}
2043
Dorin Drimus94d94412022-02-02 09:05:02 +01002044bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002045 DeviceVector devicesToCheck =
2046 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002047 AudioPatchCollection msdPatches = getMsdOutputPatches();
2048 for (size_t i = 0; i < msdPatches.size(); i++) {
2049 const auto& patch = msdPatches[i];
2050 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2051 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2052 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2053 const auto& foundDevice = devicesToCheck.getDevice(
2054 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2055 if (foundDevice != nullptr) {
2056 devicesToCheck.remove(foundDevice);
2057 if (devicesToCheck.isEmpty()) {
2058 return true;
2059 }
2060 }
2061 }
2062 }
2063 }
2064 return false;
2065}
2066
Eric Laurente0720872014-03-11 09:30:41 -07002067audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002068 audio_output_flags_t flags,
2069 audio_format_t format,
2070 audio_channel_mask_t channelMask,
2071 uint32_t samplingRate,
2072 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002073{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002074 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2075 "%s called with format %#x", __func__, format);
2076
jiabinebb6af42020-06-09 17:31:17 -07002077 // Return the output that haptic-generating attached to when 1) session id is specified,
2078 // 2) haptic-generating effect exists for given session id and 3) the output that
2079 // haptic-generating effect attached to is in given outputs.
2080 if (sessionId != AUDIO_SESSION_NONE) {
2081 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2082 sessionId, FX_IID_HAPTICGENERATOR);
2083 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2084 return hapticGeneratingOutput;
2085 }
2086 }
2087
Eric Laurent16c66dd2019-05-01 17:54:10 -07002088 // Flags disqualifying an output: the match must happen before calling selectOutput()
2089 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2090 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2091
2092 // Flags expressing a functional request: must be honored in priority over
2093 // other criteria
2094 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2095 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002096 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2097 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002098 // Flags expressing a performance request: have lower priority than serving
2099 // requested sampling rate or channel mask
2100 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2101 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2102 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2103
2104 const audio_output_flags_t functionalFlags =
2105 (audio_output_flags_t)(flags & kFunctionalFlags);
2106 const audio_output_flags_t performanceFlags =
2107 (audio_output_flags_t)(flags & kPerformanceFlags);
2108
2109 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2110
Eric Laurente552edb2014-03-10 17:42:56 -07002111 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002112 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002113 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002114 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002115 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002116 // with tiebreak preferring the minimum number of extra functional flags
2117 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002118 // 3: the output supporting the exact channel mask
2119 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002120 // 5: the output with the highest sampling rate if the requested sample rate is
2121 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002122 // 6: the output with the highest number of requested performance flags
2123 // 7: the output with the bit depth the closest to the requested one
2124 // 8: the primary output
2125 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002126
Eric Laurent16c66dd2019-05-01 17:54:10 -07002127 // matching criteria values in priority order for best matching output so far
2128 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002129
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002130 const bool hasOrphanHaptic =
2131 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002132 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2133 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2134 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002135
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002136 for (audio_io_handle_t output : outputs) {
2137 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002138 // matching criteria values in priority order for current output
2139 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002140
Eric Laurent16c66dd2019-05-01 17:54:10 -07002141 if (outputDesc->isDuplicated()) {
2142 continue;
2143 }
2144 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2145 continue;
2146 }
Eric Laurent8838a382014-09-08 16:44:28 -07002147
Eric Laurent16c66dd2019-05-01 17:54:10 -07002148 // If haptic channel is specified, use the haptic output if present.
2149 // When using haptic output, same audio format and sample rate are required.
2150 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002151 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002152 // skip if haptic channel specified but output does not support it, or output support haptic
2153 // but there is no haptic channel requested AND no orphan haptic effect exist
2154 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2155 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002156 continue;
2157 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002158 // In the case of audio-coupled-haptic playback, there is no format conversion and
2159 // resampling in the framework, same format/channel/sampleRate for client and the output
2160 // thread is required. In the case of HapticGenerator effect, do not require format
2161 // matching.
2162 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2163 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002164 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002165 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002166 }
2167
2168 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002169 const int matchingFunctionalFlags =
2170 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2171 const int totalFunctionalFlags =
2172 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2173 // Prefer matching functional flags, but subtract unnecessary functional flags.
2174 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002175
2176 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002177 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2178 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002179 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2180 channelCount <= outputChannelCount) {
2181 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002182 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2183 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002184 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002185 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002186 currentMatchCriteria[3] = outputChannelCount;
2187 }
2188
2189 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002190 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002191 int diff; // avoid unsigned integer overflow.
2192 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2193
2194 // prefer the closest output sampling rate greater than or equal to target
2195 // if none exists, prefer the closest output sampling rate less than target.
2196 //
2197 // criteria is offset to make non-negative.
2198 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002199 }
2200
2201 // performance flags match
2202 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2203
2204 // format match
2205 if (format != AUDIO_FORMAT_INVALID) {
2206 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002207 PolicyAudioPort::kFormatDistanceMax -
2208 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002209 }
2210
2211 // primary output match
2212 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2213
2214 // compare match criteria by priority then value
2215 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2216 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2217 bestMatchCriteria = currentMatchCriteria;
2218 bestOutput = output;
2219
2220 std::stringstream result;
2221 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2222 std::ostream_iterator<int>(result, " "));
2223 ALOGV("%s new bestOutput %d criteria %s",
2224 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002225 }
2226 }
2227
Eric Laurent16c66dd2019-05-01 17:54:10 -07002228 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002229}
2230
Eric Laurent8fc147b2018-07-22 19:13:55 -07002231status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002232{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002233 ALOGV("%s portId %d", __FUNCTION__, portId);
2234
2235 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2236 if (outputDesc == 0) {
2237 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002238 return BAD_VALUE;
2239 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002240 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002241
Eric Laurent8fc147b2018-07-22 19:13:55 -07002242 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002243 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002244
jiabin220eea12024-05-17 17:55:20 +00002245 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2246 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2247 && outputDesc->isBitPerfect()) {
2248 // Usually, APM selects bit-perfect output for high priority use cases only when
2249 // bit-perfect output is the only output that can be routed to the selected device.
2250 // However, here is no need to play high priority use cases such as ringtone and alarm
2251 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2252 // can attach to new output.
2253 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2254 __func__, client->stream());
2255 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2256 return DEAD_OBJECT;
2257 }
2258
Eric Laurent733ce942017-12-07 12:18:25 -08002259 status_t status = outputDesc->start();
2260 if (status != NO_ERROR) {
2261 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002262 }
2263
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 uint32_t delayMs;
2265 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002266
2267 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002268 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002269 if (status == DEAD_OBJECT) {
2270 sp<SwAudioOutputDescriptor> desc =
2271 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2272 if (desc == nullptr) {
2273 // This is not common, it may indicate something wrong with the HAL.
2274 ALOGE("%s unable to open output with default config", __func__);
2275 return status;
2276 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002277 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002278 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002279 }
jiabina84c3d32022-12-02 18:59:55 +00002280
2281 // If the client is the first one active on preferred mixer parameters, reopen the output
2282 // if the current mixer parameters doesn't match the preferred one.
2283 if (outputDesc->devices().size() == 1) {
2284 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2285 outputDesc->devices()[0]->getId(), client->strategy());
2286 if (info != nullptr && info->getUid() == client->uid()) {
2287 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2288 info->getConfigBase(), info->getFlags())) {
2289 stopSource(outputDesc, client);
2290 outputDesc->stop();
2291 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2292 config.channel_mask = info->getConfigBase().channel_mask;
2293 config.sample_rate = info->getConfigBase().sample_rate;
2294 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002295 sp<SwAudioOutputDescriptor> desc =
2296 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2297 if (desc == nullptr) {
2298 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002299 }
jiabin220eea12024-05-17 17:55:20 +00002300 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002301 // Intentionally return error to let the client side resending request for
2302 // creating and starting.
2303 return DEAD_OBJECT;
2304 }
2305 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002306 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002307 // If it is first bit-perfect client, reroute all clients that will be routed to
2308 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2309 PortHandleVector clientsToInvalidate;
2310 for (size_t i = 0; i < mOutputs.size(); i++) {
2311 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002312 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002313 continue;
2314 }
2315 for (const auto& c : mOutputs[i]->getClientIterable()) {
2316 clientsToInvalidate.push_back(c->portId());
2317 }
2318 }
2319 if (!clientsToInvalidate.empty()) {
2320 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2321 __func__);
2322 mpClientInterface->invalidateTracks(clientsToInvalidate);
2323 }
2324 }
jiabina84c3d32022-12-02 18:59:55 +00002325 }
2326 }
2327
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002328 if (client->hasPreferredDevice()) {
2329 // playback activity with preferred device impacts routing occurred, inform upper layers
2330 mpClientInterface->onRoutingUpdated();
2331 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002332 if (delayMs != 0) {
2333 usleep(delayMs * 1000);
2334 }
2335
jiabin220eea12024-05-17 17:55:20 +00002336 if (status == NO_ERROR &&
2337 outputDesc->mPreferredAttrInfo != nullptr &&
2338 outputDesc->isBitPerfect() &&
2339 com::android::media::audioserver::
2340 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2341 // A new client is started on bit-perfect output, update all clients internal mute.
2342 updateClientsInternalMute(outputDesc);
2343 }
2344
Eric Laurentc75307b2015-03-17 15:29:32 -07002345 return status;
2346}
2347
Eric Laurent96d1dda2022-03-14 17:14:19 +01002348bool AudioPolicyManager::isLeUnicastActive() const {
2349 if (isInCall()) {
2350 return true;
2351 }
2352 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2353}
2354
2355bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2356 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2357 return false;
2358 }
2359 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2360 ALOGV("%s active %d", __func__, active);
2361 return active;
2362}
2363
Eric Laurent97ac8712018-07-27 18:59:02 -07002364status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2365 const sp<TrackClientDescriptor>& client,
2366 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002367{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002368 // cannot start playback of STREAM_TTS if any other output is being used
2369 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002370
2371 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002372 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002373 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002374 auto clientStrategy = client->strategy();
2375 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002376 if (stream == AUDIO_STREAM_TTS) {
2377 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002378 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002379 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002380 return INVALID_OPERATION;
2381 } else {
2382 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2383 }
2384 } else {
2385 // some playback other than beacon starts
2386 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2387 }
2388
Eric Laurent77305a62016-07-25 16:39:22 -07002389 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002390 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002391 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002392
François Gaffie11d30102018-11-02 16:09:09 +01002393 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002394 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002395 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002396 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002397 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002398 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002399 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002400 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002401 } else {
2402 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002403 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002404 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2405 AUDIO_FORMAT_DEFAULT);
2406 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2407 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002408 }
2409
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002410 // requiresMuteCheck is false when we can bypass mute strategy.
2411 // It covers a common case when there is no materially active audio
2412 // and muting would result in unnecessary delay and dropped audio.
2413 const uint32_t outputLatencyMs = outputDesc->latency();
2414 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002415 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002416
Eric Laurente552edb2014-03-10 17:42:56 -07002417 // increment usage count for this stream on the requested output:
2418 // NOTE that the usage count is the same for duplicated output and hardware output which is
2419 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002420 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002421
2422 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002423 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002424 // Preferred device may be exclusive, use only if no other active clients on this output
2425 devices = DeviceVector(
2426 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2427 } else {
2428 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2429 }
François Gaffie11d30102018-11-02 16:09:09 +01002430 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002431 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002432 }
2433 }
Eric Laurente552edb2014-03-10 17:42:56 -07002434
François Gaffiec005e562018-11-06 15:04:49 +01002435 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002436 selectOutputForMusicEffects();
2437 }
2438
François Gaffie1c878552018-11-22 16:53:21 +01002439 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002440 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002441 if (devices.isEmpty()) {
2442 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002443 }
François Gaffiec005e562018-11-06 15:04:49 +01002444 bool shouldWait =
2445 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2446 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2447 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002448 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002449 const bool needToCloseBitPerfectOutput =
2450 (com::android::media::audioserver::
2451 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2452 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2453 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002454 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002455 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002456 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002457 // An output has a shared device if
2458 // - managed by the same hw module
2459 // - supports the currently selected device
2460 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002461 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002462
Eric Laurent77305a62016-07-25 16:39:22 -07002463 // force a device change if any other output is:
2464 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002465 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002466 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002467 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002468 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002469 // change the device currently selected by the other output.
2470 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002471 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002472 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002473 force = true;
2474 }
2475 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002476 // a notification so that audio focus effect can propagate, or that a mute/unmute
2477 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002478 const uint32_t latencyMs = desc->latency();
2479 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2480
2481 if (shouldWait && isActive && (waitMs < latencyMs)) {
2482 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002483 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002484
2485 // Require mute check if another output is on a shared device
2486 // and currently active to have proper drain and avoid pops.
2487 // Note restoring AudioTracks onto this output needs to invoke
2488 // a volume ramp if there is no mute.
2489 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002490
2491 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2492 outputsToReopen.push_back(desc);
2493 }
Eric Laurente552edb2014-03-10 17:42:56 -07002494 }
2495 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002496
jiabin220eea12024-05-17 17:55:20 +00002497 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002498 // If the output is open with preferred mixer attributes, but the routed device is
2499 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2500 // changed.
2501 return DEAD_OBJECT;
2502 }
jiabin220eea12024-05-17 17:55:20 +00002503 for (auto& outputToReopen : outputsToReopen) {
2504 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2505 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002506 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302507 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2508 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002509
Eric Laurente552edb2014-03-10 17:42:56 -07002510 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002511 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002512 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002513 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002514 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002515 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002516 outputDesc->useHwGain() /*force*/)) {
2517 // request AudioService to reinitialize the volume curves asynchronously
2518 ALOGE("checkAndSetVolume failed, requesting volume range init");
2519 mpClientInterface->onVolumeRangeInitRequest();
2520 };
Eric Laurente552edb2014-03-10 17:42:56 -07002521
2522 // update the outputs if starting an output with a stream that can affect notification
2523 // routing
2524 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002525
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002526 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002527 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002528 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002529 }
Eric Laurentdc462862016-07-19 12:29:53 -07002530
2531 if (waitMs > muteWaitMs) {
2532 *delayMs = waitMs - muteWaitMs;
2533 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002534
2535 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2536 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2537 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2538 // change occurs after the MixerThread starts and causes a stream volume
2539 // glitch.
2540 //
2541 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002542 }
Eric Laurentdc462862016-07-19 12:29:53 -07002543
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002544 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002545 mEngine->getForceUse(
2546 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002547 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002548 }
2549
Eric Laurent97ac8712018-07-27 18:59:02 -07002550 // Automatically enable the remote submix input when output is started on a re routing mix
2551 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002552 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2553 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2555 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2556 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002557 "remote-submix",
2558 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002559 }
2560
Eric Laurent96d1dda2022-03-14 17:14:19 +01002561 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2562
Eric Laurente552edb2014-03-10 17:42:56 -07002563 return NO_ERROR;
2564}
2565
Eric Laurent96d1dda2022-03-14 17:14:19 +01002566void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2567 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2568 bool isUnicastActive = isLeUnicastActive();
2569
2570 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002571 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002572 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2573 for (size_t i = 0; i < mOutputs.size(); i++) {
2574 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2575 if (desc != ignoredOutput && desc->isActive()
2576 && ((isUnicastActive &&
2577 !desc->devices().
2578 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2579 || (wasUnicastActive &&
2580 !desc->devices().getDevicesFromTypes(
2581 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2582 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2583 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002584 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002585 // If the device is using preferred mixer attributes, the output need to reopen
2586 // with default configuration when the new selected devices are different from
2587 // current routing devices.
2588 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2589 continue;
2590 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302591 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002592 // re-apply device specific volume if not done by setOutputDevice()
2593 if (!force) {
2594 applyStreamVolumes(desc, newDevices.types(), delayMs);
2595 }
2596 }
2597 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002598 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002599 }
2600}
2601
Eric Laurent8fc147b2018-07-22 19:13:55 -07002602status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002603{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002604 ALOGV("%s portId %d", __FUNCTION__, portId);
2605
2606 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2607 if (outputDesc == 0) {
2608 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002609 return BAD_VALUE;
2610 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002611 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002612
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002613 if (client->hasPreferredDevice(true)) {
2614 // playback activity with preferred device impacts routing occurred, inform upper layers
2615 mpClientInterface->onRoutingUpdated();
2616 }
2617
Eric Laurent97ac8712018-07-27 18:59:02 -07002618 ALOGV("stopOutput() output %d, stream %d, session %d",
2619 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002620
Eric Laurent97ac8712018-07-27 18:59:02 -07002621 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002622
Eric Laurent733ce942017-12-07 12:18:25 -08002623 if (status == NO_ERROR ) {
2624 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002625 } else {
2626 return status;
2627 }
2628
2629 if (outputDesc->devices().size() == 1) {
2630 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2631 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002632 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002633 if (info != nullptr && info->getUid() == client->uid()) {
2634 info->decreaseActiveClient();
2635 if (info->getActiveClientCount() == 0) {
2636 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002637 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002638 }
2639 }
jiabin220eea12024-05-17 17:55:20 +00002640 if (com::android::media::audioserver::
2641 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2642 !outputReopened && outputDesc->isBitPerfect()) {
2643 // Only need to update the clients' internal mute when the output is bit-perfect and it
2644 // is not reopened.
2645 updateClientsInternalMute(outputDesc);
2646 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002647 }
2648 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002649}
2650
Eric Laurent97ac8712018-07-27 18:59:02 -07002651status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2652 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002653{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002654 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002655 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002656 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002657 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002658
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002659 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2660
François Gaffie1c878552018-11-22 16:53:21 +01002661 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2662 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002663 // Automatically disable the remote submix input when output is stopped on a
2664 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002665 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002666 if (isSingleDeviceType(
2667 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002668 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002669 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002670 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2671 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002672 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002673 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002674 }
2675 }
2676 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002677 if (client->hasPreferredDevice(true) &&
2678 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002679 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002680 forceDeviceUpdate = true;
2681 }
2682
Eric Laurente552edb2014-03-10 17:42:56 -07002683 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002684 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002685
Eric Laurente552edb2014-03-10 17:42:56 -07002686 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002687 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002688 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002689 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002690
2691 // If the routing does not change, if an output is routed on a device using HwGain
2692 // (aka setAudioPortConfig) and there are still active clients following different
2693 // volume group(s), force reapply volume
2694 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2695 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2696
Eric Laurente552edb2014-03-10 17:42:56 -07002697 // delay the device switch by twice the latency because stopOutput() is executed when
2698 // the track stop() command is received and at that time the audio track buffer can
2699 // still contain data that needs to be drained. The latency only covers the audio HAL
2700 // and kernel buffers. Also the latency does not always include additional delay in the
2701 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302702 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002703 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002704
2705 // force restoring the device selection on other active outputs if it differs from the
2706 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002707 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002708 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002709 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002710 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002711 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002712 desc->isActive() &&
2713 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002714 (newDevices != desc->devices())) {
2715 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2716 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002717
jiabin220eea12024-05-17 17:55:20 +00002718 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002719 // If the device is using preferred mixer attributes, the output need to
2720 // reopen with default configuration when the new selected devices are
2721 // different from current routing devices.
2722 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2723 continue;
2724 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302725 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002726
Eric Laurent57de36c2016-09-28 16:59:11 -07002727 // re-apply device specific volume if not done by setOutputDevice()
2728 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002729 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002730 }
Eric Laurente552edb2014-03-10 17:42:56 -07002731 }
2732 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002733 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002734 // update the outputs if stopping one with a stream that can affect notification routing
2735 handleNotificationRoutingForStream(stream);
2736 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002737
2738 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2739 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002740 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002741 }
2742
François Gaffiec005e562018-11-06 15:04:49 +01002743 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002744 selectOutputForMusicEffects();
2745 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002746
2747 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2748
Eric Laurente552edb2014-03-10 17:42:56 -07002749 return NO_ERROR;
2750 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002751 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002752 return INVALID_OPERATION;
2753 }
2754}
2755
jiabinbce0c1d2020-10-05 11:20:18 -07002756bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002757{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002758 ALOGV("%s portId %d", __FUNCTION__, portId);
2759
2760 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2761 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002762 // If an output descriptor is closed due to a device routing change,
2763 // then there are race conditions with releaseOutput from tracks
2764 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2765 // destroyed shortly thereafter.
2766 //
2767 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002768 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002769 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002770 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002771
2772 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002773
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302774 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2775 if (outputDesc->isClientActive(client)) {
2776 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2777 stopOutput(portId);
2778 }
2779
Eric Laurent8fc147b2018-07-22 19:13:55 -07002780 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2781 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002782 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002783 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002784 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002785 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002786 if (--outputDesc->mDirectOpenCount == 0) {
2787 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002788 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002789 }
2790 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302791
Andy Hung39efb7a2018-09-26 15:39:28 -07002792 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002793 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2794 // The output is pending reopened to query dynamic profiles and
2795 // there is no active clients
2796 closeOutput(outputDesc->mIoHandle);
2797 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2798 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2799 if (newOutputDesc == nullptr) {
2800 ALOGE("%s failed to open output", __func__);
2801 }
2802 return true;
2803 }
2804 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002805}
2806
Eric Laurentcaf7f482014-11-25 17:50:47 -08002807status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2808 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002809 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002810 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002811 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002812 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002813 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002814 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002815 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002816 audio_port_handle_t *portId,
2817 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002818{
François Gaffiec005e562018-11-06 15:04:49 +01002819 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002820 "flags %#x attributes=%s requested device ID %d",
2821 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2822 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002823
Eric Laurentad2e7b92017-09-14 20:06:42 -07002824 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002825 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002826 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002827 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002828 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002829 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002830 sp<RecordClientDescriptor> clientDesc;
2831 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002832 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002833 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002834
2835 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2836 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2837 return INVALID_OPERATION;
2838 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002839
Francois Gaffie716e1432019-01-14 16:58:59 +01002840 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2841 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002842 }
2843
Paul McLean466dc8e2015-04-17 13:15:36 -06002844 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002845 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002846 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002847
Eric Laurentad2e7b92017-09-14 20:06:42 -07002848 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2849 // possible
2850 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2851 *input != AUDIO_IO_HANDLE_NONE) {
2852 ssize_t index = mInputs.indexOfKey(*input);
2853 if (index < 0) {
2854 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2855 status = BAD_VALUE;
2856 goto error;
2857 }
2858 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002859 RecordClientVector clients = inputDesc->getClientsForSession(session);
2860 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002861 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2862 status = BAD_VALUE;
2863 goto error;
2864 }
2865 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2866 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002867 // corresponds to a new client and is only permitted from the same UID.
2868 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002869 if (clients.size() > 1) {
2870 for (const auto& client : clients) {
2871 // The client map is ordered by key values (portId) and portIds are allocated
2872 // incrementaly. So the first client in this list is the one opened by audio flinger
2873 // when the mmap stream is created and should be ignored as it does not correspond
2874 // to an actual client
2875 if (client == *clients.cbegin()) {
2876 continue;
2877 }
2878 if (uid != client->uid() && !client->isSilenced()) {
2879 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2880 uid, client->portId(), client->uid());
2881 status = INVALID_OPERATION;
2882 goto error;
2883 }
Eric Laurent331679c2018-04-16 17:03:16 -07002884 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002885 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002886 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002887 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002888
Eric Laurentfecbceb2021-02-09 14:46:43 +01002889 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002890 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002891 }
2892
2893 *input = AUDIO_IO_HANDLE_NONE;
2894 *inputType = API_INPUT_INVALID;
2895
Francois Gaffie716e1432019-01-14 16:58:59 +01002896 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002897 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002898 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002899 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002900 ALOGW("%s could not find input mix for attr %s",
2901 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002902 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002903 }
jiabinc1de2df2019-05-07 14:26:40 -07002904 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2905 String8(attr->tags + strlen("addr=")),
2906 AUDIO_FORMAT_DEFAULT);
2907 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002908 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002909 __func__, attributes.source, attributes.tags);
2910 status = BAD_VALUE;
2911 goto error;
2912 }
2913
Kevin Rocard25f9b052019-02-27 15:08:54 -08002914 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2915 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2916 } else {
2917 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2918 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002919 if (virtualDeviceId) {
2920 *virtualDeviceId = policyMix->mVirtualDeviceId;
2921 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002922 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002923 if (explicitRoutingDevice != nullptr) {
2924 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002925 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002926 // Prevent from storing invalid requested device id in clients
2927 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002928 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002929 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2930 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002931 }
François Gaffie11d30102018-11-02 16:09:09 +01002932 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002933 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002934 status = BAD_VALUE;
2935 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002936 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002937 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2938 *inputType = API_INPUT_MIX_CAPTURE;
2939 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002940 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2941 // there is an external policy, but this input is attached to a mix of recorders,
2942 // meaning it receives audio injected into the framework, so the recorder doesn't
2943 // know about it and is therefore considered "legacy"
2944 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002945
2946 if (virtualDeviceId) {
2947 *virtualDeviceId = policyMix->mVirtualDeviceId;
2948 }
François Gaffie11d30102018-11-02 16:09:09 +01002949 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002950 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002951 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002952 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002953 } else {
2954 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002955 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002956
Eric Laurent599c7582015-12-07 18:05:55 -08002957 }
2958
François Gaffiec005e562018-11-06 15:04:49 +01002959 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002960 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002961 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002962 AudioProfileVector profiles;
2963 status_t ret = getProfilesForDevices(
2964 DeviceVector(device), profiles, flags, true /*isInput*/);
2965 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002966 const auto channels = profiles[0]->getChannels();
2967 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2968 config->channel_mask = *channels.begin();
2969 }
2970 const auto sampleRates = profiles[0]->getSampleRates();
2971 if (!sampleRates.empty() &&
2972 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2973 config->sample_rate = *sampleRates.begin();
2974 }
jiabinf1c73972022-04-14 16:28:52 -07002975 config->format = profiles[0]->getFormat();
2976 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002977 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002978 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002979
Marvin Ramine5a122d2023-12-07 13:57:59 +01002980
2981 if (policyMix != nullptr && virtualDeviceId != nullptr) {
2982 *virtualDeviceId = policyMix->mVirtualDeviceId;
2983 }
2984
Eric Laurent8f42ea12018-08-08 09:08:25 -07002985exit:
2986
François Gaffiec005e562018-11-06 15:04:49 +01002987 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2988 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002989
Francois Gaffie716e1432019-01-14 16:58:59 +01002990 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002991 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002992 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002993
Mikhail Naganov2996f672019-04-18 12:29:59 -07002994 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002995 requestedDeviceId, attributes.source, flags,
2996 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002997 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002998 // Move (if found) effect for the client session to its input
2999 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003000 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003001
3002 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3003 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003004
Eric Laurent599c7582015-12-07 18:05:55 -08003005 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003006
3007error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003008 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003009}
3010
3011
François Gaffie11d30102018-11-02 16:09:09 +01003012audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003013 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003014 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003015 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003016 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003017 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003018{
3019 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003020 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003021 bool isSoundTrigger = false;
3022
François Gaffiec005e562018-11-06 15:04:49 +01003023 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003024 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3025 if (index >= 0) {
3026 input = mSoundTriggerSessions.valueFor(session);
3027 isSoundTrigger = true;
3028 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3029 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3030 } else {
3031 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003032 }
François Gaffiec005e562018-11-06 15:04:49 +01003033 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003034 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003035 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003036 }
3037
Carter Hsua3abb402021-10-26 11:11:20 +08003038 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3039 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3040 }
3041
Eric Laurentfe231122017-11-17 17:48:06 -08003042 // sampling rate and flags may be updated by getInputProfile
3043 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3044 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003045 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003046 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003047 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003048 // find a compatible input profile (not necessarily identical in parameters)
3049 sp<IOProfile> profile = getInputProfile(
3050 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3051 if (profile == nullptr) {
3052 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003053 }
jiabin2fd710d2022-05-02 23:20:22 +00003054
Glenn Kasten05ddca52016-02-11 08:17:12 -08003055 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003056 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003057 if (samplingRate == 0) {
3058 samplingRate = profileSamplingRate;
3059 }
Eric Laurente552edb2014-03-10 17:42:56 -07003060
Eric Laurent322b4d22015-04-03 15:57:54 -07003061 if (profile->getModuleHandle() == 0) {
3062 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003063 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003064 }
3065
Eric Laurentec376dc2021-04-08 20:41:22 +02003066 // Reuse an already opened input if a client with the same session ID already exists
3067 // on that input
3068 for (size_t i = 0; i < mInputs.size(); i++) {
3069 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3070 if (desc->mProfile != profile) {
3071 continue;
3072 }
3073 RecordClientVector clients = desc->clientsList();
3074 for (const auto &client : clients) {
3075 if (session == client->session()) {
3076 return desc->mIoHandle;
3077 }
3078 }
3079 }
3080
Eric Laurent3974e3b2017-12-07 17:58:43 -08003081 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003082 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003083 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003084 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003085 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003086 continue;
3087 }
3088 // if sound trigger, reuse input if used by other sound trigger on same session
3089 // else
3090 // reuse input if active client app is not in IDLE state
3091 //
3092 RecordClientVector clients = desc->clientsList();
3093 bool doClose = false;
3094 for (const auto& client : clients) {
3095 if (isSoundTrigger != client->isSoundTrigger()) {
3096 continue;
3097 }
3098 if (client->isSoundTrigger()) {
3099 if (session == client->session()) {
3100 return desc->mIoHandle;
3101 }
3102 continue;
3103 }
3104 if (client->active() && client->appState() != APP_STATE_IDLE) {
3105 return desc->mIoHandle;
3106 }
3107 doClose = true;
3108 }
3109 if (doClose) {
3110 closeInput(desc->mIoHandle);
3111 } else {
3112 i++;
3113 }
3114 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003115 }
3116
Eric Laurentfe231122017-11-17 17:48:06 -08003117 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003118
Eric Laurentfe231122017-11-17 17:48:06 -08003119 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3120 lConfig.sample_rate = profileSamplingRate;
3121 lConfig.channel_mask = profileChannelMask;
3122 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003123
François Gaffie11d30102018-11-02 16:09:09 +01003124 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003125
3126 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003127 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003128 (profileSamplingRate != lConfig.sample_rate) ||
3129 !audio_formats_match(profileFormat, lConfig.format) ||
3130 (profileChannelMask != lConfig.channel_mask)) {
3131 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003132 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003133 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003134 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003135 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003136 }
Eric Laurent599c7582015-12-07 18:05:55 -08003137 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003138 }
3139
Eric Laurentc722f302014-12-10 11:21:49 -08003140 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003141
Eric Laurent599c7582015-12-07 18:05:55 -08003142 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003143 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003144
Eric Laurent599c7582015-12-07 18:05:55 -08003145 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003146}
3147
Eric Laurent4eb58f12018-12-07 16:41:02 -08003148status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003149{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003150 ALOGV("%s portId %d", __FUNCTION__, portId);
3151
3152 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3153 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003154 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003155 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003156 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003157 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003158 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003159 if (client->active()) {
3160 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3161 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003162 }
3163
Eric Laurent8f42ea12018-08-08 09:08:25 -07003164 audio_session_t session = client->session();
3165
Eric Laurent4eb58f12018-12-07 16:41:02 -08003166 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003167
Eric Laurent4eb58f12018-12-07 16:41:02 -08003168 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003169
Eric Laurent4eb58f12018-12-07 16:41:02 -08003170 status_t status = inputDesc->start();
3171 if (status != NO_ERROR) {
3172 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003173 }
Eric Laurente552edb2014-03-10 17:42:56 -07003174
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003175 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003176 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003177 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003178
Eric Laurent8f42ea12018-08-08 09:08:25 -07003179 // indicate active capture to sound trigger service if starting capture from a mic on
3180 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003181 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003182 if (device != nullptr) {
3183 status = setInputDevice(input, device, true /* force */);
3184 } else {
3185 ALOGW("%s no new input device can be found for descriptor %d",
3186 __FUNCTION__, inputDesc->getId());
3187 status = BAD_VALUE;
3188 }
Eric Laurente552edb2014-03-10 17:42:56 -07003189
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003190 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003191 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003192 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003193 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003194 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3195 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003196 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003197 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003198
François Gaffie11d30102018-11-02 16:09:09 +01003199 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3200 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003201 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003202 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003203 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003204
Eric Laurent8f42ea12018-08-08 09:08:25 -07003205 // automatically enable the remote submix output when input is started if not
3206 // used by a policy mix of type MIX_TYPE_RECORDERS
3207 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003208 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003209 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003210 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003211 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003212 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3213 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003214 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003215 if (address != "") {
3216 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3217 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003218 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003219 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003220 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003221 } else if (status != NO_ERROR) {
3222 // Restore client activity state.
3223 inputDesc->setClientActive(client, false);
3224 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003225 }
3226
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003227 ALOGV("%s input %d source = %d status = %d exit",
3228 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003229
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003230 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003231}
3232
Eric Laurent8fc147b2018-07-22 19:13:55 -07003233status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003234{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003235 ALOGV("%s portId %d", __FUNCTION__, portId);
3236
3237 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3238 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003239 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003240 return BAD_VALUE;
3241 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003242 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003243 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003244 if (!client->active()) {
3245 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003246 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003247 }
Carter Hsue6139d52021-07-08 10:30:20 +08003248 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003249 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003250
Eric Laurent8f42ea12018-08-08 09:08:25 -07003251 inputDesc->stop();
3252 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003253 auto current_source = inputDesc->source();
3254 setInputDevice(input, getNewInputDevice(inputDesc),
3255 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003256 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003257 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003258 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003259 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003260 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3261 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003262 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003263 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003264
3265 // automatically disable the remote submix output when input is stopped if not
3266 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003267 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003268 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003269 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003270 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003271 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3272 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003273 }
3274 if (address != "") {
3275 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3276 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003277 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003278 }
3279 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003280 resetInputDevice(input);
3281
3282 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3283 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003284 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3285 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003286 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003287 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003288 }
3289 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003290 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003291 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003292}
3293
Eric Laurent8fc147b2018-07-22 19:13:55 -07003294void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003295{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003296 ALOGV("%s portId %d", __FUNCTION__, portId);
3297
3298 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3299 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003300 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003301 return;
3302 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003303 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003304 audio_io_handle_t input = inputDesc->mIoHandle;
3305
Eric Laurent8f42ea12018-08-08 09:08:25 -07003306 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003307
Andy Hung39efb7a2018-09-26 15:39:28 -07003308 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003309
3310 // If no more clients are present in this session, park effects to an orphan chain
3311 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3312 if (clientsOnSession.size() == 0) {
3313 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3314 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003315 if (inputDesc->getClientCount() > 0) {
3316 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003317 return;
3318 }
3319
Eric Laurent05b90f82014-08-27 15:32:29 -07003320 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003321 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003322 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003323}
3324
Eric Laurent8f42ea12018-08-08 09:08:25 -07003325void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003326{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003327 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003328
3329 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003330 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003331 }
3332}
3333
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3335{
3336 stopInput(portId);
3337 releaseInput(portId);
3338}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003339
Eric Laurent0dd51852019-04-19 18:18:58 -07003340void AudioPolicyManager::checkCloseInputs() {
3341 // After connecting or disconnecting an input device, close input if:
3342 // - it has no client (was just opened to check profile) OR
3343 // - none of its supported devices are connected anymore OR
3344 // - one of its clients cannot be routed to one of its supported
3345 // devices anymore. Otherwise update device selection
3346 std::vector<audio_io_handle_t> inputsToClose;
3347 for (size_t i = 0; i < mInputs.size(); i++) {
3348 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3349 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003350 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003351 inputsToClose.push_back(mInputs.keyAt(i));
3352 } else {
3353 bool close = false;
3354 for (const auto& client : input->clientsList()) {
3355 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003356 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3357 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003358 if (!input->supportedDevices().contains(device)) {
3359 close = true;
3360 break;
3361 }
3362 }
3363 if (close) {
3364 inputsToClose.push_back(mInputs.keyAt(i));
3365 } else {
3366 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3367 }
3368 }
3369 }
3370
3371 for (const audio_io_handle_t handle : inputsToClose) {
3372 ALOGV("%s closing input %d", __func__, handle);
3373 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003374 }
Eric Laurentd4692962014-05-05 18:13:44 -07003375}
3376
Vlad Popa87e0e582024-05-20 18:49:20 -07003377status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3378 const char *address __unused,
3379 bool enabled,
3380 audio_stream_type_t streamToDriveAbs)
3381{
3382 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3383 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3384 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3385 toString(streamToDriveAbs).c_str());
3386 return BAD_VALUE;
3387 }
3388
3389 if (enabled) {
3390 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3391 } else {
3392 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3393 }
3394
3395 return NO_ERROR;
3396}
3397
François Gaffie251c7f02018-11-07 10:41:08 +01003398void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003399{
3400 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003401 if (indexMin < 0 || indexMax < 0) {
3402 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3403 return;
3404 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003405 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003406
3407 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003408 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3409 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003410 continue;
3411 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003412 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003413 }
Eric Laurente552edb2014-03-10 17:42:56 -07003414}
3415
Eric Laurente0720872014-03-11 09:30:41 -07003416status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003417 int index,
3418 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003419{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003420 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003421 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3422 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3423 return NO_ERROR;
3424 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003425 ALOGV("%s: stream %s attributes=%s", __func__,
3426 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003427 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003428}
3429
Eric Laurente0720872014-03-11 09:30:41 -07003430status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003431 int *index,
3432 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003433{
François Gaffiec005e562018-11-06 15:04:49 +01003434 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3435 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003436 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003437 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003438 deviceTypes = mEngine->getOutputDevicesForStream(
3439 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003440 }
jiabin9a3361e2019-10-01 09:38:30 -07003441 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003442}
3443
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003444status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003445 int index,
3446 audio_devices_t device)
3447{
3448 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003449 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3450 if (group == VOLUME_GROUP_NONE) {
3451 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003452 return BAD_VALUE;
3453 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003454 ALOGV("%s: group %d matching with %s index %d",
3455 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003456 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003457 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003458 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003459 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3460 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3461 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3462 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003463 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3464
3465 status = setVolumeCurveIndex(index, device, curves);
3466 if (status != NO_ERROR) {
3467 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3468 return status;
3469 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003470
jiabin9a3361e2019-10-01 09:38:30 -07003471 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003472 auto curCurvAttrs = curves.getAttributes();
3473 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3474 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003475 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003476 } else if (!curves.getStreamTypes().empty()) {
3477 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003478 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003479 } else {
3480 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3481 return BAD_VALUE;
3482 }
jiabin9a3361e2019-10-01 09:38:30 -07003483 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3484 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003485
François Gaffiecfe17322018-11-07 13:41:29 +01003486 // update volume on all outputs and streams matching the following:
3487 // - The requested stream (or a stream matching for volume control) is active on the output
3488 // - The device (or devices) selected by the engine for this stream includes
3489 // the requested device
3490 // - For non default requested device, currently selected device on the output is either the
3491 // requested device or one of the devices selected by the engine for this stream
3492 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3493 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003494 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003495 for (size_t i = 0; i < mOutputs.size(); i++) {
3496 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003497 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003498
jiabin9a3361e2019-10-01 09:38:30 -07003499 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3500 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003501 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003502
3503 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003504 continue;
3505 }
3506 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3507 curDevices.find(device) == curDevices.end()) {
3508 continue;
3509 }
3510 bool applyVolume = false;
3511 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3512 curSrcDevices.insert(device);
3513 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003514 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3515 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003516 } else {
3517 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3518 }
3519 if (!applyVolume) {
3520 continue; // next output
3521 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003522 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3523 // If a higher priority strategy is active, and the output is routed to a device with a
3524 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003525 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003526 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003527 // If the volume source is active with higher priority source, ensure at least Sw Muted
3528 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003529 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3530 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3531 false /*preferredDevice*/);
3532 if (activeClients.empty()) {
3533 continue;
3534 }
3535 bool isPreempted = false;
3536 bool isHigherPriority = productStrategy < strategy;
3537 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003538 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003539 ALOGV("%s: Strategy=%d (\nrequester:\n"
3540 " group %d, volumeGroup=%d attributes=%s)\n"
3541 " higher priority source active:\n"
3542 " volumeGroup=%d attributes=%s) \n"
3543 " on output %zu, bailing out", __func__, productStrategy,
3544 group, group, toString(attributes).c_str(),
3545 client->volumeSource(), toString(client->attributes()).c_str(), i);
3546 applyVolume = false;
3547 isPreempted = true;
3548 break;
3549 }
3550 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003551 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003552 applyVolume = true;
3553 }
3554 }
3555 if (isPreempted || applyVolume) {
3556 break;
3557 }
3558 }
3559 if (!applyVolume) {
3560 continue; // next output
3561 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003562 }
François Gaffieed91f582020-01-31 10:35:37 +01003563 //FIXME: workaround for truncated touch sounds
3564 // delayed volume change for system stream to be removed when the problem is
3565 // handled by system UI
3566 status_t volStatus = checkAndSetVolume(
3567 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003568 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003569 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3570 if (volStatus != NO_ERROR) {
3571 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003572 }
3573 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003574
3575 // update voice volume if the an active call route exists
3576 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3577 && (curSrcDevices.find(
3578 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3579 != curSrcDevices.end())) {
3580 bool isVoiceVolSrc;
3581 bool isBtScoVolSrc;
3582 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3583 isVoiceVolSrc, isBtScoVolSrc, __func__)
3584 && (isVoiceVolSrc || isBtScoVolSrc)) {
3585 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3586 }
3587 }
3588
François Gaffiecfe17322018-11-07 13:41:29 +01003589 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3590 return status;
3591}
3592
François Gaffieaaac0fd2018-11-22 17:56:39 +01003593status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003594 audio_devices_t device,
3595 IVolumeCurves &volumeCurves)
3596{
3597 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3598 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003599 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3600 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003601 (index > volumeCurves.getVolumeIndexMax())) {
3602 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3603 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3604 return BAD_VALUE;
3605 }
3606 if (!audio_is_output_device(device)) {
3607 return BAD_VALUE;
3608 }
3609
3610 // Force max volume if stream cannot be muted
3611 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3612
François Gaffieaaac0fd2018-11-22 17:56:39 +01003613 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003614 volumeCurves.addCurrentVolumeIndex(device, index);
3615 return NO_ERROR;
3616}
3617
3618status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3619 int &index,
3620 audio_devices_t device)
3621{
3622 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3623 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003624 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003625 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003626 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003627 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003628 }
jiabin9a3361e2019-10-01 09:38:30 -07003629 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003630}
3631
3632status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3633 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003634 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003635{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003636 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003637 return BAD_VALUE;
3638 }
jiabin9a3361e2019-10-01 09:38:30 -07003639 index = curves.getVolumeIndex(deviceTypes);
3640 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003641 return NO_ERROR;
3642}
3643
3644status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3645 int &index)
3646{
3647 index = getVolumeCurves(attr).getVolumeIndexMin();
3648 return NO_ERROR;
3649}
3650
3651status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3652 int &index)
3653{
3654 index = getVolumeCurves(attr).getVolumeIndexMax();
3655 return NO_ERROR;
3656}
3657
Eric Laurent36829f92017-04-07 19:04:42 -07003658audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003659{
3660 // select one output among several suitable for global effects.
3661 // The priority is as follows:
3662 // 1: An offloaded output. If the effect ends up not being offloadable,
3663 // AudioFlinger will invalidate the track and the offloaded output
3664 // will be closed causing the effect to be moved to a PCM output.
3665 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003666 // 3: The primary output
3667 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003668
François Gaffiec005e562018-11-06 15:04:49 +01003669 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3670 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003671 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003672
Eric Laurent36829f92017-04-07 19:04:42 -07003673 if (outputs.size() == 0) {
3674 return AUDIO_IO_HANDLE_NONE;
3675 }
Eric Laurente552edb2014-03-10 17:42:56 -07003676
Eric Laurent36829f92017-04-07 19:04:42 -07003677 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3678 bool activeOnly = true;
3679
3680 while (output == AUDIO_IO_HANDLE_NONE) {
3681 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3682 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3683 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3684
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003685 for (audio_io_handle_t output : outputs) {
3686 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003687 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003688 continue;
3689 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003690 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3691 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003692 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003693 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003694 }
3695 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003696 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003697 }
3698 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003699 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003700 }
3701 }
3702 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3703 output = outputOffloaded;
3704 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3705 output = outputDeepBuffer;
3706 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3707 output = outputPrimary;
3708 } else {
3709 output = outputs[0];
3710 }
3711 activeOnly = false;
3712 }
3713
3714 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003715 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3716 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003717 mMusicEffectOutput = output;
3718 }
3719
3720 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003721 return output;
3722}
3723
Eric Laurent36829f92017-04-07 19:04:42 -07003724audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3725{
3726 return selectOutputForMusicEffects();
3727}
3728
Eric Laurente0720872014-03-11 09:30:41 -07003729status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003730 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003731 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003732 int session,
3733 int id)
3734{
Shunkai Yao29d10572024-03-19 04:31:47 +00003735 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003736 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003737 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003738 index = mInputs.indexOfKey(io);
3739 if (index < 0) {
3740 ALOGW("registerEffect() unknown io %d", io);
3741 return INVALID_OPERATION;
3742 }
Eric Laurente552edb2014-03-10 17:42:56 -07003743 }
3744 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003745 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3746 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3747 || strategy == PRODUCT_STRATEGY_NONE));
3748 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003749}
3750
Eric Laurentc241b0d2018-11-28 09:08:49 -08003751status_t AudioPolicyManager::unregisterEffect(int id)
3752{
3753 if (mEffects.getEffect(id) == nullptr) {
3754 return INVALID_OPERATION;
3755 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003756 if (mEffects.isEffectEnabled(id)) {
3757 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3758 setEffectEnabled(id, false);
3759 }
3760 return mEffects.unregisterEffect(id);
3761}
3762
3763status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3764{
3765 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3766 if (effect == nullptr) {
3767 return INVALID_OPERATION;
3768 }
3769
3770 status_t status = mEffects.setEffectEnabled(id, enabled);
3771 if (status == NO_ERROR) {
3772 mInputs.trackEffectEnabled(effect, enabled);
3773 }
3774 return status;
3775}
3776
Eric Laurent6c796322019-04-09 14:13:17 -07003777
3778status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3779{
3780 mEffects.moveEffects(ids, io);
3781 return NO_ERROR;
3782}
3783
Eric Laurentc75307b2015-03-17 15:29:32 -07003784bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3785{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003786 auto vs = toVolumeSource(stream, false);
3787 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003788}
3789
3790bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3791{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003792 auto vs = toVolumeSource(stream, false);
3793 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003794}
3795
Eric Laurente0720872014-03-11 09:30:41 -07003796bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003797{
3798 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003799 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003800 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003801 return true;
3802 }
3803 }
3804 return false;
3805}
3806
Eric Laurent275e8e92014-11-30 15:14:47 -08003807// Register a list of custom mixes with their attributes and format.
3808// When a mix is registered, corresponding input and output profiles are
3809// added to the remote submix hw module. The profile contains only the
3810// parameters (sampling rate, format...) specified by the mix.
3811// The corresponding input remote submix device is also connected.
3812//
3813// When a remote submix device is connected, the address is checked to select the
3814// appropriate profile and the corresponding input or output stream is opened.
3815//
3816// When capture starts, getInputForAttr() will:
3817// - 1 look for a mix matching the address passed in attribtutes tags if any
3818// - 2 if none found, getDeviceForInputSource() will:
3819// - 2.1 look for a mix matching the attributes source
3820// - 2.2 if none found, default to device selection by policy rules
3821// At this time, the corresponding output remote submix device is also connected
3822// and active playback use cases can be transferred to this mix if needed when reconnecting
3823// after AudioTracks are invalidated
3824//
3825// When playback starts, getOutputForAttr() will:
3826// - 1 look for a mix matching the address passed in attribtutes tags if any
3827// - 2 if none found, look for a mix matching the attributes usage
3828// - 3 if none found, default to device and output selection by policy rules.
3829
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003830status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003831{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003832 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3833 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003834 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003835 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003836 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003837 // examine each mix's route type
3838 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003839 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003840 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3841 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3842 ALOGE("Unsupported Policy Mix %zu of %zu: "
3843 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3844 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003845 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003846 break;
3847 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003848 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3849 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003850 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003851 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3852 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003853 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003854 rSubmixModule = mHwModules.getModuleFromName(
3855 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3856 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003857 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003858 i);
3859 res = INVALID_OPERATION;
3860 break;
3861 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003862 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003863
Eric Laurent97ac8712018-07-27 18:59:02 -07003864 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003865 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003866 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003867 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003868 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3869 } else {
3870 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3871 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003872 }
François Gaffie036e1e92015-03-19 10:16:24 +01003873
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003874 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003875 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003876 res = INVALID_OPERATION;
3877 break;
3878 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003879 audio_config_t outputConfig = mix.mFormat;
3880 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003881 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3882 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003883 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3884 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003885 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003886 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3887 audio_is_linear_pcm(outputConfig.format)
3888 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003889 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003890 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3891 audio_is_linear_pcm(inputConfig.format)
3892 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003893
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003894 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003895 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003896 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003897 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003898 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003899 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003900 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003901 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3902 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003903 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003904 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003905 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003906
3907 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3908 mix.mDeviceType, mix.mDeviceAddress,
3909 String8(), AUDIO_FORMAT_DEFAULT);
3910 if (device == nullptr) {
3911 res = INVALID_OPERATION;
3912 break;
3913 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003914
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003915 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003916 // First try to find an already opened output supporting the device
3917 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003919
Eric Laurentc529cf62020-04-17 18:19:10 -07003920 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003921 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003922 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003923 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003924 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003925 } else {
3926 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003927 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003928 }
3929 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003930 // If no output found, try to find a direct output profile supporting the device
3931 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3932 sp<HwModule> module = mHwModules[i];
3933 for (size_t j = 0;
3934 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3935 j++) {
3936 sp<IOProfile> profile = module->getOutputProfiles()[j];
3937 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3938 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3939 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003940 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003941 res = INVALID_OPERATION;
3942 } else {
3943 foundOutput = true;
3944 }
3945 }
3946 }
3947 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003948 if (res != NO_ERROR) {
3949 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003950 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003951 res = INVALID_OPERATION;
3952 break;
3953 } else if (!foundOutput) {
3954 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003955 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003956 res = INVALID_OPERATION;
3957 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003958 } else {
3959 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003960 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003961 }
Eric Laurentc722f302014-12-10 11:21:49 -08003962 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003963 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003964 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003965 if (audio_flags::audio_mix_ownership()) {
3966 // Only unregister mixes that were actually registered to not accidentally unregister
3967 // mixes that already existed previously.
3968 unregisterPolicyMixes(registeredMixes);
3969 registeredMixes.clear();
3970 } else {
3971 unregisterPolicyMixes(mixes);
3972 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003973 } else if (checkOutputs) {
3974 checkForDeviceAndOutputChanges();
3975 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003976 }
3977 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003978}
3979
3980status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3981{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003982 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003983 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003984 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003985 sp<HwModule> rSubmixModule;
3986 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003987 for (const auto& mix : mixes) {
3988 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003989
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003990 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003991 rSubmixModule = mHwModules.getModuleFromName(
3992 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3993 if (rSubmixModule == 0) {
3994 res = INVALID_OPERATION;
3995 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003996 }
3997 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003998
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003999 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004000
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004001 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004002 res = INVALID_OPERATION;
4003 continue;
4004 }
4005
Marvin Ramin0783e202024-03-05 12:45:50 +01004006 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004007 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004008 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4009 status_t currentRes =
4010 setDeviceConnectionStateInt(device,
4011 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4012 address.c_str(),
4013 "remote-submix",
4014 AUDIO_FORMAT_DEFAULT);
4015 if (!audio_flags::audio_mix_ownership()) {
4016 res = currentRes;
4017 }
4018 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004019 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004020 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004021 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004022 }
4023 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004024 }
jiabin5740f082019-08-19 15:08:30 -07004025 rSubmixModule->removeOutputProfile(address.c_str());
4026 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004027
Kevin Rocard153f92d2018-12-18 18:33:28 -08004028 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004029 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004030 res = INVALID_OPERATION;
4031 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004032 } else {
4033 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004034 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004035 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004036 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004037
4038 if (res == NO_ERROR && checkOutputs) {
4039 checkForDeviceAndOutputChanges();
4040 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004041 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004042 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004043}
4044
Marvin Raminbdefaf02023-11-01 09:10:32 +01004045status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4046 if (!audio_flags::audio_mix_test_api()) {
4047 return INVALID_OPERATION;
4048 }
4049
4050 _aidl_return.clear();
4051 _aidl_return.reserve(mPolicyMixes.size());
4052 for (const auto &policyMix: mPolicyMixes) {
4053 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4054 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4055 policyMix->mCbFlags);
4056 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004057 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004058 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004059 }
4060
Vlad Popaa5d73f32024-03-08 16:05:38 -08004061 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004062 return OK;
4063}
4064
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004065status_t AudioPolicyManager::updatePolicyMix(
4066 const AudioMix& mix,
4067 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4068 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4069 if (res == NO_ERROR) {
4070 checkForDeviceAndOutputChanges();
4071 updateCallAndOutputRouting();
4072 }
4073 return res;
4074}
4075
Mikhail Naganov100f0122018-11-29 11:22:16 -08004076void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4077{
4078 size_t i = 0;
4079 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4080 for (const auto& fmt : mManualSurroundFormats) {
4081 if (i++ != 0) dst->append(", ");
4082 std::string sfmt;
4083 FormatConverter::toString(fmt, sfmt);
4084 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4085 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4086 }
4087}
4088
Eric Laurentc529cf62020-04-17 18:19:10 -07004089// Returns true if all devices types match the predicate and are supported by one HW module
4090bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004091 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004092 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004093 const char *context,
4094 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004095 for (size_t i = 0; i < devices.size(); i++) {
4096 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004097 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004098 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004099 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004100 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004101 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004102 return false;
4103 }
4104 }
4105 return true;
4106}
4107
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004108void AudioPolicyManager::changeOutputDevicesMuteState(
4109 const AudioDeviceTypeAddrVector& devices) {
4110 ALOGVV("%s() num devices %zu", __func__, devices.size());
4111
4112 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4113 getSoftwareOutputsForDevices(devices);
4114
4115 for (size_t i = 0; i < outputs.size(); i++) {
4116 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4117 DeviceVector prevDevices = outputDesc->devices();
4118 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4119 }
4120}
4121
4122std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4123 const AudioDeviceTypeAddrVector& devices) const
4124{
4125 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4126 DeviceVector deviceDescriptors;
4127 for (size_t j = 0; j < devices.size(); j++) {
4128 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4129 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4130 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4131 ALOGE("%s: device type %#x address %s not supported or not an output device",
4132 __func__, devices[j].mType, devices[j].getAddress());
4133 continue;
4134 }
4135 deviceDescriptors.add(desc);
4136 }
4137 for (size_t i = 0; i < mOutputs.size(); i++) {
4138 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4139 continue;
4140 }
4141 outputs.push_back(mOutputs.valueAt(i));
4142 }
4143 return outputs;
4144}
4145
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004146status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004147 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004148 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004149 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4150 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004151 }
4152 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004153 if (res != NO_ERROR) {
4154 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4155 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004156 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004157
4158 checkForDeviceAndOutputChanges();
4159 updateCallAndOutputRouting();
4160
4161 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004162}
4163
4164status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4165 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004166 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4167 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004168 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004169 __FUNCTION__, uid);
4170 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004171 }
4172
Eric Laurentc529cf62020-04-17 18:19:10 -07004173 checkForDeviceAndOutputChanges();
4174 updateCallAndOutputRouting();
4175
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004176 return res;
4177}
4178
Eric Laurent2517af32020-11-25 15:31:27 +01004179
jiabin0a488932020-08-07 17:32:40 -07004180status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4181 device_role_t role,
4182 const AudioDeviceTypeAddrVector &devices) {
4183 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4184 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004185
Eric Laurentc529cf62020-04-17 18:19:10 -07004186 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004187 return BAD_VALUE;
4188 }
jiabin0a488932020-08-07 17:32:40 -07004189 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004190 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004191 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4192 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004193 return status;
4194 }
4195
4196 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004197
4198 bool forceVolumeReeval = false;
4199 // FIXME: workaround for truncated touch sounds
4200 // to be removed when the problem is handled by system UI
4201 uint32_t delayMs = 0;
4202 if (strategy == mCommunnicationStrategy) {
4203 forceVolumeReeval = true;
4204 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4205 updateInputRouting();
4206 }
4207 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004208
4209 return NO_ERROR;
4210}
4211
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004212void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4213 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004214{
4215 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004216 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004217 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004218 // Only apply special touch sound delay once
4219 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004220 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004221 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004222 for (size_t i = 0; i < mOutputs.size(); i++) {
4223 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4224 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004225 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4226 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004227 // As done in setDeviceConnectionState, we could also fix default device issue by
4228 // preventing the force re-routing in case of default dev that distinguishes on address.
4229 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004230 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004231 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004232 // If the device is using preferred mixer attributes, the output need to reopen
4233 // with default configuration when the new selected devices are different from
4234 // current routing devices.
4235 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4236 continue;
4237 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304238
4239 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4240 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004241 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004242 // Only apply special touch sound delay once
4243 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004244 }
4245 if (forceVolumeReeval && !newDevices.isEmpty()) {
4246 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4247 }
4248 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004249 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004250 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004251}
4252
Eric Laurent2517af32020-11-25 15:31:27 +01004253void AudioPolicyManager::updateInputRouting() {
4254 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304255 // Skip for hotword recording as the input device switch
4256 // is handled within sound trigger HAL
4257 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4258 continue;
4259 }
Eric Laurent2517af32020-11-25 15:31:27 +01004260 auto newDevice = getNewInputDevice(activeDesc);
4261 // Force new input selection if the new device can not be reached via current input
4262 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4263 setInputDevice(activeDesc->mIoHandle, newDevice);
4264 } else {
4265 closeInput(activeDesc->mIoHandle);
4266 }
4267 }
4268}
4269
Paul Wang5d7cdb52022-11-22 09:45:06 +00004270status_t
4271AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4272 device_role_t role,
4273 const AudioDeviceTypeAddrVector &devices) {
4274 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4275 dumpAudioDeviceTypeAddrVector(devices).c_str());
4276
Eric Laurent78fedbf2023-03-09 14:40:44 +01004277 if (!areAllDevicesSupported(
4278 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004279 return BAD_VALUE;
4280 }
4281 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4282 if (status != NO_ERROR) {
4283 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4284 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4285 return status;
4286 }
4287
4288 checkForDeviceAndOutputChanges();
4289
4290 bool forceVolumeReeval = false;
4291 // TODO(b/263479999): workaround for truncated touch sounds
4292 // to be removed when the problem is handled by system UI
4293 uint32_t delayMs = 0;
4294 if (strategy == mCommunnicationStrategy) {
4295 forceVolumeReeval = true;
4296 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4297 updateInputRouting();
4298 }
4299 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4300
4301 return NO_ERROR;
4302}
4303
4304status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4305 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004306{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004307 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004308
Paul Wang5d7cdb52022-11-22 09:45:06 +00004309 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004310 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004311 ALOGW_IF(status != NAME_NOT_FOUND,
4312 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004313 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004314 return status;
4315 }
4316
4317 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004318
4319 bool forceVolumeReeval = false;
4320 // FIXME: workaround for truncated touch sounds
4321 // to be removed when the problem is handled by system UI
4322 uint32_t delayMs = 0;
4323 if (strategy == mCommunnicationStrategy) {
4324 forceVolumeReeval = true;
4325 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4326 updateInputRouting();
4327 }
4328 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004329
4330 return NO_ERROR;
4331}
4332
jiabin0a488932020-08-07 17:32:40 -07004333status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4334 device_role_t role,
4335 AudioDeviceTypeAddrVector &devices) {
4336 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004337}
4338
Jiabin Huang3b98d322020-09-03 17:54:16 +00004339status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4340 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4341 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4342 dumpAudioDeviceTypeAddrVector(devices).c_str());
4343
Mikhail Naganov55773032020-10-01 15:08:13 -07004344 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004345 return BAD_VALUE;
4346 }
4347 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4348 ALOGW_IF(status != NO_ERROR,
4349 "Engine could not set preferred devices %s for audio source %d role %d",
4350 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4351
4352 return status;
4353}
4354
4355status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4356 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4357 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4358 dumpAudioDeviceTypeAddrVector(devices).c_str());
4359
Mikhail Naganov55773032020-10-01 15:08:13 -07004360 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004361 return BAD_VALUE;
4362 }
4363 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4364 ALOGW_IF(status != NO_ERROR,
4365 "Engine could not add preferred devices %s for audio source %d role %d",
4366 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4367
Eric Laurent2517af32020-11-25 15:31:27 +01004368 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004369 return status;
4370}
4371
4372status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4373 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4374{
4375 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4376 dumpAudioDeviceTypeAddrVector(devices).c_str());
4377
Eric Laurent78fedbf2023-03-09 14:40:44 +01004378 if (!areAllDevicesSupported(
4379 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004380 return BAD_VALUE;
4381 }
4382
4383 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4384 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004385 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004386 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004387 if (status == NO_ERROR) {
4388 updateInputRouting();
4389 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004390 return status;
4391}
4392
4393status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4394 device_role_t role) {
4395 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4396
4397 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004398 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004399 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004400 if (status == NO_ERROR) {
4401 updateInputRouting();
4402 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004403 return status;
4404}
4405
4406status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4407 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4408 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4409}
4410
Oscar Azucena90e77632019-11-27 17:12:28 -08004411status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004412 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004413 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004414 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4415 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004416 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004417 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4418 if (status != NO_ERROR) {
4419 ALOGE("%s() could not set device affinity for userId %d",
4420 __FUNCTION__, userId);
4421 return status;
4422 }
4423
4424 // reevaluate outputs for all devices
4425 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004426 changeOutputDevicesMuteState(devices);
4427 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4428 true /* skipDelays */);
4429 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004430
4431 return NO_ERROR;
4432}
4433
4434status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004435 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004436 AudioDeviceTypeAddrVector devices;
4437 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004438 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4439 if (status != NO_ERROR) {
4440 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4441 __FUNCTION__, userId);
4442 return status;
4443 }
4444
4445 // reevaluate outputs for all devices
4446 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004447 changeOutputDevicesMuteState(devices);
4448 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4449 true /* skipDelays */);
4450 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004451
4452 return NO_ERROR;
4453}
4454
Andy Hungc29d82b2018-10-05 12:23:17 -07004455void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004456{
Andy Hungc29d82b2018-10-05 12:23:17 -07004457 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004458 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004459 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004460 std::string stateLiteral;
4461 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004462 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004463 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4464 "communications", "media", "record", "dock", "system",
4465 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4466 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4467 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004468 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4469 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4470 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4471 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4472 dst->append(" (MANUAL: ");
4473 dumpManualSurroundFormats(dst);
4474 dst->append(")");
4475 }
4476 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004477 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004478 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4479 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004480 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004481 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004482
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004483 dst->append("\n");
4484 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4485 dst->append("\n");
4486 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004487 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004488 mOutputs.dump(dst);
4489 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004490 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004491 mAudioPatches.dump(dst);
4492 mPolicyMixes.dump(dst);
4493 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004494
Kevin Rocardb99cc752019-03-21 20:52:24 -07004495 dst->appendFormat(" AllowedCapturePolicies:\n");
4496 for (auto& policy : mAllowedCapturePolicies) {
4497 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4498 }
4499
jiabina84c3d32022-12-02 18:59:55 +00004500 dst->appendFormat(" Preferred mixer audio configuration:\n");
4501 for (const auto it : mPreferredMixerAttrInfos) {
4502 dst->appendFormat(" - device port id: %d\n", it.first);
4503 for (const auto preferredMixerInfoIt : it.second) {
4504 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4505 preferredMixerInfoIt.second->dump(dst);
4506 }
4507 }
4508
François Gaffiec005e562018-11-06 15:04:49 +01004509 dst->appendFormat("\nPolicy Engine dump:\n");
4510 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004511
4512 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4513 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4514 dst->appendFormat(" - device type: %s, driving stream %d\n",
4515 dumpDeviceTypes({it.first}).c_str(),
4516 mEngine->getVolumeGroupForAttributes(it.second));
4517 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004518}
4519
4520status_t AudioPolicyManager::dump(int fd)
4521{
4522 String8 result;
4523 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004524 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004525 return NO_ERROR;
4526}
4527
Kevin Rocardb99cc752019-03-21 20:52:24 -07004528status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4529{
4530 mAllowedCapturePolicies[uid] = capturePolicy;
4531 return NO_ERROR;
4532}
4533
Eric Laurente552edb2014-03-10 17:42:56 -07004534// This function checks for the parameters which can be offloaded.
4535// This can be enhanced depending on the capability of the DSP and policy
4536// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004537audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004538{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004539 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004540 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004541 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004542 offloadInfo.format,
4543 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4544 offloadInfo.has_video);
4545
jiabin2b9d5a12021-12-10 01:06:29 +00004546 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004547 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004548 }
4549
4550 // See if there is a profile to support this.
4551 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004552 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004553 offloadInfo.sample_rate,
4554 offloadInfo.format,
4555 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004556 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4557 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004558 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4559 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4560 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004561 if (profile == nullptr) {
4562 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4563 }
4564 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4565 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4566 }
4567 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004568}
4569
Michael Chana94fbb22018-04-24 14:31:19 +10004570bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4571 const audio_attributes_t& attributes) {
4572 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004573 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004574 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4575 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004576 config.sample_rate,
4577 config.format,
4578 config.channel_mask,
4579 output_flags,
4580 true /* directOnly */);
4581 ALOGV("%s() profile %sfound with name: %s, "
4582 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4583 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004584 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004585 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004586
4587 // also try the MSD module if compatible profile not found
4588 if (profile == nullptr) {
4589 profile = getMsdProfileForOutput(outputDevices,
4590 config.sample_rate,
4591 config.format,
4592 config.channel_mask,
4593 output_flags,
4594 true /* directOnly */);
4595 ALOGV("%s() MSD profile %sfound with name: %s, "
4596 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4597 __FUNCTION__, profile != 0 ? "" : "NOT ",
4598 (profile != 0 ? profile->getTagName().c_str() : "null"),
4599 config.sample_rate, config.format, config.channel_mask, output_flags);
4600 }
4601 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004602}
4603
jiabin2b9d5a12021-12-10 01:06:29 +00004604bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4605 bool durationIgnored) {
4606 if (mMasterMono) {
4607 return false; // no offloading if mono is set.
4608 }
4609
4610 // Check if offload has been disabled
4611 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4612 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4613 return false;
4614 }
4615
4616 // Check if stream type is music, then only allow offload as of now.
4617 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4618 {
4619 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4620 return false;
4621 }
4622
4623 //TODO: enable audio offloading with video when ready
4624 const bool allowOffloadWithVideo =
4625 property_get_bool("audio.offload.video", false /* default_value */);
4626 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4627 ALOGV("%s: has_video == true, returning false", __func__);
4628 return false;
4629 }
4630
4631 //If duration is less than minimum value defined in property, return false
4632 const int min_duration_secs = property_get_int32(
4633 "audio.offload.min.duration.secs", -1 /* default_value */);
4634 if (!durationIgnored) {
4635 if (min_duration_secs >= 0) {
4636 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4637 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4638 __func__, min_duration_secs);
4639 return false;
4640 }
4641 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4642 ALOGV("%s: Offload denied by duration < default min(=%u)",
4643 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4644 return false;
4645 }
4646 }
4647
4648 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4649 // creating an offloaded track and tearing it down immediately after start when audioflinger
4650 // detects there is an active non offloadable effect.
4651 // FIXME: We should check the audio session here but we do not have it in this context.
4652 // This may prevent offloading in rare situations where effects are left active by apps
4653 // in the background.
4654 if (mEffects.isNonOffloadableEffectEnabled()) {
4655 return false;
4656 }
4657
4658 return true;
4659}
4660
4661audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4662 const audio_config_t *config) {
4663 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4664 offloadInfo.format = config->format;
4665 offloadInfo.sample_rate = config->sample_rate;
4666 offloadInfo.channel_mask = config->channel_mask;
4667 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4668 offloadInfo.has_video = false;
4669 offloadInfo.is_streaming = false;
4670 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4671
4672 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4673 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4674 audio_flags_to_audio_output_flags(attr->flags, &flags);
4675 // only retain flags that will drive compressed offload or passthrough
4676 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4677 if (offloadPossible) {
4678 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4679 }
4680 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4681
Dorin Drimusfae3c642022-03-17 18:36:30 +01004682 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004683 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004684 DeviceVector outputDevices = engineOutputDevices;
4685 // the MSD module checks for different conditions and output devices
4686 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4687 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4688 continue;
4689 }
4690 outputDevices = getMsdAudioOutDevices();
4691 }
jiabin2b9d5a12021-12-10 01:06:29 +00004692 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004693 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004694 config->sample_rate, nullptr /*updatedSamplingRate*/,
4695 config->format, nullptr /*updatedFormat*/,
4696 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004697 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004698 continue;
4699 }
4700 // reject profiles not corresponding to a device currently available
4701 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4702 continue;
4703 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004704 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4705 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004706 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004707 != AUDIO_DIRECT_NOT_SUPPORTED) {
4708 // Already reports offload gapless supported. No need to report offload support.
4709 continue;
4710 }
4711 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4712 != AUDIO_OUTPUT_FLAG_NONE) {
4713 // If offload gapless is reported, no need to report offload support.
4714 directMode = (audio_direct_mode_t) ((directMode &
4715 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4716 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4717 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004718 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004719 }
4720 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004721 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004722 }
4723 }
4724 }
4725 return directMode;
4726}
4727
Dorin Drimusf2196d82022-01-03 12:11:18 +01004728status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4729 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004730 if (mEffects.isNonOffloadableEffectEnabled()) {
4731 return OK;
4732 }
jiabinf1c73972022-04-14 16:28:52 -07004733 DeviceVector devices;
4734 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004735 if (status != OK) {
4736 return status;
4737 }
4738 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4739 if (devices.empty()) {
4740 return OK; // no output devices for the attributes
4741 }
jiabinf1c73972022-04-14 16:28:52 -07004742 return getProfilesForDevices(devices, audioProfilesVector,
4743 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004744}
4745
jiabina84c3d32022-12-02 18:59:55 +00004746status_t AudioPolicyManager::getSupportedMixerAttributes(
4747 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4748 ALOGV("%s, portId=%d", __func__, portId);
4749 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4750 if (deviceDescriptor == nullptr) {
4751 ALOGE("%s the requested device is currently unavailable", __func__);
4752 return BAD_VALUE;
4753 }
jiabin96daffc2023-05-11 17:51:55 +00004754 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4755 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4756 deviceDescriptor->type());
4757 return BAD_VALUE;
4758 }
jiabina84c3d32022-12-02 18:59:55 +00004759 for (const auto& hwModule : mHwModules) {
4760 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4761 if (curProfile->supportsDevice(deviceDescriptor)) {
4762 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4763 }
4764 }
4765 }
4766 return NO_ERROR;
4767}
4768
4769status_t AudioPolicyManager::setPreferredMixerAttributes(
4770 const audio_attributes_t *attr,
4771 audio_port_handle_t portId,
4772 uid_t uid,
4773 const audio_mixer_attributes_t *mixerAttributes) {
4774 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4775 "mixerBehavior=%d}, uid=%d, portId=%u",
4776 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4777 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4778 mixerAttributes->mixer_behavior, uid, portId);
4779 if (attr->usage != AUDIO_USAGE_MEDIA) {
4780 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4781 return BAD_VALUE;
4782 }
4783 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4784 if (deviceDescriptor == nullptr) {
4785 ALOGE("%s the requested device is currently unavailable", __func__);
4786 return BAD_VALUE;
4787 }
4788 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4789 ALOGE("%s(%d), type=%d, is not a usb output device",
4790 __func__, portId, deviceDescriptor->type());
4791 return BAD_VALUE;
4792 }
4793
4794 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4795 audio_flags_to_audio_output_flags(attr->flags, &flags);
4796 flags = (audio_output_flags_t) (flags |
4797 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4798 sp<IOProfile> profile = nullptr;
4799 DeviceVector devices(deviceDescriptor);
4800 for (const auto& hwModule : mHwModules) {
4801 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4802 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004803 && curProfile->getCompatibilityScore(
4804 devices,
4805 mixerAttributes->config.sample_rate,
4806 nullptr /*updatedSamplingRate*/,
4807 mixerAttributes->config.format,
4808 nullptr /*updatedFormat*/,
4809 mixerAttributes->config.channel_mask,
4810 nullptr /*updatedChannelMask*/,
4811 flags,
4812 false /*exactMatchRequiredForInputFlags*/)
4813 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004814 profile = curProfile;
4815 break;
4816 }
4817 }
4818 }
4819 if (profile == nullptr) {
4820 ALOGE("%s, there is no compatible profile found", __func__);
4821 return BAD_VALUE;
4822 }
4823
4824 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4825 sp<PreferredMixerAttributesInfo>::make(
4826 uid, portId, profile, flags, *mixerAttributes);
4827 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4828 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4829
4830 // If 1) there is any client from the preferred mixer configuration owner that is currently
4831 // active and matches the strategy and 2) current output is on the preferred device and the
4832 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4833 // configuration.
4834 std::vector<audio_io_handle_t> outputsToReopen;
4835 for (size_t i = 0; i < mOutputs.size(); i++) {
4836 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004837 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4838 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004839 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004840 } else {
4841 for (const auto &client: output->getActiveClients()) {
4842 if (client->uid() == uid && client->strategy() == strategy) {
4843 client->setIsInvalid();
4844 outputsToReopen.push_back(output->mIoHandle);
4845 }
jiabina84c3d32022-12-02 18:59:55 +00004846 }
4847 }
4848 }
4849 }
4850 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4851 config.sample_rate = mixerAttributes->config.sample_rate;
4852 config.channel_mask = mixerAttributes->config.channel_mask;
4853 config.format = mixerAttributes->config.format;
4854 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004855 sp<SwAudioOutputDescriptor> desc =
4856 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4857 if (desc == nullptr) {
4858 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4859 continue;
4860 }
jiabin220eea12024-05-17 17:55:20 +00004861 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004862 }
4863
4864 return NO_ERROR;
4865}
4866
4867sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004868 audio_port_handle_t devicePortId,
4869 product_strategy_t strategy,
4870 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004871 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4872 if (it == mPreferredMixerAttrInfos.end()) {
4873 return nullptr;
4874 }
jiabind9a58d32023-06-01 17:57:30 +00004875 if (activeBitPerfectPreferred) {
4876 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004877 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004878 return info;
4879 }
4880 }
jiabina84c3d32022-12-02 18:59:55 +00004881 }
jiabind9a58d32023-06-01 17:57:30 +00004882 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4883 return strategyMatchedMixerAttrInfoIt == it->second.end()
4884 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004885}
4886
4887status_t AudioPolicyManager::getPreferredMixerAttributes(
4888 const audio_attributes_t *attr,
4889 audio_port_handle_t portId,
4890 audio_mixer_attributes_t* mixerAttributes) {
4891 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4892 portId, mEngine->getProductStrategyForAttributes(*attr));
4893 if (info == nullptr) {
4894 return NAME_NOT_FOUND;
4895 }
4896 *mixerAttributes = info->getMixerAttributes();
4897 return NO_ERROR;
4898}
4899
4900status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4901 audio_port_handle_t portId,
4902 uid_t uid) {
4903 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4904 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4905 if (preferredMixerAttrInfo == nullptr) {
4906 return NAME_NOT_FOUND;
4907 }
4908 if (preferredMixerAttrInfo->getUid() != uid) {
4909 ALOGE("%s, requested uid=%d, owned uid=%d",
4910 __func__, uid, preferredMixerAttrInfo->getUid());
4911 return PERMISSION_DENIED;
4912 }
4913 mPreferredMixerAttrInfos[portId].erase(strategy);
4914 if (mPreferredMixerAttrInfos[portId].empty()) {
4915 mPreferredMixerAttrInfos.erase(portId);
4916 }
4917
4918 // Reconfig existing output
4919 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4920 for (size_t i = 0; i < mOutputs.size(); i++) {
4921 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4922 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4923 }
4924 }
4925 for (const auto output : potentialOutputsToReopen) {
4926 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4927 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4928 preferredMixerAttrInfo->getFlags())) {
4929 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4930 }
4931 }
4932 return NO_ERROR;
4933}
4934
Eric Laurent6a94d692014-05-20 11:18:06 -07004935status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4936 audio_port_type_t type,
4937 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004938 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 unsigned int *generation)
4940{
jiabin19cdba52020-11-24 11:28:58 -08004941 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4942 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004943 return BAD_VALUE;
4944 }
4945 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004946 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004947 *num_ports = 0;
4948 }
4949
4950 size_t portsWritten = 0;
4951 size_t portsMax = *num_ports;
4952 *num_ports = 0;
4953 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004954 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4955 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004956 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004957 for (const auto& dev : mAvailableOutputDevices) {
4958 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004959 continue;
4960 }
4961 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004962 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004963 }
4964 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004966 }
4967 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004968 for (const auto& dev : mAvailableInputDevices) {
4969 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004970 continue;
4971 }
4972 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004973 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004974 }
4975 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 }
4978 }
4979 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4980 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4981 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4982 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4983 }
4984 *num_ports += mInputs.size();
4985 }
4986 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004987 size_t numOutputs = 0;
4988 for (size_t i = 0; i < mOutputs.size(); i++) {
4989 if (!mOutputs[i]->isDuplicated()) {
4990 numOutputs++;
4991 if (portsWritten < portsMax) {
4992 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4993 }
4994 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 }
Eric Laurent84c70242014-06-23 08:46:27 -07004996 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 }
4998 }
jiabina84c3d32022-12-02 18:59:55 +00004999
Eric Laurent6a94d692014-05-20 11:18:06 -07005000 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005001 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 return NO_ERROR;
5003}
5004
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005005status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5006 std::vector<media::AudioPortFw>* _aidl_return) {
5007 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5008 audio_port_v7 port;
5009 dev->toAudioPort(&port);
5010 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5011 _aidl_return->push_back(std::move(aidlPort));
5012 return OK;
5013 };
5014
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005015 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005016 for (const auto& dev : module->getDeclaredDevices()) {
5017 if (role == media::AudioPortRole::NONE ||
5018 ((role == media::AudioPortRole::SOURCE)
5019 == audio_is_input_device(dev->type()))) {
5020 RETURN_STATUS_IF_ERROR(pushPort(dev));
5021 }
5022 }
5023 }
5024 return OK;
5025}
5026
jiabin19cdba52020-11-24 11:28:58 -08005027status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005028{
Eric Laurent99fcae42018-05-17 16:59:18 -07005029 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5030 return BAD_VALUE;
5031 }
5032 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5033 if (dev != 0) {
5034 dev->toAudioPort(port);
5035 return NO_ERROR;
5036 }
5037 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5038 if (dev != 0) {
5039 dev->toAudioPort(port);
5040 return NO_ERROR;
5041 }
5042 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5043 if (out != 0) {
5044 out->toAudioPort(port);
5045 return NO_ERROR;
5046 }
5047 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5048 if (in != 0) {
5049 in->toAudioPort(port);
5050 return NO_ERROR;
5051 }
5052 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005053}
5054
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005055status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5056 audio_patch_handle_t *handle,
5057 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005058{
François Gaffieafd4cea2019-11-18 15:50:22 +01005059 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 if (handle == NULL || patch == NULL) {
5061 return BAD_VALUE;
5062 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005063 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005064 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005065 return BAD_VALUE;
5066 }
5067 // only one source per audio patch supported for now
5068 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 return INVALID_OPERATION;
5070 }
Eric Laurent874c42872014-08-08 15:13:39 -07005071 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005072 return INVALID_OPERATION;
5073 }
Eric Laurent874c42872014-08-08 15:13:39 -07005074 for (size_t i = 0; i < patch->num_sinks; i++) {
5075 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5076 return INVALID_OPERATION;
5077 }
5078 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005079
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005080 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5081 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5082 if (srcDevice == nullptr || sinkDevice == nullptr) {
5083 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5084 return BAD_VALUE;
5085 }
5086 ALOGV("%s between source %s and sink %s", __func__,
5087 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5088 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5089 // Default attributes, default volume priority, not to infer with non raw audio patches.
5090 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5091 const struct audio_port_config *source = &patch->sources[0];
5092 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005093 new SourceClientDescriptor(
5094 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5095 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
5096 true);
5097 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005098
5099 status_t status =
5100 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5101
5102 if (status != NO_ERROR) {
5103 return INVALID_OPERATION;
5104 }
5105 mAudioSources.add(portId, sourceDesc);
5106 return NO_ERROR;
5107}
5108
5109status_t AudioPolicyManager::connectAudioSourceToSink(
5110 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5111 const struct audio_patch *patch,
5112 audio_patch_handle_t &handle,
5113 uid_t uid, uint32_t delayMs)
5114{
5115 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5116 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5117 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5118 return INVALID_OPERATION;
5119 }
5120 sourceDesc->connect(handle, sinkDevice);
5121 if (isMsdPatch(handle)) {
5122 return NO_ERROR;
5123 }
5124 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5125 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5126 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5127 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5128 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5129 goto FailurePatchAdded;
5130 }
5131 status = swOutput->start();
5132 if (status != NO_ERROR) {
5133 goto FailureSourceAdded;
5134 }
5135 swOutput->addClient(sourceDesc);
5136 status = startSource(swOutput, sourceDesc, &delayMs);
5137 if (status != NO_ERROR) {
5138 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5139 goto FailureSourceActive;
5140 }
5141 if (delayMs != 0) {
5142 usleep(delayMs * 1000);
5143 }
5144 return NO_ERROR;
5145
5146FailureSourceActive:
5147 swOutput->stop();
5148 releaseOutput(sourceDesc->portId());
5149FailureSourceAdded:
5150 sourceDesc->setSwOutput(nullptr);
5151FailurePatchAdded:
5152 releaseAudioPatchInternal(handle);
5153 return INVALID_OPERATION;
5154}
5155
5156status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5157 audio_patch_handle_t *handle,
5158 uid_t uid, uint32_t delayMs,
5159 const sp<SourceClientDescriptor>& sourceDesc)
5160{
5161 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005162 sp<AudioPatch> patchDesc;
5163 ssize_t index = mAudioPatches.indexOfKey(*handle);
5164
François Gaffieafd4cea2019-11-18 15:50:22 +01005165 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5166 patch->sources[0].role,
5167 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005168#if LOG_NDEBUG == 0
5169 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005170 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5171 patch->sinks[i].role,
5172 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005173 }
5174#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005175
5176 if (index >= 0) {
5177 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005178 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5179 __func__, mUidCached, patchDesc->getUid(), uid);
5180 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005181 return INVALID_OPERATION;
5182 }
5183 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005184 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005185 }
5186
5187 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005188 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005190 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 return BAD_VALUE;
5192 }
Eric Laurent84c70242014-06-23 08:46:27 -07005193 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5194 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005195 if (patchDesc != 0) {
5196 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005197 ALOGV("%s source id differs for patch current id %d new id %d",
5198 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005199 return BAD_VALUE;
5200 }
5201 }
Eric Laurent874c42872014-08-08 15:13:39 -07005202 DeviceVector devices;
5203 for (size_t i = 0; i < patch->num_sinks; i++) {
5204 // Only support mix to devices connection
5205 // TODO add support for mix to mix connection
5206 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005207 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005208 return INVALID_OPERATION;
5209 }
5210 sp<DeviceDescriptor> devDesc =
5211 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5212 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005213 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005214 return BAD_VALUE;
5215 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005216
jiabin66acc432024-02-06 00:57:36 +00005217 if (outputDesc->mProfile->getCompatibilityScore(
5218 DeviceVector(devDesc),
5219 patch->sources[0].sample_rate,
5220 nullptr, // updatedSamplingRate
5221 patch->sources[0].format,
5222 nullptr, // updatedFormat
5223 patch->sources[0].channel_mask,
5224 nullptr, // updatedChannelMask
5225 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005226 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005227 return INVALID_OPERATION;
5228 }
5229 devices.add(devDesc);
5230 }
5231 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005232 return INVALID_OPERATION;
5233 }
Eric Laurent874c42872014-08-08 15:13:39 -07005234
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005236 ALOGV("%s setting device %s on output %d",
5237 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305238 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005239 index = mAudioPatches.indexOfKey(*handle);
5240 if (index >= 0) {
5241 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005242 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005243 }
5244 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005245 patchDesc->setUid(uid);
5246 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005247 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005248 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 return INVALID_OPERATION;
5250 }
5251 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5252 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5253 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005254 // only one sink supported when connecting an input device to a mix
5255 if (patch->num_sinks > 1) {
5256 return INVALID_OPERATION;
5257 }
François Gaffie53615e22015-03-19 09:24:12 +01005258 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 if (inputDesc == NULL) {
5260 return BAD_VALUE;
5261 }
5262 if (patchDesc != 0) {
5263 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5264 return BAD_VALUE;
5265 }
5266 }
François Gaffie11d30102018-11-02 16:09:09 +01005267 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005268 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005269 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 return BAD_VALUE;
5271 }
5272
jiabin66acc432024-02-06 00:57:36 +00005273 if (inputDesc->mProfile->getCompatibilityScore(
5274 DeviceVector(device),
5275 patch->sinks[0].sample_rate,
5276 nullptr, /*updatedSampleRate*/
5277 patch->sinks[0].format,
5278 nullptr, /*updatedFormat*/
5279 patch->sinks[0].channel_mask,
5280 nullptr, /*updatedChannelMask*/
5281 // FIXME for the parameter type,
5282 // and the NONE
5283 (audio_output_flags_t)
5284 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 return INVALID_OPERATION;
5286 }
5287 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005288 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005289 device->toString().c_str(), inputDesc->mIoHandle);
5290 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005291 index = mAudioPatches.indexOfKey(*handle);
5292 if (index >= 0) {
5293 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005294 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005295 }
5296 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005297 patchDesc->setUid(uid);
5298 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005300 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005301 return INVALID_OPERATION;
5302 }
5303 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5304 // device to device connection
5305 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005306 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005307 return BAD_VALUE;
5308 }
5309 }
François Gaffie11d30102018-11-02 16:09:09 +01005310 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005312 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005313 return BAD_VALUE;
5314 }
Eric Laurent874c42872014-08-08 15:13:39 -07005315
Eric Laurent6a94d692014-05-20 11:18:06 -07005316 //update source and sink with our own data as the data passed in the patch may
5317 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005318 PatchBuilder patchBuilder;
5319 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005320
5321 // if first sink is to MSD, establish single MSD patch
5322 if (getMsdAudioOutDevices().contains(
5323 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5324 ALOGV("%s patching to MSD", __FUNCTION__);
5325 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5326 goto installPatch;
5327 }
5328
François Gaffieafd4cea2019-11-18 15:50:22 +01005329 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5330 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005331
Eric Laurent874c42872014-08-08 15:13:39 -07005332 for (size_t i = 0; i < patch->num_sinks; i++) {
5333 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005334 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005335 return INVALID_OPERATION;
5336 }
François Gaffie11d30102018-11-02 16:09:09 +01005337 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005338 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005339 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005340 return BAD_VALUE;
5341 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005342 audio_port_config sinkPortConfig = {};
5343 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5344 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005345
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005346 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5347 // volume management purpose (tracking activity)
5348 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5349 // in config XML to reach the sink so that is can be declared as available.
5350 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005351 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005352 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005353 // take care of dynamic routing for SwOutput selection,
5354 audio_attributes_t attributes = sourceDesc->attributes();
5355 audio_stream_type_t stream = sourceDesc->stream();
5356 audio_attributes_t resultAttr;
5357 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5358 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005359 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5360 config.channel_mask =
5361 (audio_channel_mask_get_representation(sourceMask)
5362 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5363 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005364 config.format = sourceDesc->config().format;
5365 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5366 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5367 bool isRequestedDeviceForExclusiveUse = false;
5368 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005369 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005370 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005371 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5372 &stream, sourceDesc->uid(), &config, &flags,
5373 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005374 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005375 if (output == AUDIO_IO_HANDLE_NONE) {
5376 ALOGV("%s no output for device %s",
5377 __FUNCTION__, sinkDevice->toString().c_str());
5378 return INVALID_OPERATION;
5379 }
5380 outputDesc = mOutputs.valueFor(output);
5381 if (outputDesc->isDuplicated()) {
5382 ALOGE("%s output is duplicated", __func__);
5383 return INVALID_OPERATION;
5384 }
François Gaffie7e39df22022-04-26 12:48:49 +02005385 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5386 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005387 } else {
5388 // Same for "raw patches" aka created from createAudioPatch API
5389 SortedVector<audio_io_handle_t> outputs =
5390 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5391 // if the sink device is reachable via an opened output stream, request to
5392 // go via this output stream by adding a second source to the patch
5393 // description
5394 output = selectOutput(outputs);
5395 if (output == AUDIO_IO_HANDLE_NONE) {
5396 ALOGE("%s no output available for internal patch sink", __func__);
5397 return INVALID_OPERATION;
5398 }
5399 outputDesc = mOutputs.valueFor(output);
5400 if (outputDesc->isDuplicated()) {
5401 ALOGV("%s output for device %s is duplicated",
5402 __func__, sinkDevice->toString().c_str());
5403 return INVALID_OPERATION;
5404 }
François Gaffie7e39df22022-04-26 12:48:49 +02005405 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005406 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005407 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005408 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005409 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005410 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005411 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5412 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005413 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5414 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005415 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005416 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005417 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005418 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005419 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005420 return INVALID_OPERATION;
5421 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005422 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005423 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005424 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005425 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005426 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005427 srcMixPortConfig.ext.mix.usecase.stream =
5428 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005429 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5430 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005431 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005432 }
Eric Laurent83b88082014-06-20 18:31:16 -07005433 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005434 }
5435 // TODO: check from routing capabilities in config file and other conflicting patches
5436
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005437installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005438 status_t status = installPatch(
5439 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005440 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005441 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 return INVALID_OPERATION;
5443 }
5444 } else {
5445 return BAD_VALUE;
5446 }
5447 } else {
5448 return BAD_VALUE;
5449 }
5450 return NO_ERROR;
5451}
5452
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005453status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005454{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005455 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005456 ssize_t index = mAudioPatches.indexOfKey(handle);
5457
5458 if (index < 0) {
5459 return BAD_VALUE;
5460 }
5461 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005462 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5463 __func__, mUidCached, patchDesc->getUid(), uid);
5464 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 return INVALID_OPERATION;
5466 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005467 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5468 for (size_t i = 0; i < mAudioSources.size(); i++) {
5469 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5470 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5471 portId = sourceDesc->portId();
5472 break;
5473 }
5474 }
5475 return portId != AUDIO_PORT_HANDLE_NONE ?
5476 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005477}
Eric Laurent6a94d692014-05-20 11:18:06 -07005478
François Gaffieafd4cea2019-11-18 15:50:22 +01005479status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005480 uint32_t delayMs,
5481 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005482{
5483 ALOGV("%s patch %d", __func__, handle);
5484 if (mAudioPatches.indexOfKey(handle) < 0) {
5485 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5486 return BAD_VALUE;
5487 }
5488 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005489 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005490 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005491 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005492 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005493 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005494 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005495 return BAD_VALUE;
5496 }
5497
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305498 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005499 getNewOutputDevices(outputDesc, true /*fromCache*/),
5500 true,
5501 0,
5502 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005503 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5504 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005505 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005506 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005507 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005508 return BAD_VALUE;
5509 }
5510 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005511 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005512 true,
5513 NULL);
5514 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005515 status_t status =
5516 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5517 ALOGV("%s patch panel returned %d patchHandle %d",
5518 __func__, status, patchDesc->getAfHandle());
5519 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005520 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005521 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005522 // SW or HW Bridge
5523 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5524 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005525 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005526 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5527 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5528 outputDesc = sourceDesc->swOutput().promote();
5529 }
5530 if (outputDesc == nullptr) {
5531 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5532 // releaseOutput has already called closeOutput in case of direct output
5533 return NO_ERROR;
5534 }
François Gaffie7e39df22022-04-26 12:48:49 +02005535 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005536 // While using a HwBridge, force reconsidering device only if not reusing an existing
5537 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005538 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005539 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5540 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5541 // Reconsider device only for cases:
5542 // 1 / Active Output
5543 // 2 / Inactive Output previously hosting HwBridge
5544 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5545 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5546 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305547 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005548 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5549 outputDesc->devices(),
5550 force,
5551 0,
5552 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005553 } else {
5554 return BAD_VALUE;
5555 }
5556 } else {
5557 return BAD_VALUE;
5558 }
5559 return NO_ERROR;
5560}
5561
5562status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5563 struct audio_patch *patches,
5564 unsigned int *generation)
5565{
François Gaffie53615e22015-03-19 09:24:12 +01005566 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005567 return BAD_VALUE;
5568 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005569 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005570 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005571}
5572
Eric Laurente1715a42014-05-20 11:30:42 -07005573status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005574{
Eric Laurente1715a42014-05-20 11:30:42 -07005575 ALOGV("setAudioPortConfig()");
5576
5577 if (config == NULL) {
5578 return BAD_VALUE;
5579 }
5580 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5581 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005582 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5583 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005584 }
5585
Eric Laurenta121f902014-06-03 13:32:54 -07005586 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005587 if (config->type == AUDIO_PORT_TYPE_MIX) {
5588 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005589 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005590 if (outputDesc == NULL) {
5591 return BAD_VALUE;
5592 }
Eric Laurent84c70242014-06-23 08:46:27 -07005593 ALOG_ASSERT(!outputDesc->isDuplicated(),
5594 "setAudioPortConfig() called on duplicated output %d",
5595 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005596 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005597 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005598 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005599 if (inputDesc == NULL) {
5600 return BAD_VALUE;
5601 }
Eric Laurenta121f902014-06-03 13:32:54 -07005602 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005603 } else {
5604 return BAD_VALUE;
5605 }
5606 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5607 sp<DeviceDescriptor> deviceDesc;
5608 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5609 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5610 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5611 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5612 } else {
5613 return BAD_VALUE;
5614 }
5615 if (deviceDesc == NULL) {
5616 return BAD_VALUE;
5617 }
Eric Laurenta121f902014-06-03 13:32:54 -07005618 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005619 } else {
5620 return BAD_VALUE;
5621 }
5622
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005623 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005624 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5625 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005626 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005627 audioPortConfig->toAudioPortConfig(&newConfig, config);
5628 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005629 }
Eric Laurenta121f902014-06-03 13:32:54 -07005630 if (status != NO_ERROR) {
5631 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005632 }
Eric Laurente1715a42014-05-20 11:30:42 -07005633
5634 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005635}
5636
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005637void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5638{
Eric Laurentd60560a2015-04-10 11:31:20 -07005639 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005640 clearAudioPatches(uid);
5641 clearSessionRoutes(uid);
5642}
5643
Eric Laurent6a94d692014-05-20 11:18:06 -07005644void AudioPolicyManager::clearAudioPatches(uid_t uid)
5645{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005646 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005647 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005648 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005649 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005650 }
5651 }
5652}
5653
François Gaffiec005e562018-11-06 15:04:49 +01005654void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005655{
François Gaffiec005e562018-11-06 15:04:49 +01005656 // Take the first attributes following the product strategy as it is used to retrieve the routed
5657 // device. All attributes wihin a strategy follows the same "routing strategy"
5658 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5659 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005660 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005661 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005662 for (size_t j = 0; j < mOutputs.size(); j++) {
5663 if (mOutputs.keyAt(j) == ouptutToSkip) {
5664 continue;
5665 }
5666 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005667 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005668 continue;
5669 }
5670 // If the default device for this strategy is on another output mix,
5671 // invalidate all tracks in this strategy to force re connection.
5672 // Otherwise select new device on the output mix.
5673 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005674 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005675 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005676 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005677 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005678 // If the device is using preferred mixer attributes, the output need to reopen
5679 // with default configuration when the new selected devices are different from
5680 // current routing devices.
5681 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5682 continue;
5683 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305684 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005685 }
5686 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005687 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005688}
5689
5690void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5691{
5692 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005693 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005694 for (size_t i = 0; i < mOutputs.size(); i++) {
5695 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005696 for (const auto& client : outputDesc->getClientIterable()) {
5697 if (client->hasPreferredDevice() && client->uid() == uid) {
5698 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005699 auto clientStrategy = client->strategy();
5700 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5701 end(affectedStrategies)) {
5702 continue;
5703 }
5704 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005705 }
5706 }
5707 }
5708 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005709 for (const auto& strategy : affectedStrategies) {
5710 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005711 }
5712
5713 // remove input routes associated with this uid
5714 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005715 for (size_t i = 0; i < mInputs.size(); i++) {
5716 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005717 for (const auto& client : inputDesc->getClientIterable()) {
5718 if (client->hasPreferredDevice() && client->uid() == uid) {
5719 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5720 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005721 }
5722 }
5723 }
5724 // reroute inputs if necessary
5725 SortedVector<audio_io_handle_t> inputsToClose;
5726 for (size_t i = 0; i < mInputs.size(); i++) {
5727 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005728 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005729 inputsToClose.add(inputDesc->mIoHandle);
5730 }
5731 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005732 for (const auto& input : inputsToClose) {
5733 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005734 }
5735}
5736
Eric Laurentd60560a2015-04-10 11:31:20 -07005737void AudioPolicyManager::clearAudioSources(uid_t uid)
5738{
5739 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005740 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5741 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005742 stopAudioSource(mAudioSources.keyAt(i));
5743 }
5744 }
5745}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005746
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005747status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5748 audio_io_handle_t *ioHandle,
5749 audio_devices_t *device)
5750{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005751 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5752 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005753 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005754 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5755 if (deviceDesc == nullptr) {
5756 return INVALID_OPERATION;
5757 }
5758 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005759
François Gaffiedf372692015-03-19 10:43:27 +01005760 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005761}
5762
Eric Laurentd60560a2015-04-10 11:31:20 -07005763status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005764 const audio_attributes_t *attributes,
5765 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005766 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005767{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005768 ALOGV("%s", __FUNCTION__);
5769 *portId = AUDIO_PORT_HANDLE_NONE;
5770
5771 if (source == NULL || attributes == NULL || portId == NULL) {
5772 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5773 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005774 return BAD_VALUE;
5775 }
5776
Eric Laurentd60560a2015-04-10 11:31:20 -07005777 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5778 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005779 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5780 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005781 return INVALID_OPERATION;
5782 }
5783
François Gaffie11d30102018-11-02 16:09:09 +01005784 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005785 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005786 String8(source->ext.device.address),
5787 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005788 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005789 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005790 return BAD_VALUE;
5791 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005792
jiabin4ef93452019-09-10 14:29:54 -07005793 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005794
François Gaffieaaac0fd2018-11-22 17:56:39 +01005795 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005796 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005797 mEngine->getStreamTypeForAttributes(*attributes),
5798 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005799 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005800
5801 status_t status = connectAudioSource(sourceDesc);
5802 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005803 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005804 }
5805 return status;
5806}
5807
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005808status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005809{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005810 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005811
5812 // make sure we only have one patch per source.
5813 disconnectAudioSource(sourceDesc);
5814
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005815 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005816 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5817 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5818 sourceDesc->srcDevice()->type(),
5819 String8(sourceDesc->srcDevice()->address().c_str()),
5820 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005821 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005822 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005823 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005824 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005825 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5826 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5827 return INVALID_OPERATION;
5828 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005829 PatchBuilder patchBuilder;
5830 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5831 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005832
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005833 return connectAudioSourceToSink(
5834 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005835}
5836
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005837status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005838{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005839 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5840 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005841 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005842 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005843 return BAD_VALUE;
5844 }
5845 status_t status = disconnectAudioSource(sourceDesc);
5846
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005847 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005848 return status;
5849}
5850
Andy Hung2ddee192015-12-18 17:34:44 -08005851status_t AudioPolicyManager::setMasterMono(bool mono)
5852{
5853 if (mMasterMono == mono) {
5854 return NO_ERROR;
5855 }
5856 mMasterMono = mono;
5857 // if enabling mono we close all offloaded devices, which will invalidate the
5858 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5859 // for recreating the new AudioTrack as non-offloaded PCM.
5860 //
5861 // If disabling mono, we leave all tracks as is: we don't know which clients
5862 // and tracks are able to be recreated as offloaded. The next "song" should
5863 // play back offloaded.
5864 if (mMasterMono) {
5865 Vector<audio_io_handle_t> offloaded;
5866 for (size_t i = 0; i < mOutputs.size(); ++i) {
5867 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5868 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5869 offloaded.push(desc->mIoHandle);
5870 }
5871 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005872 for (const auto& handle : offloaded) {
5873 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005874 }
5875 }
5876 // update master mono for all remaining outputs
5877 for (size_t i = 0; i < mOutputs.size(); ++i) {
5878 updateMono(mOutputs.keyAt(i));
5879 }
5880 return NO_ERROR;
5881}
5882
5883status_t AudioPolicyManager::getMasterMono(bool *mono)
5884{
5885 *mono = mMasterMono;
5886 return NO_ERROR;
5887}
5888
Eric Laurentac9cef52017-06-09 15:46:26 -07005889float AudioPolicyManager::getStreamVolumeDB(
5890 audio_stream_type_t stream, int index, audio_devices_t device)
5891{
jiabin9a3361e2019-10-01 09:38:30 -07005892 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005893}
5894
jiabin81772902018-04-02 17:52:27 -07005895status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5896 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005897 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005898{
Kriti Dang6537def2021-03-02 13:46:59 +01005899 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5900 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005901 return BAD_VALUE;
5902 }
Kriti Dang6537def2021-03-02 13:46:59 +01005903 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5904 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005905
5906 size_t formatsWritten = 0;
5907 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005908
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005909 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005910 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5911 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005912 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005913 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005914 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005915 bool formatEnabled = true;
5916 switch (forceUse) {
5917 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005918 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005919 break;
5920 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5921 formatEnabled = false;
5922 break;
5923 default: // AUTO or ALWAYS => true
5924 break;
jiabin81772902018-04-02 17:52:27 -07005925 }
5926 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5927 }
jiabin81772902018-04-02 17:52:27 -07005928 }
5929 return NO_ERROR;
5930}
5931
Kriti Dang6537def2021-03-02 13:46:59 +01005932status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5933 audio_format_t *surroundFormats) {
5934 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5935 return BAD_VALUE;
5936 }
5937 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5938 __func__, *numSurroundFormats, surroundFormats);
5939
5940 size_t formatsWritten = 0;
5941 size_t formatsMax = *numSurroundFormats;
5942 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5943
5944 // Return formats from all device profiles that have already been resolved by
5945 // checkOutputsForDevice().
5946 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5947 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5948 audio_devices_t deviceType = device->type();
5949 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5950 // returns formats reported by HDMI devices.
5951 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5952 continue;
5953 }
5954 // Formats reported by sink devices
5955 std::unordered_set<audio_format_t> formatset;
5956 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5957 formatset.insert(it->second.begin(), it->second.end());
5958 }
5959
5960 // Formats hard-coded in the in policy configuration file (if any).
5961 FormatVector encodedFormats = device->encodedFormats();
5962 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5963 // Filter the formats which are supported by the vendor hardware.
5964 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005965 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005966 formats.insert(*it);
5967 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005968 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005969 if (pair.second.count(*it) != 0) {
5970 formats.insert(pair.first);
5971 break;
5972 }
5973 }
5974 }
5975 }
5976 }
5977 *numSurroundFormats = formats.size();
5978 for (const auto& format: formats) {
5979 if (formatsWritten < formatsMax) {
5980 surroundFormats[formatsWritten++] = format;
5981 }
5982 }
5983 return NO_ERROR;
5984}
5985
jiabin81772902018-04-02 17:52:27 -07005986status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5987{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005988 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005989 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5990 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005991 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005992 return BAD_VALUE;
5993 }
5994
Mikhail Naganov100f0122018-11-29 11:22:16 -08005995 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5996 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005997 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005998 return INVALID_OPERATION;
5999 }
6000
Mikhail Naganov100f0122018-11-29 11:22:16 -08006001 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006002 return NO_ERROR;
6003 }
6004
Mikhail Naganov100f0122018-11-29 11:22:16 -08006005 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006006 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006007 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006008 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006009 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006010 }
6011 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006012 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006013 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006014 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006015 }
6016 }
6017
6018 sp<SwAudioOutputDescriptor> outputDesc;
6019 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006020 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6021 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006022 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6023 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006024 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006025 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006026 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6027 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6028 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006029 name.c_str(),
6030 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006031 if (status != NO_ERROR) {
6032 continue;
6033 }
6034 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6035 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6036 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006037 name.c_str(),
6038 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006039 profileUpdated |= (status == NO_ERROR);
6040 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006041 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006042 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006043 AUDIO_DEVICE_IN_HDMI);
6044 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6045 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006046 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006047 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006048 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6049 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6050 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006051 name.c_str(),
6052 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006053 if (status != NO_ERROR) {
6054 continue;
6055 }
6056 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6057 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6058 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006059 name.c_str(),
6060 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006061 profileUpdated |= (status == NO_ERROR);
6062 }
6063
jiabin81772902018-04-02 17:52:27 -07006064 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006065 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006066 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006067 }
6068
6069 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6070}
6071
Eric Laurent5ada82e2019-08-29 17:53:54 -07006072void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006073{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006074 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006075 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006076 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006077 }
6078}
6079
jiabin6012f912018-11-02 17:06:30 -07006080bool AudioPolicyManager::isHapticPlaybackSupported()
6081{
6082 for (const auto& hwModule : mHwModules) {
6083 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6084 for (const auto &outProfile : outputProfiles) {
6085 struct audio_port audioPort;
6086 outProfile->toAudioPort(&audioPort);
6087 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6088 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6089 return true;
6090 }
6091 }
6092 }
6093 }
6094 return false;
6095}
6096
Carter Hsu325a8eb2022-01-19 19:56:51 +08006097bool AudioPolicyManager::isUltrasoundSupported()
6098{
6099 bool hasUltrasoundOutput = false;
6100 bool hasUltrasoundInput = false;
6101 for (const auto& hwModule : mHwModules) {
6102 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6103 if (!hasUltrasoundOutput) {
6104 for (const auto &outProfile : outputProfiles) {
6105 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6106 hasUltrasoundOutput = true;
6107 break;
6108 }
6109 }
6110 }
6111
6112 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6113 if (!hasUltrasoundInput) {
6114 for (const auto &inputProfile : inputProfiles) {
6115 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6116 hasUltrasoundInput = true;
6117 break;
6118 }
6119 }
6120 }
6121
6122 if (hasUltrasoundOutput && hasUltrasoundInput)
6123 return true;
6124 }
6125 return false;
6126}
6127
Atneya Nair698f5ef2022-12-15 16:15:09 -08006128bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6129{
6130 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6131 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6132 for (const auto& hwModule : mHwModules) {
6133 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6134 for (const auto &inputProfile : inputProfiles) {
6135 if ((inputProfile->getFlags() & mask) == mask) {
6136 return true;
6137 }
6138 }
6139 }
6140 return false;
6141}
6142
Eric Laurent8340e672019-11-06 11:01:08 -08006143bool AudioPolicyManager::isCallScreenModeSupported()
6144{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006145 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006146}
6147
6148
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006149status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006150{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006151 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006152 if (!sourceDesc->isConnected()) {
6153 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6154 return NO_ERROR;
6155 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006156 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6157 if (swOutput != 0) {
6158 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006159 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006160 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006161 }
jiabinbce0c1d2020-10-05 11:20:18 -07006162 if (releaseOutput(sourceDesc->portId())) {
6163 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6164 // no need to release audio patch here but just return NO_ERROR.
6165 return NO_ERROR;
6166 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006167 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006168 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006169 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006170 // close Hwoutput and remove from mHwOutputs
6171 } else {
6172 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6173 }
6174 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006175 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006176 sourceDesc->disconnect();
6177 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006178}
6179
François Gaffiec005e562018-11-06 15:04:49 +01006180sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6181 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006182{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006183 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006184 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006185 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006186 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006187 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6188 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006189 source = sourceDesc;
6190 break;
6191 }
6192 }
6193 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006194}
6195
Eric Laurentb4f42a92022-01-17 17:37:31 +01006196bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006197 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006198 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006199{
6200 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6201 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006202 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006203 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006204 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6205 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6206 return false;
6207 }
6208 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6209 return false;
6210 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006211 }
6212
Eric Laurentd332bc82023-08-04 11:45:23 +02006213 // The caller can have the audio config criteria ignored by either passing a null ptr or
6214 // the AUDIO_CONFIG_INITIALIZER value.
6215 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006216 // some positional channel masks and PCM format and for stereo if low latency performance
6217 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006218
6219 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006220 static const bool stereo_spatialization_enabled =
6221 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006222 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006223 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006224 ? audio_channel_mask_contains_stereo(config->channel_mask)
6225 : audio_is_channel_mask_spatialized(config->channel_mask);
6226 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006227 return false;
6228 }
6229 if (!audio_is_linear_pcm(config->format)) {
6230 return false;
6231 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006232 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6233 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6234 return false;
6235 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006236 }
6237
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006238 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006239 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006240 if (profile == nullptr) {
6241 return false;
6242 }
6243
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006244 return true;
6245}
6246
Shunkai Yao4c3af932024-04-26 04:12:21 +00006247// The Spatializer output is compatible with Haptic use cases if:
6248// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6249// with client if client haptic channel bits were set, or
6250// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6251// including the haptic bits or creating the HapticGenerator effect for same session.
6252bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6253 const audio_config_t* config, audio_session_t sessionId) const {
6254 const auto clientHapticChannel =
6255 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6256 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6257 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6258
6259 if (threadOutputHapticChannel) {
6260 // check format and sampleRate match if client haptic channel mask exist
6261 if (clientHapticChannel) {
6262 return mSpatializerOutput->getFormat() == config->format &&
6263 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6264 }
6265 return true;
6266 } else {
6267 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6268 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6269 // HapticGenerator effect for this session) are not supported.
6270 return clientHapticChannel == 0 &&
6271 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6272 }
6273}
6274
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006275void AudioPolicyManager::checkVirtualizerClientRoutes() {
6276 std::set<audio_stream_type_t> streamsToInvalidate;
6277 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006278 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6279 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006280 audio_attributes_t attr = client->attributes();
6281 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6282 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6283 audio_config_base_t clientConfig = client->config();
6284 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006285 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006286 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006287 streamsToInvalidate.insert(client->stream());
6288 }
6289 }
6290 }
6291
jiabinc44b3462022-12-08 12:52:31 -08006292 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006293}
6294
Eric Laurente191d1b2022-04-15 11:59:25 +02006295
6296bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6297 const sp<SwAudioOutputDescriptor>& outputDesc) {
6298 if (outputDesc->isDuplicated()) {
6299 return false;
6300 }
6301 DeviceVector devices = outputDesc->supportedDevices();
6302 for (size_t i = 0; i < mOutputs.size(); i++) {
6303 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6304 if (desc == outputDesc || desc->isDuplicated()) {
6305 continue;
6306 }
6307 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6308 if (!sharedDevices.isEmpty()
6309 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6310 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6311 return false;
6312 }
6313 }
6314 return true;
6315}
6316
6317
Eric Laurentfa0f6742021-08-17 18:39:44 +02006318status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006319 const audio_attributes_t *attr,
6320 audio_io_handle_t *output) {
6321 *output = AUDIO_IO_HANDLE_NONE;
6322
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006323 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6324 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6325 audio_config_t *configPtr = nullptr;
6326 audio_config_t config;
6327 if (mixerConfig != nullptr) {
6328 config = audio_config_initializer(mixerConfig);
6329 configPtr = &config;
6330 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006331 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006332 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006333 return BAD_VALUE;
6334 }
6335
6336 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006337 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006338 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006339 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006340 return BAD_VALUE;
6341 }
6342
Eric Laurente191d1b2022-04-15 11:59:25 +02006343 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006344 for (size_t i = 0; i < mOutputs.size(); i++) {
6345 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006346 if (!desc->isDuplicated()
6347 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6348 spatializerOutputs.push_back(desc);
6349 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006350 }
6351 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006352 mSpatializerOutput.clear();
6353 bool outputsChanged = false;
6354 for (const auto& desc : spatializerOutputs) {
6355 if (desc->mProfile == profile
6356 && (configPtr == nullptr
6357 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6358 mSpatializerOutput = desc;
6359 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6360 } else {
6361 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6362 " and devices %s", __func__, desc->mIoHandle,
6363 configPtr != nullptr ? configPtr->channel_mask : 0,
6364 devices.toString().c_str());
6365 closeOutput(desc->mIoHandle);
6366 outputsChanged = true;
6367 }
Eric Laurent39095982021-08-24 18:29:27 +02006368 }
6369
Eric Laurente191d1b2022-04-15 11:59:25 +02006370 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006371 sp<SwAudioOutputDescriptor> desc =
6372 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006373 if (desc != nullptr) {
6374 mSpatializerOutput = desc;
6375 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006376 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006377 }
6378
6379 checkVirtualizerClientRoutes();
6380
Eric Laurente191d1b2022-04-15 11:59:25 +02006381 if (outputsChanged) {
6382 mPreviousOutputs = mOutputs;
6383 mpClientInterface->onAudioPortListUpdate();
6384 }
6385
6386 if (mSpatializerOutput == nullptr) {
6387 ALOGV("%s could not open spatializer output with requested config", __func__);
6388 return BAD_VALUE;
6389 }
Eric Laurent39095982021-08-24 18:29:27 +02006390 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006391 ALOGV("%s returning new spatializer output %d", __func__, *output);
6392 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006393}
6394
Eric Laurentfa0f6742021-08-17 18:39:44 +02006395status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6396 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006397 return INVALID_OPERATION;
6398 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006399 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006400 return BAD_VALUE;
6401 }
Eric Laurent39095982021-08-24 18:29:27 +02006402
Eric Laurente191d1b2022-04-15 11:59:25 +02006403 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6404 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6405 closeOutput(mSpatializerOutput->mIoHandle);
6406 //from now on mSpatializerOutput is null
6407 checkVirtualizerClientRoutes();
6408 }
Eric Laurent39095982021-08-24 18:29:27 +02006409
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006410 return NO_ERROR;
6411}
6412
Eric Laurente552edb2014-03-10 17:42:56 -07006413// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006414// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006415// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006416uint32_t AudioPolicyManager::nextAudioPortGeneration()
6417{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006418 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006419}
6420
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006421AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006422 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006423 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006424 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006425 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006426 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006427 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006428 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006429 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006430 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006431 mAudioPortGeneration(1),
6432 mBeaconMuteRefCount(0),
6433 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006434 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006435 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006436 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006437 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006438{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006439}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006440
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006441status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006442 if (mEngine == nullptr) {
6443 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006444 }
6445 mEngine->setObserver(this);
6446 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006447 if (status != NO_ERROR) {
6448 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6449 return status;
6450 }
François Gaffie2110e042015-03-24 08:41:51 +01006451
jiabin29230182023-04-04 21:02:36 +00006452 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6453 // at the end of this function.
6454 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006455 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6456 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6457
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006458 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006459 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006460 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006461
Eric Laurent3a4311c2014-03-17 12:00:47 -07006462 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006463 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6464 defaultOutputDevice == nullptr ||
6465 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6466 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6467 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006468 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006469 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006470 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006471
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006472 // Silence ALOGV statements
6473 property_set("log.tag." LOG_TAG, "D");
6474
Eric Laurente552edb2014-03-10 17:42:56 -07006475 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006476 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006477}
6478
Eric Laurente0720872014-03-11 09:30:41 -07006479AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006480{
Eric Laurente552edb2014-03-10 17:42:56 -07006481 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006482 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006483 }
6484 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006485 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006486 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006487 mAvailableOutputDevices.clear();
6488 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006489 mOutputs.clear();
6490 mInputs.clear();
6491 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006492 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006493 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006494}
6495
Eric Laurente0720872014-03-11 09:30:41 -07006496status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006497{
Eric Laurent87ffa392015-05-22 10:32:38 -07006498 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006499}
6500
Eric Laurente552edb2014-03-10 17:42:56 -07006501// ---
6502
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006503void AudioPolicyManager::onNewAudioModulesAvailable()
6504{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006505 DeviceVector newDevices;
6506 onNewAudioModulesAvailableInt(&newDevices);
6507 if (!newDevices.empty()) {
6508 nextAudioPortGeneration();
6509 mpClientInterface->onAudioPortListUpdate();
6510 }
6511}
6512
6513void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6514{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006515 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006516 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6517 continue;
6518 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006519 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006520 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6521 handle != AUDIO_MODULE_HANDLE_NONE) {
6522 hwModule->setHandle(handle);
6523 } else {
6524 ALOGW("could not load HW module %s", hwModule->getName());
6525 continue;
6526 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006527 }
6528 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006529 // open all output streams needed to access attached devices.
6530 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006531 // This also validates mAvailableOutputDevices list
6532 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6533 if (!outProfile->canOpenNewIo()) {
6534 ALOGE("Invalid Output profile max open count %u for profile %s",
6535 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6536 continue;
6537 }
6538 if (!outProfile->hasSupportedDevices()) {
6539 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6540 continue;
6541 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006542 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6543 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006544 mTtsOutputAvailable = true;
6545 }
6546
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006547 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006548 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006549 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006550 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6551 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006552 } else {
6553 // choose first device present in profile's SupportedDevices also part of
6554 // mAvailableOutputDevices.
6555 if (availProfileDevices.isEmpty()) {
6556 continue;
6557 }
6558 supportedDevice = availProfileDevices.itemAt(0);
6559 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006560 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006561 continue;
6562 }
6563 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6564 mpClientInterface);
6565 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006566 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6567 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006568 AUDIO_STREAM_DEFAULT,
6569 AUDIO_OUTPUT_FLAG_NONE, &output);
6570 if (status != NO_ERROR) {
6571 ALOGW("Cannot open output stream for devices %s on hw module %s",
6572 supportedDevice->toString().c_str(), hwModule->getName());
6573 continue;
6574 }
6575 for (const auto &device : availProfileDevices) {
6576 // give a valid ID to an attached device once confirmed it is reachable
6577 if (!device->isAttached()) {
6578 device->attach(hwModule);
6579 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006580 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006581 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006582 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6583 }
6584 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006585 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006586 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6587 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006588 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006589 }
Eric Laurent39095982021-08-24 18:29:27 +02006590 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006591 outputDesc->close();
6592 } else {
6593 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306594 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006595 DeviceVector(supportedDevice),
6596 true,
6597 0,
6598 NULL);
6599 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006600 }
6601 // open input streams needed to access attached devices to validate
6602 // mAvailableInputDevices list
6603 for (const auto& inProfile : hwModule->getInputProfiles()) {
6604 if (!inProfile->canOpenNewIo()) {
6605 ALOGE("Invalid Input profile max open count %u for profile %s",
6606 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6607 continue;
6608 }
6609 if (!inProfile->hasSupportedDevices()) {
6610 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6611 continue;
6612 }
6613 // chose first device present in profile's SupportedDevices also part of
6614 // available input devices
6615 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006616 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006617 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006618 ALOGV("%s: Input device list is empty! for profile %s",
6619 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006620 continue;
6621 }
6622 sp<AudioInputDescriptor> inputDesc =
6623 new AudioInputDescriptor(inProfile, mpClientInterface);
6624
6625 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6626 status_t status = inputDesc->open(nullptr,
6627 availProfileDevices.itemAt(0),
6628 AUDIO_SOURCE_MIC,
6629 AUDIO_INPUT_FLAG_NONE,
6630 &input);
6631 if (status != NO_ERROR) {
6632 ALOGW("Cannot open input stream for device %s on hw module %s",
6633 availProfileDevices.toString().c_str(),
6634 hwModule->getName());
6635 continue;
6636 }
6637 for (const auto &device : availProfileDevices) {
6638 // give a valid ID to an attached device once confirmed it is reachable
6639 if (!device->isAttached()) {
6640 device->attach(hwModule);
6641 device->importAudioPortAndPickAudioProfile(inProfile, true);
6642 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006643 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006644 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6645 }
6646 }
6647 inputDesc->close();
6648 }
6649 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006650
6651 // Check if spatializer outputs can be closed until used.
6652 // mOutputs vector never contains duplicated outputs at this point.
6653 std::vector<audio_io_handle_t> outputsClosed;
6654 for (size_t i = 0; i < mOutputs.size(); i++) {
6655 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6656 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6657 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6658 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006659 nextAudioPortGeneration();
6660 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6661 if (index >= 0) {
6662 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6663 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6664 patchDesc->getAfHandle(), 0);
6665 mAudioPatches.removeItemsAt(index);
6666 mpClientInterface->onAudioPatchListUpdate();
6667 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006668 desc->close();
6669 }
6670 }
6671 for (auto output : outputsClosed) {
6672 removeOutput(output);
6673 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006674}
6675
Eric Laurent98e38192018-02-15 18:31:53 -08006676void AudioPolicyManager::addOutput(audio_io_handle_t output,
6677 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006678{
Eric Laurent1c333e22014-05-20 10:48:17 -07006679 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006680 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006681 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006682 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006683 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006684}
6685
François Gaffie53615e22015-03-19 09:24:12 +01006686void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6687{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006688 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6689 ALOGV("%s: removing primary output", __func__);
6690 mPrimaryOutput = nullptr;
6691 }
François Gaffie53615e22015-03-19 09:24:12 +01006692 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006693 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006694}
6695
Eric Laurent98e38192018-02-15 18:31:53 -08006696void AudioPolicyManager::addInput(audio_io_handle_t input,
6697 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006698{
Eric Laurent1c333e22014-05-20 10:48:17 -07006699 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006700 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006701}
Eric Laurente552edb2014-03-10 17:42:56 -07006702
François Gaffie11d30102018-11-02 16:09:09 +01006703status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006704 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006705 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006706{
François Gaffie11d30102018-11-02 16:09:09 +01006707 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006708 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006709 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006710
François Gaffie11d30102018-11-02 16:09:09 +01006711 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006712 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006713 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006714 }
Eric Laurente552edb2014-03-10 17:42:56 -07006715
Eric Laurent3b73df72014-03-11 09:06:29 -07006716 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006717 // first call getAudioPort to get the supported attributes from the HAL
6718 struct audio_port_v7 port = {};
6719 device->toAudioPort(&port);
6720 status_t status = mpClientInterface->getAudioPort(&port);
6721 if (status == NO_ERROR) {
6722 device->importAudioPort(port);
6723 }
6724
6725 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006726 for (size_t i = 0; i < mOutputs.size(); i++) {
6727 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006728 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006729 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006730 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6731 mOutputs.keyAt(i), device->toString().c_str());
6732 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006733 }
6734 }
6735 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006736 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006737 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006738 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6739 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006740 if (profile->supportsDevice(device)) {
6741 profiles.add(profile);
6742 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6743 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006744 }
6745 }
6746 }
6747
Eric Laurent7b279bb2015-12-14 10:18:23 -08006748 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006749
Eric Laurente552edb2014-03-10 17:42:56 -07006750 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006751 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006752 return BAD_VALUE;
6753 }
6754
6755 // open outputs for matching profiles if needed. Direct outputs are also opened to
6756 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6757 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006758 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006759
6760 // nothing to do if one output is already opened for this profile
6761 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006762 for (j = 0; j < outputs.size(); j++) {
6763 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006764 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006765 // matching profile: save the sample rates, format and channel masks supported
6766 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006767 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006768 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006769 }
Eric Laurente552edb2014-03-10 17:42:56 -07006770 break;
6771 }
6772 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006773 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006774 continue;
6775 }
6776
Eric Laurent3974e3b2017-12-07 17:58:43 -08006777 if (!profile->canOpenNewIo()) {
6778 ALOGW("Max Output number %u already opened for this profile %s",
6779 profile->maxOpenCount, profile->getTagName().c_str());
6780 continue;
6781 }
6782
Eric Laurent83efe1c2017-07-09 16:51:08 -07006783 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006784 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006785 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6786 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006787 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006788 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006789 profiles.removeAt(profile_index);
6790 profile_index--;
6791 } else {
6792 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006793 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006794 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006795 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6796 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006797 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006798 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006799
François Gaffie11d30102018-11-02 16:09:09 +01006800 if (device_distinguishes_on_address(deviceType)) {
6801 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6802 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306803 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6804 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006805 }
Eric Laurente552edb2014-03-10 17:42:56 -07006806 ALOGV("checkOutputsForDevice(): adding output %d", output);
6807 }
6808 }
6809
6810 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006811 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006812 return BAD_VALUE;
6813 }
Eric Laurentd4692962014-05-05 18:13:44 -07006814 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006815 // check if one opened output is not needed any more after disconnecting one device
6816 for (size_t i = 0; i < mOutputs.size(); i++) {
6817 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006818 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006819 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006820 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006821 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006822 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006823 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006824 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6825 mOutputs.keyAt(i));
6826 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006827 }
Eric Laurente552edb2014-03-10 17:42:56 -07006828 }
6829 }
Eric Laurentd4692962014-05-05 18:13:44 -07006830 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006831 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006832 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6833 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006834 if (!profile->supportsDevice(device)) {
6835 continue;
6836 }
6837 ALOGV("checkOutputsForDevice(): "
6838 "clearing direct output profile %zu on module %s",
6839 j, hwModule->getName());
6840 profile->clearAudioProfiles();
6841 if (!profile->hasDynamicAudioProfile()) {
6842 continue;
6843 }
6844 // When a device is disconnected, if there is an IOProfile that contains dynamic
6845 // profiles and supports the disconnected device, call getAudioPort to repopulate
6846 // the capabilities of the devices that is supported by the IOProfile.
6847 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6848 if (supportedDevice == device ||
6849 !mAvailableOutputDevices.contains(supportedDevice)) {
6850 continue;
6851 }
6852 struct audio_port_v7 port;
6853 supportedDevice->toAudioPort(&port);
6854 status_t status = mpClientInterface->getAudioPort(&port);
6855 if (status == NO_ERROR) {
6856 supportedDevice->importAudioPort(port);
6857 }
Eric Laurente552edb2014-03-10 17:42:56 -07006858 }
6859 }
6860 }
6861 }
6862 return NO_ERROR;
6863}
6864
François Gaffie11d30102018-11-02 16:09:09 +01006865status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006866 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006867{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006868 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006869
François Gaffie11d30102018-11-02 16:09:09 +01006870 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006871 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006872 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006873 }
6874
Eric Laurentd4692962014-05-05 18:13:44 -07006875 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006876 // first call getAudioPort to get the supported attributes from the HAL
6877 struct audio_port_v7 port = {};
6878 device->toAudioPort(&port);
6879 status_t status = mpClientInterface->getAudioPort(&port);
6880 if (status == NO_ERROR) {
6881 device->importAudioPort(port);
6882 }
6883
Eric Laurent0dd51852019-04-19 18:18:58 -07006884 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006885 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006886 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006887 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006888 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006889 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006890 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006891
François Gaffie11d30102018-11-02 16:09:09 +01006892 if (profile->supportsDevice(device)) {
6893 profiles.add(profile);
6894 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6895 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006896 }
6897 }
6898 }
6899
Eric Laurent0dd51852019-04-19 18:18:58 -07006900 if (profiles.isEmpty()) {
6901 ALOGW("%s: No input profile available for device %s",
6902 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006903 return BAD_VALUE;
6904 }
6905
6906 // open inputs for matching profiles if needed. Direct inputs are also opened to
6907 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6908 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6909
Eric Laurent1c333e22014-05-20 10:48:17 -07006910 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006911
Eric Laurentd4692962014-05-05 18:13:44 -07006912 // nothing to do if one input is already opened for this profile
6913 size_t input_index;
6914 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6915 desc = mInputs.valueAt(input_index);
6916 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006917 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006918 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006919 }
Eric Laurentd4692962014-05-05 18:13:44 -07006920 break;
6921 }
6922 }
6923 if (input_index != mInputs.size()) {
6924 continue;
6925 }
6926
Eric Laurent3974e3b2017-12-07 17:58:43 -08006927 if (!profile->canOpenNewIo()) {
6928 ALOGW("Max Input number %u already opened for this profile %s",
6929 profile->maxOpenCount, profile->getTagName().c_str());
6930 continue;
6931 }
6932
Eric Laurentfe231122017-11-17 17:48:06 -08006933 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006934 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006935 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006936
Eric Laurentcf2c0212014-07-25 16:20:43 -07006937 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006938 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006939 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006940 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006941 mpClientInterface->setParameters(input, String8(param));
6942 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006943 }
jiabin12537fc2023-10-12 17:56:08 +00006944 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006945 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006946 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006947 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006948 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006949 }
6950
Eric Laurent0dd51852019-04-19 18:18:58 -07006951 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006952 addInput(input, desc);
6953 }
6954 } // endif input != 0
6955
Eric Laurentcf2c0212014-07-25 16:20:43 -07006956 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006957 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006958 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006959 profiles.removeAt(profile_index);
6960 profile_index--;
6961 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006962 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006963 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006964 }
Eric Laurentd4692962014-05-05 18:13:44 -07006965 ALOGV("checkInputsForDevice(): adding input %d", input);
6966 }
6967 } // end scan profiles
6968
6969 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006970 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006971 return BAD_VALUE;
6972 }
6973 } else {
6974 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006975 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006976 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006977 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006978 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006979 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006980 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006981 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006982 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6983 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006984 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006985 }
6986 }
6987 }
6988 } // end disconnect
6989
6990 return NO_ERROR;
6991}
6992
6993
Eric Laurente0720872014-03-11 09:30:41 -07006994void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006995{
6996 ALOGV("closeOutput(%d)", output);
6997
François Gaffie1c878552018-11-22 16:53:21 +01006998 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6999 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007000 ALOGW("closeOutput() unknown output %d", output);
7001 return;
7002 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007003 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007004 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007005
Eric Laurente552edb2014-03-10 17:42:56 -07007006 // look for duplicated outputs connected to the output being removed.
7007 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007008 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7009 if (dupOutput->isDuplicated() &&
7010 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7011 sp<SwAudioOutputDescriptor> remainingOutput =
7012 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007013 // As all active tracks on duplicated output will be deleted,
7014 // and as they were also referenced on the other output, the reference
7015 // count for their stream type must be adjusted accordingly on
7016 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007017 const bool wasActive = remainingOutput->isActive();
7018 // Note: no-op on the closing output where all clients has already been set inactive
7019 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007020 // stop() will be a no op if the output is still active but is needed in case all
7021 // active streams refcounts where cleared above
7022 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007023 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007024 }
Eric Laurente552edb2014-03-10 17:42:56 -07007025 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7026 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7027
7028 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007029 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007030 }
7031 }
7032
Eric Laurent05b90f82014-08-27 15:32:29 -07007033 nextAudioPortGeneration();
7034
François Gaffie1c878552018-11-22 16:53:21 +01007035 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007036 if (index >= 0) {
7037 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007038 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7039 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007040 mAudioPatches.removeItemsAt(index);
7041 mpClientInterface->onAudioPatchListUpdate();
7042 }
7043
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007044 if (closingOutputWasActive) {
7045 closingOutput->stop();
7046 }
François Gaffie1c878552018-11-22 16:53:21 +01007047 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007048 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007049 for (const auto device : closingOutput->devices()) {
7050 device->setPreferredConfig(nullptr);
7051 }
7052 }
Eric Laurente552edb2014-03-10 17:42:56 -07007053
François Gaffie53615e22015-03-19 09:24:12 +01007054 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007055 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007056 if (closingOutput == mSpatializerOutput) {
7057 mSpatializerOutput.clear();
7058 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007059
7060 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7061 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007062 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007063 bool directOutputOpen = false;
7064 for (size_t i = 0; i < mOutputs.size(); i++) {
7065 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7066 directOutputOpen = true;
7067 break;
7068 }
7069 }
7070 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007071 ALOGV("no direct outputs open, reset MSD patches");
7072 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7073 // how output devices for patching are resolved. Avoid by caching and reusing the
7074 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7075 // devices to patch to. This may be complicated by the fact that devices may become
7076 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007077 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007078 }
7079 }
jiabin220eea12024-05-17 17:55:20 +00007080
7081 if (closingOutput->mPreferredAttrInfo != nullptr) {
7082 closingOutput->mPreferredAttrInfo->resetActiveClient();
7083 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007084}
7085
7086void AudioPolicyManager::closeInput(audio_io_handle_t input)
7087{
7088 ALOGV("closeInput(%d)", input);
7089
7090 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7091 if (inputDesc == NULL) {
7092 ALOGW("closeInput() unknown input %d", input);
7093 return;
7094 }
7095
Eric Laurent6a94d692014-05-20 11:18:06 -07007096 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007097
François Gaffie11d30102018-11-02 16:09:09 +01007098 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007099 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007100 if (index >= 0) {
7101 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007102 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7103 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007104 mAudioPatches.removeItemsAt(index);
7105 mpClientInterface->onAudioPatchListUpdate();
7106 }
7107
François Gaffie6ebbce02023-07-19 13:27:53 +02007108 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007109 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007110 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007111
François Gaffie11d30102018-11-02 16:09:09 +01007112 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7113 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007114 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007115 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007116 }
Eric Laurente552edb2014-03-10 17:42:56 -07007117}
7118
François Gaffie11d30102018-11-02 16:09:09 +01007119SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7120 const DeviceVector &devices,
7121 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007122{
7123 SortedVector<audio_io_handle_t> outputs;
7124
François Gaffie11d30102018-11-02 16:09:09 +01007125 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007126 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007127 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007128 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007129 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007130 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007131 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007132 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007133 outputs.add(openOutputs.keyAt(i));
7134 }
7135 }
7136 return outputs;
7137}
7138
Mikhail Naganov37977152018-07-11 15:54:44 -07007139void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7140{
7141 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7142 // output is suspended before any tracks are moved to it
7143 checkA2dpSuspend();
7144 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007145 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007146 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007147 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007148 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007149 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7150 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7151 // configuration changes will ultimately be rerouted correctly. We can still avoid
7152 // unnecessary rerouting by caching and reusing the arguments to
7153 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7154 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007155 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007156 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007157 // an event that changed routing likely occurred, inform upper layers
7158 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007159}
7160
François Gaffiec005e562018-11-06 15:04:49 +01007161bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7162 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007163{
François Gaffiec005e562018-11-06 15:04:49 +01007164 return mEngine->getProductStrategyForAttributes(lAttr) ==
7165 mEngine->getProductStrategyForAttributes(rAttr);
7166}
7167
Francois Gaffieff1eb522020-05-06 18:37:04 +02007168void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7169{
7170 for (size_t i = 0; i < mAudioSources.size(); i++) {
7171 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7172 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007173 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007174 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007175 connectAudioSource(sourceDesc);
7176 }
7177 }
7178}
7179
7180void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7181{
7182 for (size_t i = 0; i < mAudioSources.size(); i++) {
7183 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7184 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7185 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7186 disconnectAudioSource(sourceDesc);
7187 }
7188 }
7189}
7190
François Gaffiec005e562018-11-06 15:04:49 +01007191void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7192{
7193 auto psId = mEngine->getProductStrategyForAttributes(attr);
7194
7195 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7196 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007197
François Gaffie11d30102018-11-02 16:09:09 +01007198 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7199 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007200
Eric Laurentc209fe42020-06-05 18:11:23 -07007201 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007202 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007203 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007204 // take into account dynamic audio policies related changes: if a client is now associated
7205 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007206 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007207 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7208 if (desc->isDuplicated()) {
7209 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007210 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007211 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7212 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7213 continue;
7214 }
7215 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007216 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007217 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7218 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7219 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007220 if (status != OK) {
7221 continue;
7222 }
yucliuf4de36d2020-09-14 14:57:56 -07007223 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007224 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007225 maxLatency = desc->latency();
7226 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007227 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007228 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007229 }
7230 }
7231
Eric Laurent56ed8842022-11-15 16:04:41 +01007232 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007233 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7234 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007235 for (audio_io_handle_t srcOut : srcOutputs) {
7236 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007237 if (desc == nullptr) continue;
7238
7239 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007240 maxLatency = desc->latency();
7241 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007242
Eric Laurent56ed8842022-11-15 16:04:41 +01007243 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007244 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007245 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007246 // a client on a non direct outputs has necessarily a linear PCM format
7247 // so we can call selectOutput() safely
7248 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7249 client->flags(),
7250 client->config().format,
7251 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007252 client->config().sample_rate,
7253 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007254 if (newOutput != srcOut) {
7255 invalidate = true;
7256 break;
7257 }
7258 } else {
7259 sp<IOProfile> profile = getProfileForOutput(newDevices,
7260 client->config().sample_rate,
7261 client->config().format,
7262 client->config().channel_mask,
7263 client->flags(),
7264 true /* directOnly */);
7265 if (profile != desc->mProfile) {
7266 invalidate = true;
7267 break;
7268 }
7269 }
7270 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007271 // mute strategy while moving tracks from one output to another
7272 if (invalidate) {
7273 invalidatedOutputs.push_back(desc);
7274 if (desc->isStrategyActive(psId)) {
7275 setStrategyMute(psId, true, desc);
7276 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7277 newDevices.types());
7278 }
Eric Laurente552edb2014-03-10 17:42:56 -07007279 }
François Gaffiec005e562018-11-06 15:04:49 +01007280 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007281 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007282 connectAudioSource(source);
7283 }
Eric Laurente552edb2014-03-10 17:42:56 -07007284 }
7285
Eric Laurent56ed8842022-11-15 16:04:41 +01007286 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7287 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7288 std::to_string(srcOutputs[0]).c_str(),
7289 std::to_string(dstOutputs[0]).c_str());
7290
François Gaffiec005e562018-11-06 15:04:49 +01007291 // Move effects associated to this stream from previous output to new output
7292 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007293 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007294 }
François Gaffiec005e562018-11-06 15:04:49 +01007295 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007296 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007297 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007298 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007299 desc->setTracksInvalidatedStatusByStrategy(psId);
7300 }
Eric Laurente552edb2014-03-10 17:42:56 -07007301 }
7302 }
7303}
7304
Eric Laurente0720872014-03-11 09:30:41 -07007305void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007306{
François Gaffiec005e562018-11-06 15:04:49 +01007307 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7308 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7309 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007310 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007311 }
Eric Laurente552edb2014-03-10 17:42:56 -07007312}
7313
Kevin Rocard153f92d2018-12-18 18:33:28 -08007314void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007315 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007316 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007317 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007318 for (size_t i = 0; i < mOutputs.size(); i++) {
7319 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7320 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007321 sp<AudioPolicyMix> primaryMix;
7322 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007323 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007324 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7325 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7326 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007327 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7328 for (auto &secondaryMix : secondaryMixes) {
7329 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7330 if (outputDesc != nullptr &&
7331 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7332 secondaryDescs.push_back(outputDesc);
7333 }
7334 }
7335
jiabinc44b3462022-12-08 12:52:31 -08007336 if (status != OK &&
7337 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7338 // When it failed to query secondary output, only invalidate the client that is not
7339 // MMAP. The reason is that MMAP stream will not support secondary output.
7340 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007341 } else if (!std::equal(
7342 client->getSecondaryOutputs().begin(),
7343 client->getSecondaryOutputs().end(),
7344 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007345 if (!audio_is_linear_pcm(client->config().format)) {
7346 // If the format is not PCM, the tracks should be invalidated to get correct
7347 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007348 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007349 } else {
7350 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7351 std::vector<audio_io_handle_t> secondaryOutputIds;
7352 for (const auto &secondaryDesc: secondaryDescs) {
7353 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7354 weakSecondaryDescs.push_back(secondaryDesc);
7355 }
7356 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7357 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007358 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007359 }
7360 }
7361 }
jiabin10a03f12021-05-07 23:46:28 +00007362 if (!trackSecondaryOutputs.empty()) {
7363 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7364 }
jiabinc44b3462022-12-08 12:52:31 -08007365 if (!clientsToInvalidate.empty()) {
7366 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7367 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007368 }
7369}
7370
Eric Laurent2517af32020-11-25 15:31:27 +01007371bool AudioPolicyManager::isScoRequestedForComm() const {
7372 AudioDeviceTypeAddrVector devices;
7373 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7374 for (const auto &device : devices) {
7375 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7376 return true;
7377 }
7378 }
7379 return false;
7380}
7381
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007382bool AudioPolicyManager::isHearingAidUsedForComm() const {
7383 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7384 true /*fromCache*/);
7385 for (const auto &device : devices) {
7386 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7387 return true;
7388 }
7389 }
7390 return false;
7391}
7392
7393
Eric Laurente0720872014-03-11 09:30:41 -07007394void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007395{
François Gaffie53615e22015-03-19 09:24:12 +01007396 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007397 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007398 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007399 return;
7400 }
7401
Eric Laurent3a4311c2014-03-17 12:00:47 -07007402 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007403 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7404 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007405 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007406
7407 // if suspended, restore A2DP output if:
7408 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007409 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007410 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007411 //
Eric Laurentf732e072016-08-03 19:30:28 -07007412 // if not suspended, suspend A2DP output if:
7413 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007414 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007415 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007416 //
7417 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007418 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007419 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007420 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007421 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007422
7423 mpClientInterface->restoreOutput(a2dpOutput);
7424 mA2dpSuspended = false;
7425 }
7426 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007427 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007428 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007429 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007430 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007431
7432 mpClientInterface->suspendOutput(a2dpOutput);
7433 mA2dpSuspended = true;
7434 }
7435 }
7436}
7437
François Gaffie11d30102018-11-02 16:09:09 +01007438DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7439 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007440{
François Gaffiedb1755b2023-09-01 11:50:35 +02007441 if (outputDesc == nullptr) {
7442 return DeviceVector{};
7443 }
François Gaffie11d30102018-11-02 16:09:09 +01007444
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007445 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007446 if (index >= 0) {
7447 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007448 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007449 ALOGV("%s device %s forced by patch %d", __func__,
7450 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7451 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007452 }
7453 }
7454
Dean Wheatley514b4312020-06-17 21:45:00 +10007455 // Do not retrieve engine device for outputs through MSD
7456 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7457 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7458 return outputDesc->devices();
7459 }
7460
Eric Laurent97ac8712018-07-27 18:59:02 -07007461 // Honor explicit routing requests only if no client using default routing is active on this
7462 // input: a specific app can not force routing for other apps by setting a preferred device.
7463 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007464 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007465 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007466 if (device != nullptr) {
7467 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007468 }
7469
François Gaffiea807ef92018-11-05 10:44:33 +01007470 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7471 // of setForceUse / Default Bus device here
7472 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7473 if (device != nullptr) {
7474 return DeviceVector(device);
7475 }
7476
François Gaffiedb1755b2023-09-01 11:50:35 +02007477 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007478 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7479 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307480 auto hasStreamActive = [&](auto stream) {
7481 return hasStream(streams, stream) && isStreamActive(stream, 0);
7482 };
Eric Laurent484e9272018-06-07 17:29:23 -07007483
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307484 auto doGetOutputDevicesForVoice = [&]() {
7485 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007486 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307487 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007488 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7489 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307490 };
7491
7492 // With low-latency playing on speaker, music on WFD, when the first low-latency
7493 // output is stopped, getNewOutputDevices checks for a product strategy
7494 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007495 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307496 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7497 // stream is associated to the output descriptor.
7498 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7499 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7500 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7501 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007502 // Retrieval of devices for voice DL is done on primary output profile, cannot
7503 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007504 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007505 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7506 break;
7507 }
Eric Laurente552edb2014-03-10 17:42:56 -07007508 }
François Gaffiec005e562018-11-06 15:04:49 +01007509 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007510 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007511}
7512
François Gaffie11d30102018-11-02 16:09:09 +01007513sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7514 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007515{
François Gaffie11d30102018-11-02 16:09:09 +01007516 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007517
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007518 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007519 if (index >= 0) {
7520 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007521 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007522 ALOGV("getNewInputDevice() device %s forced by patch %d",
7523 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7524 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007525 }
7526 }
7527
Eric Laurent97ac8712018-07-27 18:59:02 -07007528 // Honor explicit routing requests only if no client using default routing is active on this
7529 // input: a specific app can not force routing for other apps by setting a preferred device.
7530 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007531 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7532 if (device != nullptr) {
7533 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007534 }
7535
Eric Laurentdc95a252018-04-12 12:46:56 -07007536 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007537 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007538 audio_attributes_t attributes;
7539 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007540 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007541 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7542 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007543 attributes = topClient->attributes();
7544 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007545 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007546 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007547 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7548 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007549 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007550 }
7551
Francois Gaffie716e1432019-01-14 16:58:59 +01007552 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7553 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007554 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007555 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007556 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007557 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007558
Eric Laurente552edb2014-03-10 17:42:56 -07007559 return device;
7560}
7561
Eric Laurent794fde22016-03-11 09:50:45 -08007562bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7563 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007564 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007565}
7566
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007567status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007568 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007569 if (devices == nullptr) {
7570 return BAD_VALUE;
7571 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007572
Andy Hung6d23c0f2022-02-16 09:37:15 -08007573 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007574 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7575 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007576 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007577 for (const auto& device : curDevices) {
7578 devices->push_back(device->getDeviceTypeAddr());
7579 }
7580 return NO_ERROR;
7581}
7582
Eric Laurente0720872014-03-11 09:30:41 -07007583void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007584 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007585 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007586 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007587 updateDevicesAndOutputs();
7588 break;
7589 default:
7590 break;
7591 }
7592}
7593
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007594uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007595
7596 // skip beacon mute management if a dedicated TTS output is available
7597 if (mTtsOutputAvailable) {
7598 return 0;
7599 }
7600
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007601 switch(event) {
7602 case STARTING_OUTPUT:
7603 mBeaconMuteRefCount++;
7604 break;
7605 case STOPPING_OUTPUT:
7606 if (mBeaconMuteRefCount > 0) {
7607 mBeaconMuteRefCount--;
7608 }
7609 break;
7610 case STARTING_BEACON:
7611 mBeaconPlayingRefCount++;
7612 break;
7613 case STOPPING_BEACON:
7614 if (mBeaconPlayingRefCount > 0) {
7615 mBeaconPlayingRefCount--;
7616 }
7617 break;
7618 }
7619
7620 if (mBeaconMuteRefCount > 0) {
7621 // any playback causes beacon to be muted
7622 return setBeaconMute(true);
7623 } else {
7624 // no other playback: unmute when beacon starts playing, mute when it stops
7625 return setBeaconMute(mBeaconPlayingRefCount == 0);
7626 }
7627}
7628
7629uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7630 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7631 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7632 // keep track of muted state to avoid repeating mute/unmute operations
7633 if (mBeaconMuted != mute) {
7634 // mute/unmute AUDIO_STREAM_TTS on all outputs
7635 ALOGV("\t muting %d", mute);
7636 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007637 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7638 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7639 ALOGV("\t no tts volume source available");
7640 return 0;
7641 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007642 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007643 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007644 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007645 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007646 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007647 maxLatency = latency;
7648 }
7649 }
7650 mBeaconMuted = mute;
7651 return maxLatency;
7652 }
7653 return 0;
7654}
7655
Eric Laurente0720872014-03-11 09:30:41 -07007656void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007657{
François Gaffiec005e562018-11-06 15:04:49 +01007658 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007659 mPreviousOutputs = mOutputs;
7660}
7661
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007662uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007663 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007664 uint32_t delayMs)
7665{
7666 // mute/unmute strategies using an incompatible device combination
7667 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7668 // if unmuting, unmute only after the specified delay
7669 if (outputDesc->isDuplicated()) {
7670 return 0;
7671 }
7672
7673 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007674 DeviceVector devices = outputDesc->devices();
7675 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007676
François Gaffiec005e562018-11-06 15:04:49 +01007677 auto productStrategies = mEngine->getOrderedProductStrategies();
7678 for (const auto &productStrategy : productStrategies) {
7679 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7680 DeviceVector curDevices =
7681 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7682 curDevices = curDevices.filter(outputDesc->supportedDevices());
7683 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007684 bool doMute = false;
7685
François Gaffiec005e562018-11-06 15:04:49 +01007686 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007687 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007688 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7689 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007690 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007691 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007692 }
Eric Laurent99401132014-05-07 19:48:15 -07007693 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007694 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007695 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007696 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007697 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007698 continue;
7699 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307700 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007701 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7702 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7703 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007704 if (mute) {
7705 // FIXME: should not need to double latency if volume could be applied
7706 // immediately by the audioflinger mixer. We must account for the delay
7707 // between now and the next time the audioflinger thread for this output
7708 // will process a buffer (which corresponds to one buffer size,
7709 // usually 1/2 or 1/4 of the latency).
7710 if (muteWaitMs < desc->latency() * 2) {
7711 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007712 }
7713 }
7714 }
7715 }
7716 }
7717 }
7718
Eric Laurent99401132014-05-07 19:48:15 -07007719 // temporary mute output if device selection changes to avoid volume bursts due to
7720 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007721 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007722 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007723
Eric Laurentdc462862016-07-19 12:29:53 -07007724 if (muteWaitMs < tempMuteWaitMs) {
7725 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007726 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007727
7728 // If recommended duration is defined, replace temporary mute duration to avoid
7729 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7730 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7731 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7732 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7733 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7734
François Gaffieaaac0fd2018-11-22 17:56:39 +01007735 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7736 // make sure that we do not start the temporary mute period too early in case of
7737 // delayed device change
7738 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7739 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007740 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007741 }
7742 }
7743
Eric Laurente552edb2014-03-10 17:42:56 -07007744 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7745 if (muteWaitMs > delayMs) {
7746 muteWaitMs -= delayMs;
7747 usleep(muteWaitMs * 1000);
7748 return muteWaitMs;
7749 }
7750 return 0;
7751}
7752
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307753uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7754 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007755 const DeviceVector &devices,
7756 bool force,
7757 int delayMs,
7758 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007759 bool requiresMuteCheck, bool requiresVolumeCheck,
7760 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007761{
jiabin3ff8d7d2022-12-13 06:27:44 +00007762 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307763 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7764 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7765 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007766 uint32_t muteWaitMs;
7767
7768 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307769 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007770 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307771 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007772 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007773 return muteWaitMs;
7774 }
Eric Laurente552edb2014-03-10 17:42:56 -07007775
7776 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007777 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007778 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007779 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007780
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307781 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7782 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007783
7784 if (!filteredDevices.isEmpty()) {
7785 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007786 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007787
7788 // if the outputs are not materially active, there is no need to mute.
7789 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007790 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007791 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307792 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7793 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007794 muteWaitMs = 0;
7795 }
Eric Laurente552edb2014-03-10 17:42:56 -07007796
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007797 bool outputRouted = outputDesc->isRouted();
7798
Eric Laurent79ea9582020-06-11 18:49:24 -07007799 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7800 // output profile or if new device is not supported AND previous device(s) is(are) still
7801 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007802 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307803 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7804 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007805 // restore previous device after evaluating strategy mute state
7806 outputDesc->setDevices(prevDevices);
7807 return muteWaitMs;
7808 }
7809
Eric Laurente552edb2014-03-10 17:42:56 -07007810 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007811 // the requested device is AUDIO_DEVICE_NONE
7812 // OR the requested device is the same as current device
7813 // AND force is not specified
7814 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007815 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007816 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307817 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7818 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7819 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007820 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307821 ALOGV("%s %s setting same device on routed output, force apply volumes",
7822 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007823 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7824 }
Eric Laurente552edb2014-03-10 17:42:56 -07007825 return muteWaitMs;
7826 }
7827
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307828 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7829 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007830
Eric Laurente552edb2014-03-10 17:42:56 -07007831 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007832 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007833 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007834 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007835 PatchBuilder patchBuilder;
7836 patchBuilder.addSource(outputDesc);
7837 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7838 for (const auto &filteredDevice : filteredDevices) {
7839 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007840 }
7841
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007842 // Add half reported latency to delayMs when muteWaitMs is null in order
7843 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007844 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7845 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7846 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007847 }
Eric Laurente552edb2014-03-10 17:42:56 -07007848
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007849 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7850 if (!skipMuteDelay) {
7851 // update stream volumes according to new device
7852 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7853 }
Eric Laurente552edb2014-03-10 17:42:56 -07007854
7855 return muteWaitMs;
7856}
7857
Eric Laurentc75307b2015-03-17 15:29:32 -07007858status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007859 int delayMs,
7860 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007861{
Eric Laurent6a94d692014-05-20 11:18:06 -07007862 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007863 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7864 return INVALID_OPERATION;
7865 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007866 if (patchHandle) {
7867 index = mAudioPatches.indexOfKey(*patchHandle);
7868 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007869 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007870 }
7871 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007872 return INVALID_OPERATION;
7873 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007874 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007875 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007876 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007877 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007878 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007879 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007880 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007881 return status;
7882}
7883
7884status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007885 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007886 bool force,
7887 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007888{
7889 status_t status = NO_ERROR;
7890
Eric Laurent1f2f2232014-06-02 12:01:23 -07007891 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007892 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7893 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007894
François Gaffie11d30102018-11-02 16:09:09 +01007895 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007896 PatchBuilder patchBuilder;
7897 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007898 // AUDIO_SOURCE_HOTWORD is for internal use only:
7899 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007900 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7901 auto result = usecase;
7902 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7903 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7904 }
7905 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007906 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007907 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007908 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007909 }
7910 }
7911 return status;
7912}
7913
Eric Laurent6a94d692014-05-20 11:18:06 -07007914status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7915 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007916{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007917 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007918 ssize_t index;
7919 if (patchHandle) {
7920 index = mAudioPatches.indexOfKey(*patchHandle);
7921 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007922 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007923 }
7924 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007925 return INVALID_OPERATION;
7926 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007927 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007928 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007929 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007930 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007931 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007932 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007933 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007934 return status;
7935}
7936
François Gaffie11d30102018-11-02 16:09:09 +01007937sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007938 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007939 audio_format_t& format,
7940 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007941 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007942{
7943 // Choose an input profile based on the requested capture parameters: select the first available
7944 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007945 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007946
Atneya Nair0f0a8032022-12-12 16:20:12 -08007947 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7948 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7949 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7950
7951 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007952
jiabin2fd710d2022-05-02 23:20:22 +00007953 for (;;) {
7954 sp<IOProfile> firstInexact = nullptr;
7955 uint32_t updatedSamplingRate = 0;
7956 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7957 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7958 for (const auto& hwModule : mHwModules) {
7959 for (const auto& profile : hwModule->getInputProfiles()) {
7960 // profile->log();
7961 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007962 if (profile->getCompatibilityScore(
7963 DeviceVector(device),
7964 samplingRate,
7965 &updatedSamplingRate,
7966 format,
7967 &updatedFormat,
7968 channelMask,
7969 &updatedChannelMask,
7970 // FIXME ugly cast
7971 (audio_output_flags_t) flags,
7972 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7973 samplingRate = updatedSamplingRate;
7974 format = updatedFormat;
7975 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007976 return profile;
7977 }
jiabin66acc432024-02-06 00:57:36 +00007978 if (firstInexact == nullptr
7979 && profile->getCompatibilityScore(
7980 DeviceVector(device),
7981 samplingRate,
7982 &updatedSamplingRate,
7983 format,
7984 &updatedFormat,
7985 channelMask,
7986 &updatedChannelMask,
7987 // FIXME ugly cast
7988 (audio_output_flags_t) flags,
7989 false /*exactMatchRequiredForInputFlags*/)
7990 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007991 firstInexact = profile;
7992 }
7993 }
7994 }
7995
7996 if (firstInexact != nullptr) {
7997 samplingRate = updatedSamplingRate;
7998 format = updatedFormat;
7999 channelMask = updatedChannelMask;
8000 return firstInexact;
8001 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8002 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8003 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8004 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8005 flags = AUDIO_INPUT_FLAG_NONE;
8006 } else { // fail
8007 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8008 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8009 samplingRate, format, channelMask, oriFlags);
8010 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008011 }
8012 }
jiabin2fd710d2022-05-02 23:20:22 +00008013
8014 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008015}
8016
Vlad Popa87e0e582024-05-20 18:49:20 -07008017float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8018 VolumeSource volumeSource,
8019 int index,
8020 const DeviceTypeSet &deviceTypes)
8021{
8022 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8023 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8024 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8025
8026 if (com_android_media_audio_abs_volume_index_fix()) {
8027 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8028 mAbsoluteVolumeDrivingStreams.end()) {
8029 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8030 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8031 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8032 ALOGD("%s: no group matching with %s", __FUNCTION__,
8033 toString(attributesToDriveAbs).c_str());
8034 return volumeDb;
8035 }
8036
8037 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8038 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8039 if (vsToDriveAbs == volumeSource) {
8040 // attenuation is applied by the abs volume controller
8041 return volumeDbMax;
8042 } else {
8043 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8044 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8045 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8046 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8047 curvesAbs.getVolumeIndexMax());
8048 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8049 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8050 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8051 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8052 return newVolumeDb;
8053 }
8054 }
8055 return volumeDb;
8056 } else {
8057 return volumeDb;
8058 }
8059}
8060
François Gaffieaaac0fd2018-11-22 17:56:39 +01008061float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8062 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008063 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008064 const DeviceTypeSet& deviceTypes,
8065 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008066{
Vlad Popa87e0e582024-05-20 18:49:20 -07008067 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008068 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8069 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8070
8071 if (!computeInternalInteraction) {
8072 return volumeDb;
8073 }
8074
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008075 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8076 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8077 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8078 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008079 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8080 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8081 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8082 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8083 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008084 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008085 mOutputs.isActive(ringVolumeSrc, 0)) {
8086 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008087 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8088 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008089 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008090 }
8091
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008092 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008093 if ((volumeSource != callVolumeSrc && (isInCall() ||
8094 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008095 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008096 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8097 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008098 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8099 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8100 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008101 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008102 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008103 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008104 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008105 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8106 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008107 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008108 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8109 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8110 // programmatically muted.
8111 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8112 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8113 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008114 bool exemptFromCapping =
8115 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8116 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008117 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8118 volumeSource, volumeDb);
8119 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008120 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8121 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8122 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008123 }
8124 }
Eric Laurente552edb2014-03-10 17:42:56 -07008125 // if a headset is connected, apply the following rules to ring tones and notifications
8126 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008127 // - always attenuate notifications volume by 6dB
8128 // - attenuate ring tones volume by 6dB unless music is not playing and
8129 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008130 // - if music is playing, always limit the volume to current music volume,
8131 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008132 if (!Intersection(deviceTypes,
8133 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8134 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008135 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8136 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008137 ((volumeSource == alarmVolumeSrc ||
8138 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008139 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8140 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8141 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008142 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8143 curves.canBeMuted()) {
8144
Eric Laurente552edb2014-03-10 17:42:56 -07008145 // when the phone is ringing we must consider that music could have been paused just before
8146 // by the music application and behave as if music was active if the last music track was
8147 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008148 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8149 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008150 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008151 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008152 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8153 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008154 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008155 float musicVolDb = computeVolume(musicCurves,
8156 musicVolumeSrc,
8157 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008158 musicDevice,
8159 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008160 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8161 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8162 if (volumeDb > minVolDb) {
8163 volumeDb = minVolDb;
8164 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008165 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008166 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8167 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
8168 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008169 // on A2DP, also ensure notification volume is not too low compared to media when
8170 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01008171 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008172 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008173 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8174 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008175 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8176 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008177 }
8178 }
jiabin9a3361e2019-10-01 09:38:30 -07008179 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008180 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008181 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008182 }
8183 }
8184
François Gaffie43c73442018-11-08 08:21:55 +01008185 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008186}
8187
Eric Laurent3839bc02018-07-10 18:33:34 -07008188int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008189 VolumeSource fromVolumeSource,
8190 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008191{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008192 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008193 return srcIndex;
8194 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008195 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8196 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008197 float minSrc = (float)srcCurves.getVolumeIndexMin();
8198 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8199 float minDst = (float)dstCurves.getVolumeIndexMin();
8200 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008201
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008202 // preserve mute request or correct range
8203 if (srcIndex < minSrc) {
8204 if (srcIndex == 0) {
8205 return 0;
8206 }
8207 srcIndex = minSrc;
8208 } else if (srcIndex > maxSrc) {
8209 srcIndex = maxSrc;
8210 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008211 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8212}
8213
François Gaffieaaac0fd2018-11-22 17:56:39 +01008214status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8215 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008216 int index,
8217 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008218 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008219 int delayMs,
8220 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008221{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008222 // do not change actual attributes volume if the attributes is muted
8223 if (outputDesc->isMuted(volumeSource)) {
8224 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8225 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008226 return NO_ERROR;
8227 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008228
Eric Laurentae6e88c2024-01-10 14:42:57 +01008229 bool isVoiceVolSrc;
8230 bool isBtScoVolSrc;
8231 if (!isVolumeConsistentForCalls(
8232 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008233 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008234 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008235 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008236 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008237
jiabin9a3361e2019-10-01 09:38:30 -07008238 if (deviceTypes.empty()) {
8239 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008240 index = curves.getVolumeIndex(deviceTypes);
8241 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
8242 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008243 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008244
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008245 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8246 ALOGE("invalid volume index range");
8247 return BAD_VALUE;
8248 }
8249
jiabin9a3361e2019-10-01 09:38:30 -07008250 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8251 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008252 // Force VoIP volume to max for bluetooth SCO device except if muted
8253 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008254 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008255 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008256 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008257 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008258 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8259 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008260
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008261 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008262 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008263 }
Eric Laurente552edb2014-03-10 17:42:56 -07008264 return NO_ERROR;
8265}
8266
Eric Laurentae6e88c2024-01-10 14:42:57 +01008267void AudioPolicyManager::setVoiceVolume(
8268 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8269 float voiceVolume;
8270 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8271 // by the headset
8272 if (isVoiceVolSrc) {
8273 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8274 } else {
8275 voiceVolume = index == 0 ? 0.0 : 1.0;
8276 }
8277 if (voiceVolume != mLastVoiceVolume) {
8278 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8279 mLastVoiceVolume = voiceVolume;
8280 }
8281}
8282
8283bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8284 const DeviceTypeSet& deviceTypes,
8285 bool& isVoiceVolSrc,
8286 bool& isBtScoVolSrc,
8287 const char* caller) {
8288 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8289 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8290 const bool isScoRequested = isScoRequestedForComm();
8291 const bool isHAUsed = isHearingAidUsedForComm();
8292
8293 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8294 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8295
8296 if ((callVolSrc != btScoVolSrc) &&
8297 ((isVoiceVolSrc && isScoRequested) ||
8298 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8299 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8300 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8301 volumeSource, isScoRequested ? " " : " not ");
8302 return false;
8303 }
8304 return true;
8305}
8306
Eric Laurentc75307b2015-03-17 15:29:32 -07008307void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008308 const DeviceTypeSet& deviceTypes,
8309 int delayMs,
8310 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008311{
jiabincd510522020-01-22 09:40:55 -08008312 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008313 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8314 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8315 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008316 curves.getVolumeIndex(deviceTypes),
8317 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008318 }
8319}
8320
François Gaffiec005e562018-11-06 15:04:49 +01008321void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8322 bool on,
8323 const sp<AudioOutputDescriptor>& outputDesc,
8324 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008325 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008326{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008327 std::vector<VolumeSource> sourcesToMute;
8328 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8329 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8330 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008331 VolumeSource source = toVolumeSource(attributes, false);
8332 if ((source != VOLUME_SOURCE_NONE) &&
8333 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8334 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008335 sourcesToMute.push_back(source);
8336 }
Eric Laurente552edb2014-03-10 17:42:56 -07008337 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008338 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008339 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008340 }
8341
Eric Laurente552edb2014-03-10 17:42:56 -07008342}
8343
François Gaffieaaac0fd2018-11-22 17:56:39 +01008344void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8345 bool on,
8346 const sp<AudioOutputDescriptor>& outputDesc,
8347 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008348 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008349{
jiabin9a3361e2019-10-01 09:38:30 -07008350 if (deviceTypes.empty()) {
8351 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008352 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008353 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008354 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008355 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008356 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008357 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008358 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8359 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008360 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008361 }
8362 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008363 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8364 // ignored
8365 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008366 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008367 if (!outputDesc->isMuted(volumeSource)) {
8368 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008369 return;
8370 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008371 if (outputDesc->decMuteCount(volumeSource) == 0) {
8372 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008373 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008374 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008375 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008376 delayMs);
8377 }
8378 }
8379}
8380
François Gaffie53615e22015-03-19 09:24:12 +01008381bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8382{
François Gaffiec005e562018-11-06 15:04:49 +01008383 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008384 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8385 return true;
8386 }
8387
8388 // has known usage?
8389 switch (paa->usage) {
8390 case AUDIO_USAGE_UNKNOWN:
8391 case AUDIO_USAGE_MEDIA:
8392 case AUDIO_USAGE_VOICE_COMMUNICATION:
8393 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8394 case AUDIO_USAGE_ALARM:
8395 case AUDIO_USAGE_NOTIFICATION:
8396 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8397 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8398 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8399 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8400 case AUDIO_USAGE_NOTIFICATION_EVENT:
8401 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8402 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8403 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8404 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008405 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008406 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008407 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008408 case AUDIO_USAGE_EMERGENCY:
8409 case AUDIO_USAGE_SAFETY:
8410 case AUDIO_USAGE_VEHICLE_STATUS:
8411 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008412 break;
8413 default:
8414 return false;
8415 }
8416 return true;
8417}
8418
François Gaffie2110e042015-03-24 08:41:51 +01008419audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8420{
8421 return mEngine->getForceUse(usage);
8422}
8423
Eric Laurent96d1dda2022-03-14 17:14:19 +01008424bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008425 return isStateInCall(mEngine->getPhoneState());
8426}
8427
Eric Laurent96d1dda2022-03-14 17:14:19 +01008428bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008429 return is_state_in_call(state);
8430}
8431
Eric Laurentf9cccec2022-11-16 19:12:00 +01008432bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008433 audio_mode_t mode = mEngine->getPhoneState();
8434 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008435 || (mode == AUDIO_MODE_CALL_SCREEN)
8436 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008437}
8438
Eric Laurentf9cccec2022-11-16 19:12:00 +01008439bool AudioPolicyManager::isInCallOrScreening() const {
8440 audio_mode_t mode = mEngine->getPhoneState();
8441 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8442}
8443
Eric Laurentd60560a2015-04-10 11:31:20 -07008444void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8445{
8446 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008447 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008448 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008449 sourceDesc->sinkDevice()->equals(deviceDesc))
8450 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008451 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008452 }
8453 }
8454
8455 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8456 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8457 bool release = false;
8458 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8459 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8460 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8461 source->ext.device.type == deviceDesc->type()) {
8462 release = true;
8463 }
8464 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008465 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008466 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8467 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8468 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008469 sink->ext.device.type == deviceDesc->type() &&
8470 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8471 || strncmp(sink->ext.device.address, address,
8472 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008473 release = true;
8474 }
8475 }
8476 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008477 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8478 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008479 }
8480 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008481
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008482 mInputs.clearSessionRoutesForDevice(deviceDesc);
8483
Francois Gaffie716e1432019-01-14 16:58:59 +01008484 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008485}
8486
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008487void AudioPolicyManager::modifySurroundFormats(
8488 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008489 std::unordered_set<audio_format_t> enforcedSurround(
8490 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008491 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008492 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008493 allSurround.insert(pair.first);
8494 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8495 }
Phil Burk09bc4612016-02-24 15:58:15 -08008496
8497 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8498 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008499 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008500 // This is the resulting set of formats depending on the surround mode:
8501 // 'all surround' = allSurround
8502 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8503 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8504 // 'manual surround' = mManualSurroundFormats
8505 // AUTO: formats v 'enforced surround'
8506 // ALWAYS: formats v 'all surround' v 'enforced surround'
8507 // NEVER: formats ^ 'non-surround'
8508 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008509
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008510 std::unordered_set<audio_format_t> formatSet;
8511 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8512 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008513 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008514 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008515 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008516 formatSet.insert(*formatIter);
8517 }
8518 }
8519 } else {
8520 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8521 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008522 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008523
jiabin81772902018-04-02 17:52:27 -07008524 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008525 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008526 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8527 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8528 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008529 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008530 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8531 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8532 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008533 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008534 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008535 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008536 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008537 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008538 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008539}
8540
jiabin06e4bab2019-07-29 10:13:34 -07008541void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8542 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008543 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8544 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8545
8546 // If NEVER, then remove support for channelMasks > stereo.
8547 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008548 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8549 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008550 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008551 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008552 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008553 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008554 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008555 }
8556 }
jiabin81772902018-04-02 17:52:27 -07008557 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8558 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8559 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008560 bool supports5dot1 = false;
8561 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008562 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008563 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8564 supports5dot1 = true;
8565 break;
8566 }
8567 }
8568 // If not then add 5.1 support.
8569 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008570 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008571 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008572 }
Phil Burk09bc4612016-02-24 15:58:15 -08008573 }
8574}
8575
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008576void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008577 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008578 const sp<IOProfile>& profile) {
8579 if (!profile->hasDynamicAudioProfile()) {
8580 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008581 }
François Gaffie112b0af2015-11-19 16:13:25 +01008582
jiabin12537fc2023-10-12 17:56:08 +00008583 audio_port_v7 devicePort;
8584 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008585
jiabin12537fc2023-10-12 17:56:08 +00008586 audio_port_v7 mixPort;
8587 profile->toAudioPort(&mixPort);
8588 mixPort.ext.mix.handle = ioHandle;
8589
8590 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8591 if (status != NO_ERROR) {
8592 ALOGE("%s failed to query the attributes of the mix port", __func__);
8593 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008594 }
jiabin12537fc2023-10-12 17:56:08 +00008595
8596 std::set<audio_format_t> supportedFormats;
8597 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8598 supportedFormats.insert(mixPort.audio_profiles[i].format);
8599 }
8600 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8601 mReportedFormatsMap[devDesc] = formats;
8602
8603 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8604 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8605 modifySurroundFormats(devDesc, &formats);
8606 size_t modifiedNumProfiles = 0;
8607 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8608 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8609 formats.end()) {
8610 // Skip the format that is not present after modifying surround formats.
8611 continue;
8612 }
8613 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8614 sizeof(struct audio_profile));
8615 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8616 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8617 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8618 modifySurroundChannelMasks(&channels);
8619 std::copy(channels.begin(), channels.end(),
8620 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8621 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8622 }
8623 mixPort.num_audio_profiles = modifiedNumProfiles;
8624 }
8625 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008626}
Eric Laurentd60560a2015-04-10 11:31:20 -07008627
Mikhail Naganovdc769682018-05-04 15:34:08 -07008628status_t AudioPolicyManager::installPatch(const char *caller,
8629 audio_patch_handle_t *patchHandle,
8630 AudioIODescriptorInterface *ioDescriptor,
8631 const struct audio_patch *patch,
8632 int delayMs)
8633{
8634 ssize_t index = mAudioPatches.indexOfKey(
8635 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8636 *patchHandle : ioDescriptor->getPatchHandle());
8637 sp<AudioPatch> patchDesc;
8638 status_t status = installPatch(
8639 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8640 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008641 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008642 }
8643 return status;
8644}
8645
8646status_t AudioPolicyManager::installPatch(const char *caller,
8647 ssize_t index,
8648 audio_patch_handle_t *patchHandle,
8649 const struct audio_patch *patch,
8650 int delayMs,
8651 uid_t uid,
8652 sp<AudioPatch> *patchDescPtr)
8653{
8654 sp<AudioPatch> patchDesc;
8655 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8656 if (index >= 0) {
8657 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008658 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008659 }
8660
8661 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8662 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8663 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8664 if (status == NO_ERROR) {
8665 if (index < 0) {
8666 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008667 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008668 } else {
8669 patchDesc->mPatch = *patch;
8670 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008671 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008672 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008673 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008674 }
8675 nextAudioPortGeneration();
8676 mpClientInterface->onAudioPatchListUpdate();
8677 }
8678 if (patchDescPtr) *patchDescPtr = patchDesc;
8679 return status;
8680}
8681
jiabinbce0c1d2020-10-05 11:20:18 -07008682bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8683{
8684 const TrackClientVector activeClients = output->getActiveClients();
8685 if (activeClients.empty()) {
8686 return true;
8687 }
8688 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8689 if (index < 0) {
8690 ALOGE("%s, no audio patch found while there are active clients on output %d",
8691 __func__, output->getId());
8692 return false;
8693 }
8694 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8695 DeviceVector routedDevices;
8696 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8697 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8698 patchDesc->mPatch.sinks[i].id);
8699 if (device == nullptr) {
8700 ALOGE("%s, no audio device found with id(%d)",
8701 __func__, patchDesc->mPatch.sinks[i].id);
8702 return false;
8703 }
8704 routedDevices.add(device);
8705 }
8706 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008707 if (client->isInvalid()) {
8708 // No need to take care about invalidated clients.
8709 continue;
8710 }
jiabinbce0c1d2020-10-05 11:20:18 -07008711 sp<DeviceDescriptor> preferredDevice =
8712 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8713 if (mEngine->getOutputDevicesForAttributes(
8714 client->attributes(), preferredDevice, false) == routedDevices) {
8715 return false;
8716 }
8717 }
8718 return true;
8719}
8720
8721sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008722 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008723 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8724 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008725{
8726 for (const auto& device : devices) {
8727 // TODO: This should be checking if the profile supports the device combo.
8728 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008729 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8730 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008731 return nullptr;
8732 }
8733 }
8734 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8735 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008736 status_t status = desc->open(halConfig, mixerConfig, devices,
8737 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008738 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008739 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008740 return nullptr;
8741 }
jiabin14b50cc2023-12-13 19:01:52 +00008742 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8743 auto portConfig = desc->getConfig();
8744 for (const auto& device : devices) {
8745 device->setPreferredConfig(&portConfig);
8746 }
8747 }
jiabinbce0c1d2020-10-05 11:20:18 -07008748
8749 // Here is where the out_set_parameters() for card & device gets called
8750 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8751 const audio_devices_t deviceType = device->type();
8752 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008753 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008754 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8755 mpClientInterface->setParameters(output, String8(param));
8756 free(param);
8757 }
jiabin12537fc2023-10-12 17:56:08 +00008758 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008759 if (!profile->hasValidAudioProfile()) {
8760 ALOGW("%s() missing param", __func__);
8761 desc->close();
8762 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008763 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8764 // Reopen the output with the best audio profile picked by APM when the profile supports
8765 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008766 desc->close();
8767 output = AUDIO_IO_HANDLE_NONE;
8768 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8769 profile->pickAudioProfile(
8770 config.sample_rate, config.channel_mask, config.format);
8771 config.offload_info.sample_rate = config.sample_rate;
8772 config.offload_info.channel_mask = config.channel_mask;
8773 config.offload_info.format = config.format;
8774
jiabina84c3d32022-12-02 18:59:55 +00008775 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008776 if (status != NO_ERROR) {
8777 return nullptr;
8778 }
8779 }
8780
8781 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008782 setOutputDevices(__func__, desc,
8783 devices,
8784 true,
8785 0,
8786 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008787 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8788 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8789
jiabinbce0c1d2020-10-05 11:20:18 -07008790 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8791 sp<AudioPolicyMix> policyMix;
8792 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8793 policyMix->setOutput(desc);
8794 desc->mPolicyMix = policyMix;
8795 } else {
8796 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008797 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008798 }
8799
baek.kim -61c20122022-07-27 10:05:32 +00008800 } else if (hasPrimaryOutput() && speaker != nullptr
8801 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008802 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8803 // no duplicated output for:
8804 // - direct outputs
8805 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008806 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008807 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8808
8809 //TODO: configure audio effect output stage here
8810
8811 // open a duplicating output thread for the new output and the primary output
8812 sp<SwAudioOutputDescriptor> dupOutputDesc =
8813 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8814 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8815 if (status == NO_ERROR) {
8816 // add duplicated output descriptor
8817 addOutput(duplicatedOutput, dupOutputDesc);
8818 } else {
8819 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8820 mPrimaryOutput->mIoHandle, output);
8821 desc->close();
8822 removeOutput(output);
8823 nextAudioPortGeneration();
8824 return nullptr;
8825 }
8826 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008827 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8828 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8829 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008830 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008831 }
jiabinbce0c1d2020-10-05 11:20:18 -07008832 return desc;
8833}
8834
jiabinf1c73972022-04-14 16:28:52 -07008835status_t AudioPolicyManager::getDevicesForAttributes(
8836 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8837 // Devices are determined in the following precedence:
8838 //
8839 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8840 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8841 //
8842 // If no such dynamic policy then
8843 // 2) Devices containing an active client using setPreferredDevice
8844 // with same strategy as the attributes.
8845 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8846 //
8847 // If no corresponding active client with setPreferredDevice then
8848 // 3) Devices associated with the strategy determined by the attributes
8849 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8850 //
8851 // See related getOutputForAttrInt().
8852
8853 // check dynamic policies but only for primary descriptors (secondary not used for audible
8854 // audio routing, only used for duplication for playback capture)
8855 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008856 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008857 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008858 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8859 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8860 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008861 if (status != OK) {
8862 return status;
8863 }
8864
8865 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8866 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8867 // as they are unaffected by device/stream volume
8868 // (per SwAudioOutputDescriptor::isFixedVolume()).
8869 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8870 ) {
8871 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8872 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8873 devices.add(deviceDesc);
8874 } else {
8875 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8876 // which selects setPreferredDevice if active. This means forVolume call
8877 // will take an active setPreferredDevice, if such exists.
8878
8879 devices = mEngine->getOutputDevicesForAttributes(
8880 attr, nullptr /* preferredDevice */, false /* fromCache */);
8881 }
8882
8883 if (forVolume) {
8884 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8885 // for single volume control in AudioService (such relationship should exist if
8886 // SPEAKER_SAFE is present).
8887 //
8888 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8889 DeviceVector speakerSafeDevices =
8890 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8891 if (!speakerSafeDevices.isEmpty()) {
8892 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8893 devices.remove(speakerSafeDevices);
8894 }
8895 }
8896
8897 return NO_ERROR;
8898}
8899
8900status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8901 AudioProfileVector& audioProfiles,
8902 uint32_t flags,
8903 bool isInput) {
8904 for (const auto& hwModule : mHwModules) {
8905 // the MSD module checks for different conditions
8906 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8907 continue;
8908 }
8909 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8910 : hwModule->getOutputProfiles();
8911 for (const auto& profile : ioProfiles) {
8912 if (!profile->areAllDevicesSupported(devices) ||
8913 !profile->isCompatibleProfileForFlags(
8914 flags, false /*exactMatchRequiredForInputFlags*/)) {
8915 continue;
8916 }
8917 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8918 }
8919 }
8920
8921 if (!isInput) {
8922 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8923 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8924 if (msdModule != nullptr) {
8925 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8926 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8927 for (const auto &profile: msdModule->getOutputProfiles()) {
8928 if (!profile->asAudioPort()->isDirectOutput()) {
8929 continue;
8930 }
8931 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8932 }
8933 } else {
8934 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8935 }
8936 }
8937 }
8938
8939 return NO_ERROR;
8940}
8941
jiabin3ff8d7d2022-12-13 06:27:44 +00008942sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8943 const audio_config_t *config,
8944 audio_output_flags_t flags,
8945 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008946 closeOutput(outputDesc->mIoHandle);
8947 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8948 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8949 if (preferredOutput == nullptr) {
8950 ALOGE("%s failed to reopen output device=%d, caller=%s",
8951 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008952 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008953 return preferredOutput;
8954}
8955
8956void AudioPolicyManager::reopenOutputsWithDevices(
8957 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8958 for (const auto& [output, devices] : outputsToReopen) {
8959 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8960 closeOutput(output);
8961 openOutputWithProfileAndDevice(desc->mProfile, devices);
8962 }
jiabina84c3d32022-12-02 18:59:55 +00008963}
8964
jiabinc44b3462022-12-08 12:52:31 -08008965PortHandleVector AudioPolicyManager::getClientsForStream(
8966 audio_stream_type_t streamType) const {
8967 PortHandleVector clients;
8968 for (size_t i = 0; i < mOutputs.size(); ++i) {
8969 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8970 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8971 }
8972 return clients;
8973}
8974
8975void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8976 PortHandleVector clients;
8977 for (auto stream : streams) {
8978 PortHandleVector clientsForStream = getClientsForStream(stream);
8979 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8980 }
8981 mpClientInterface->invalidateTracks(clients);
8982}
8983
jiabin220eea12024-05-17 17:55:20 +00008984void AudioPolicyManager::updateClientsInternalMute(
8985 const sp<android::SwAudioOutputDescriptor> &desc) {
8986 if (!desc->isBitPerfect() ||
8987 !com::android::media::audioserver::
8988 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
8989 // This is only used for bit perfect output now.
8990 return;
8991 }
8992 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
8993 bool bitPerfectClientInternalMute = false;
8994 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
8995 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
8996 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
8997 bitPerfectClient = client;
8998 continue;
8999 }
9000 bool muted = false;
9001 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9002 // System sound is muted.
9003 muted = true;
9004 } else {
9005 bitPerfectClientInternalMute = true;
9006 }
9007 if (client->setInternalMute(muted)) {
9008 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9009 if (!result.ok()) {
9010 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9011 continue;
9012 }
9013 media::TrackInternalMuteInfo info;
9014 info.portId = result.value();
9015 info.muted = client->getInternalMute();
9016 clientsInternalMute.push_back(std::move(info));
9017 }
9018 }
9019 if (bitPerfectClient != nullptr &&
9020 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9021 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9022 if (result.ok()) {
9023 media::TrackInternalMuteInfo info;
9024 info.portId = result.value();
9025 info.muted = bitPerfectClient->getInternalMute();
9026 clientsInternalMute.push_back(std::move(info));
9027 } else {
9028 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9029 __func__, bitPerfectClient->portId());
9030 }
9031 }
9032 if (!clientsInternalMute.empty()) {
9033 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9034 status != NO_ERROR) {
9035 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9036 }
9037 }
9038}
9039
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009040} // namespace android