blob: 2754cbf4abc685c3418fdc50a429ef226c3b47fc [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Mikhail Naganov3754b642024-04-17 18:31:04 +0000132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganov3754b642024-04-17 18:31:04 +0000222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000341 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530377 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700378 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } // end if is output device
380
Eric Laurente552edb2014-03-10 17:42:56 -0700381 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700382 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700384 switch (state)
385 {
386 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700390 return INVALID_OPERATION;
391 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700392
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530393 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (mAvailableInputDevices.add(device) < 0) {
396 return NO_MEMORY;
397 }
398
François Gaffie44481e72016-04-20 07:49:57 +0200399 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
400 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000401 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700402 // Propagate device availability to Engine
403 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200404
Eric Laurent0dd51852019-04-19 18:18:58 -0700405 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700406 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
407
Eric Laurent0dd51852019-04-19 18:18:58 -0700408 mAvailableInputDevices.remove(device);
409
jiabinc0048632023-04-27 22:04:31 +0000410 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100411
412 mHwModules.cleanUpForDevice(device);
413
Eric Laurentd4692962014-05-05 18:13:44 -0700414 return INVALID_OPERATION;
415 }
416
Eric Laurentd4692962014-05-05 18:13:44 -0700417 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700418
419 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700420 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700421 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return INVALID_OPERATION;
424 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700425
François Gaffie11d30102018-11-02 16:09:09 +0100426 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700427
jiabinc0048632023-04-27 22:04:31 +0000428 // Notify the HAL to prepare to disconnect device
429 broadcastDeviceConnectionState(
430 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700431
François Gaffie11d30102018-11-02 16:09:09 +0100432 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700433
434 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100435
jiabinc0048632023-04-27 22:04:31 +0000436 // Set Disconnect to HALs
437 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
438
Kriti Dangef6be8f2020-11-05 11:58:19 +0100439 // remove device from mReportedFormatsMap cache
440 mReportedFormatsMap.erase(device);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700441
442 // Propagate device availability to Engine
443 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700444 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700445
446 default:
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449 }
450
Eric Laurent0dd51852019-04-19 18:18:58 -0700451 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700452 // As the input device list can impact the output device selection, update
453 // getDeviceForStrategy() cache
454 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700455
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100456 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200457 // Reconnect Audio Source
458 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
459 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
460 checkAudioSourceForAttributes(attributes);
461 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700462 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100463 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700464 }
465
Eric Laurentb52c1522014-05-20 11:27:36 -0700466 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530467 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700468 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700469 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700470
François Gaffie11d30102018-11-02 16:09:09 +0100471 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700472 return BAD_VALUE;
473}
474
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100475status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
476 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800477 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000478 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
479 devDescr->setName(device_name);
480 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100481}
482
Eric Laurent736a1022019-03-27 18:28:46 -0700483void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
484 audio_policy_dev_state_t state) {
485
486 // the Engine does not have to know about remote submix devices used by dynamic audio policies
487 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
488 return;
489 }
490 mEngine->setDeviceConnectionState(device, state);
491}
492
493
Eric Laurente0720872014-03-11 09:30:41 -0700494audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100495 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700496{
Eric Laurent634b7142016-04-20 13:48:02 -0700497 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800498 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
499 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700500 (strlen(device_address) != 0)/*matchAddress*/);
501
502 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100503 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700504 device, device_address);
505 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
506 }
François Gaffie53615e22015-03-19 09:24:12 +0100507
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 DeviceVector *deviceVector;
509
Eric Laurente552edb2014-03-10 17:42:56 -0700510 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700511 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700512 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700513 deviceVector = &mAvailableInputDevices;
514 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100515 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700516 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700517 }
Eric Laurent634b7142016-04-20 13:48:02 -0700518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 return (deviceVector->getDevice(
520 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800522}
523
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
525 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 const char *device_name,
527 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
530 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800532 // connect/disconnect only 1 device at a time
533 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
534
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800535 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700536 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538 // Nothing to do: device is not connected
539 return NO_ERROR;
540 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800542
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700543 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 // configure codecs.
545 // Handle two specific cases by sending a set parameter to
546 // configure A2DP codecs. No need to toggle device state.
547 // Case 1: A2DP active device switches from primary to primary
548 // module
549 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100550 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700551 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800552 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
553 if (availablePrimaryOutputDevices().contains(devDesc) &&
554 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100555 bool isA2dp = audio_is_a2dp_out_device(device);
556 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
557 : String8(AudioParameter::keyReconfigLeSupported);
558 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800559 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100560 int isReconfigSupported;
561 repliedParameters.getInt(supportKey, isReconfigSupported);
562 if (isReconfigSupported) {
563 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
564 : String8(AudioParameter::keyReconfigLe);
565 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 param.add(key, String8("true"));
567 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
568 devDesc->setEncodedFormat(encodedFormat);
569 return NO_ERROR;
570 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700571 }
572 }
cnx421bd2dcc42020-07-11 14:58:44 +0800573 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
574 for (size_t i = 0; i < mOutputs.size(); i++) {
575 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
576 // mute media strategies and delay device switch by the largest
577 // This avoid sending the music tail into the earpiece or headset.
578 setStrategyMute(musicStrategy, true, desc);
579 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
580 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
581 nullptr, true /*fromCache*/).types());
582 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800583 // Toggle the device state: UNAVAILABLE -> AVAILABLE
584 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100585 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800586 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800587 device_address, device_name,
588 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800589 if (status != NO_ERROR) {
590 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
591 status);
592 return status;
593 }
594
595 status = setDeviceConnectionState(device,
596 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800597 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800598 if (status != NO_ERROR) {
599 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
600 status);
601 return status;
602 }
603
604 return NO_ERROR;
605}
606
Pattydd807582021-11-04 21:01:03 +0800607status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
608 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800609{
Pattydd807582021-11-04 21:01:03 +0800610 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800611 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800612 std::unordered_set<audio_format_t> formatSet;
613 sp<HwModule> primaryModule =
614 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700615 if (primaryModule == nullptr) {
616 ALOGE("%s() unable to get primary module", __func__);
617 return NO_INIT;
618 }
Pattydd807582021-11-04 21:01:03 +0800619
620 DeviceTypeSet audioDeviceSet;
621
622 switch(device) {
623 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
624 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
625 break;
626 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800627 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
628 break;
629 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
630 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800631 break;
632 default:
633 ALOGE("%s() device type 0x%08x not supported", __func__, device);
634 return BAD_VALUE;
635 }
636
jiabin9a3361e2019-10-01 09:38:30 -0700637 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800638 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800639 for (const auto& device : declaredDevices) {
640 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800641 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800642 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800643 return status;
644}
645
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100646DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
647{
648 DeviceVector rxSinkdevices{};
649 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
650 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
651 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
652 auto rxSinkDevice = rxSinkdevices.itemAt(0);
653 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
654 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
655 // retrieve Rx Source device descriptor
656 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
657 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
658
659 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
660 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
661 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
662 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
663 return DeviceVector(rxSinkDevice);
664 }
665 }
666 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
667 // the device returned is not necessarily reachable via this output
668 // (filter later by setOutputDevices())
669 return getNewOutputDevices(mPrimaryOutput, fromCache);
670}
671
672status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
673{
François Gaffiedb1755b2023-09-01 11:50:35 +0200674 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100675 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
676 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
677 }
678 return INVALID_OPERATION;
679}
680
681status_t AudioPolicyManager::updateCallRoutingInternal(
682 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700683{
684 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100685 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700686 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200687 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700688 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100689 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700690 }
François Gaffie11d30102018-11-02 16:09:09 +0100691
Francois Gaffie716e1432019-01-14 16:58:59 +0100692 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100693 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200694
695 disconnectTelephonyAudioSource(mCallRxSourceClient);
696 disconnectTelephonyAudioSource(mCallTxSourceClient);
697
698 if (rxDevices.isEmpty()) {
699 ALOGW("%s() no selected output device", __func__);
700 return INVALID_OPERATION;
701 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000702 if (txSourceDevice == nullptr) {
703 ALOGE("%s() selected input device not available", __func__);
704 return INVALID_OPERATION;
705 }
François Gaffiec005e562018-11-06 15:04:49 +0100706
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100707 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100708 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700709
François Gaffie9eb18552018-11-05 10:33:26 +0100710 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700711 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100712 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700713 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100714 // retrieve Rx Source and Tx Sink device descriptors
715 sp<DeviceDescriptor> rxSourceDevice =
716 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
717 String8(),
718 AUDIO_FORMAT_DEFAULT);
719 sp<DeviceDescriptor> txSinkDevice =
720 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
721 String8(),
722 AUDIO_FORMAT_DEFAULT);
723
724 // RX and TX Telephony device are declared by Primary Audio HAL
725 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
726 (telephonyRxModule->getHalVersionMajor() >= 3)) {
727 if (rxSourceDevice == 0 || txSinkDevice == 0) {
728 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100729 ALOGE("%s() no telephony Tx and/or RX device", __func__);
730 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100731 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100732 // createAudioPatchInternal now supports both HW / SW bridging
733 createRxPatch = true;
734 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100735 } else {
736 // If the RX device is on the primary HW module, then use legacy routing method for
737 // voice calls via setOutputDevice() on primary output.
738 // Otherwise, create two audio patches for TX and RX path.
739 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
740 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741 // If the TX device is also on the primary HW module, setOutputDevice() will take care
742 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100743 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
744 (txSinkDevice != 0);
745 }
746 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
747 // Otherwise, create two audio patches for TX and RX path.
748 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200749 if (!hasPrimaryOutput()) {
750 ALOGW("%s() no primary output available", __func__);
751 return INVALID_OPERATION;
752 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530753 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700754 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200755 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800756 // If the TX device is on the primary HW module but RX device is
757 // on other HW module, SinkMetaData of telephony input should handle it
758 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700759 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700760 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100761 // terminate active capture if on the same HW module as the call TX source device
762 // FIXME: would be better to refine to only inputs whose profile connects to the
763 // call TX device but this information is not in the audio patch and logic here must be
764 // symmetric to the one in startInput()
765 for (const auto& activeDesc : mInputs.getActiveInputs()) {
766 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
767 closeActiveClients(activeDesc);
768 }
769 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200770 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800771 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100772 if (waitMs != nullptr) {
773 *waitMs = muteWaitMs;
774 }
775 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800776}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700777
Mikhail Naganov100f0122018-11-29 11:22:16 -0800778bool AudioPolicyManager::isDeviceOfModule(
779 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
780 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
781 if (module != 0) {
782 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
783 .indexOf(devDesc) != NAME_NOT_FOUND
784 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
785 .indexOf(devDesc) != NAME_NOT_FOUND;
786 }
787 return false;
788}
789
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200790void AudioPolicyManager::connectTelephonyRxAudioSource()
791{
Francois Gaffie601801d2021-06-22 13:27:39 +0200792 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200793 const struct audio_port_config source = {
794 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
795 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
796 };
797 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100798
799 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
800 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
801 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
802 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200803 ALOGE_IF(mCallRxSourceClient == nullptr,
804 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200805}
806
Francois Gaffie601801d2021-06-22 13:27:39 +0200807void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200808{
Francois Gaffie601801d2021-06-22 13:27:39 +0200809 if (clientDesc == nullptr) {
810 return;
811 }
812 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
813 "%s error stopping audio source", __func__);
814 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200815}
816
817void AudioPolicyManager::connectTelephonyTxAudioSource(
818 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
819 uint32_t delayMs)
820{
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200822 if (srcDevice == nullptr || sinkDevice == nullptr) {
823 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
824 return;
825 }
826 PatchBuilder patchBuilder;
827 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
828 ALOGV("%s between source %s and sink %s", __func__,
829 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200830 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200831 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
832
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200833 struct audio_port_config source = {};
834 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100835 mCallTxSourceClient = new SourceClientDescriptor(
836 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
837 mCommunnicationStrategy, toVolumeSource(aa), true);
838 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
839
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200840 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
841 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200842 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
843 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200844 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
845 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200846 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200847 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200848}
849
Eric Laurente0720872014-03-11 09:30:41 -0700850void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700851{
852 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100853 // store previous phone state for management of sonification strategy below
854 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100855 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100856
857 if (mEngine->setPhoneState(state) != NO_ERROR) {
858 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700859 return;
860 }
François Gaffie2110e042015-03-24 08:41:51 +0100861 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700862 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700863 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700864 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800865 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700866 }
867
François Gaffie2110e042015-03-24 08:41:51 +0100868 /**
869 * Switching to or from incall state or switching between telephony and VoIP lead to force
870 * routing command.
871 */
Eric Laurent74b71512019-11-06 17:21:57 -0800872 bool force = ((isStateInCall(oldState) != isStateInCall(state))
873 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700874
875 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700876 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700877
Eric Laurente552edb2014-03-10 17:42:56 -0700878 int delayMs = 0;
879 if (isStateInCall(state)) {
880 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100881 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
882 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700883 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700884 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700885 // mute media and sonification strategies and delay device switch by the largest
886 // latency of any output where either strategy is active.
887 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100888 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
889 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
890 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700891 (delayMs < (int)desc->latency()*2)) {
892 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700893 }
François Gaffiec005e562018-11-06 15:04:49 +0100894 setStrategyMute(musicStrategy, true, desc);
895 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
896 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
897 nullptr, true /*fromCache*/).types());
898 setStrategyMute(sonificationStrategy, true, desc);
899 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
900 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
901 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700902 }
903 }
904
François Gaffiedb1755b2023-09-01 11:50:35 +0200905 if (state == AUDIO_MODE_IN_CALL) {
906 (void)updateCallRouting(false /*fromCache*/, delayMs);
907 } else {
908 if (oldState == AUDIO_MODE_IN_CALL) {
909 disconnectTelephonyAudioSource(mCallRxSourceClient);
910 disconnectTelephonyAudioSource(mCallTxSourceClient);
911 }
912 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100913 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
914 // force routing command to audio hardware when ending call
915 // even if no device change is needed
916 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
917 rxDevices = mPrimaryOutput->devices();
918 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530919 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700920 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700921 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700922
jiabin3ff8d7d2022-12-13 06:27:44 +0000923 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700924 // reevaluate routing on all outputs in case tracks have been started during the call
925 for (size_t i = 0; i < mOutputs.size(); i++) {
926 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100927 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200928 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
929 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000930 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
931 // If the device is using preferred mixer attributes, the output need to reopen
932 // with default configuration when the new selected devices are different from
933 // current routing devices.
934 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
935 continue;
936 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530937 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200938 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700939 }
940 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000941 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700942
Eric Laurent96d1dda2022-03-14 17:14:19 +0100943 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
944
Eric Laurente552edb2014-03-10 17:42:56 -0700945 if (isStateInCall(state)) {
946 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700947 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800948 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700949 }
950
951 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100952 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
953 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700954}
955
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700956audio_mode_t AudioPolicyManager::getPhoneState() {
957 return mEngine->getPhoneState();
958}
959
Eric Laurente0720872014-03-11 09:30:41 -0700960void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100961 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700962{
François Gaffie2110e042015-03-24 08:41:51 +0100963 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700964 if (config == mEngine->getForceUse(usage)) {
965 return;
966 }
Eric Laurente552edb2014-03-10 17:42:56 -0700967
François Gaffie2110e042015-03-24 08:41:51 +0100968 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
969 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
970 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700971 }
François Gaffie2110e042015-03-24 08:41:51 +0100972 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
973 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
974 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700975
976 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700977 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800978
Eric Laurent22fcda22019-05-17 16:28:47 -0700979 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
980 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800981 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700982 }
983
Eric Laurentdc462862016-07-19 12:29:53 -0700984 //FIXME: workaround for truncated touch sounds
985 // to be removed when the problem is handled by system UI
986 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700987 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
988 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
989 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700990
991 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100992 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700993}
994
Eric Laurente0720872014-03-11 09:30:41 -0700995void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700996{
997 ALOGV("setSystemProperty() property %s, value %s", property, value);
998}
999
Dorin Drimusecc9f422022-03-09 17:57:40 +01001000// Find an MSD output profile compatible with the parameters passed.
1001// When "directOnly" is set, restrict search to profiles for direct outputs.
1002sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1003 const DeviceVector& devices,
1004 uint32_t samplingRate,
1005 audio_format_t format,
1006 audio_channel_mask_t channelMask,
1007 audio_output_flags_t flags,
1008 bool directOnly)
1009{
1010 flags = getRelevantFlags(flags, directOnly);
1011
1012 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1013 if (msdModule != nullptr) {
1014 // for the msd module check if there are patches to the output devices
1015 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1016 HwModuleCollection modules;
1017 modules.add(msdModule);
1018 return searchCompatibleProfileHwModules(
1019 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1020 flags, directOnly);
1021 }
1022 }
1023 return nullptr;
1024}
1025
Michael Chana94fbb22018-04-24 14:31:19 +10001026// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1027// search to profiles for direct outputs.
1028sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001029 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001030 uint32_t samplingRate,
1031 audio_format_t format,
1032 audio_channel_mask_t channelMask,
1033 audio_output_flags_t flags,
1034 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001035{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 flags = getRelevantFlags(flags, directOnly);
1037
1038 return searchCompatibleProfileHwModules(
1039 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1040}
1041
1042audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1043 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001044 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 // only retain flags that will drive the direct output profile selection
1046 // if explicitly requested
1047 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001048 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001049 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1050 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001051 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001052 return flags;
1053}
Eric Laurent861a6282015-05-18 15:40:16 -07001054
Dorin Drimusecc9f422022-03-09 17:57:40 +01001055sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1056 const HwModuleCollection& hwModules,
1057 const DeviceVector& devices,
1058 uint32_t samplingRate,
1059 audio_format_t format,
1060 audio_channel_mask_t channelMask,
1061 audio_output_flags_t flags,
1062 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001063 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001064 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001065 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001066 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 samplingRate, NULL /*updatedSamplingRate*/,
1068 format, NULL /*updatedFormat*/,
1069 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001070 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001071 continue;
1072 }
1073 // reject profiles not corresponding to a device currently available
1074 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1075 continue;
1076 }
1077 // reject profiles if connected device does not support codec
1078 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1079 continue;
1080 }
1081 if (!directOnly) {
1082 return curProfile;
1083 }
1084
1085 // when searching for direct outputs, if several profiles are compatible, give priority
1086 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001087 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001088 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001089 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001090 }
1091 profile = curProfile;
1092 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1093 break;
1094 }
Eric Laurente552edb2014-03-10 17:42:56 -07001095 }
1096 }
Eric Laurent861a6282015-05-18 15:40:16 -07001097 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001098}
1099
Eric Laurentfa0f6742021-08-17 18:39:44 +02001100sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001101 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001102{
1103 for (const auto& hwModule : mHwModules) {
1104 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001105 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001106 continue;
1107 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001108 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001109 // reject profiles not corresponding to a device currently available
1110 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1111 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1112 continue;
1113 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001114 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1115 != devices.size()) {
1116 continue;
1117 }
1118 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001119 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1120 return curProfile;
1121 }
1122 }
1123 return nullptr;
1124}
1125
Eric Laurentf4e63452017-11-06 19:31:46 +00001126audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001127{
François Gaffiec005e562018-11-06 15:04:49 +01001128 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001129
1130 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1131 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1132 // format, flags, etc. This may result in some discrepancy for functions that utilize
1133 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1134 // and AudioSystem::getOutputSamplingRate().
1135
François Gaffie11d30102018-11-02 16:09:09 +01001136 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001137 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1138 if (stream == AUDIO_STREAM_MUSIC &&
1139 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1140 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1141 }
1142 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001143
François Gaffie11d30102018-11-02 16:09:09 +01001144 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1145 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001146 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001147}
1148
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1150 const audio_attributes_t *srcAttr,
1151 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001152{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001153 if (srcAttr != NULL) {
1154 if (!isValidAttributes(srcAttr)) {
1155 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1156 __func__,
1157 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1158 srcAttr->tags);
1159 return BAD_VALUE;
1160 }
1161 *dstAttr = *srcAttr;
1162 } else {
1163 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1164 ALOGE("%s: invalid stream type", __func__);
1165 return BAD_VALUE;
1166 }
François Gaffiec005e562018-11-06 15:04:49 +01001167 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001168 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001169
1170 // Only honor audibility enforced when required. The client will be
1171 // forced to reconnect if the forced usage changes.
1172 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001173 dstAttr->flags = static_cast<audio_flags_mask_t>(
1174 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001175 }
1176
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001177 return NO_ERROR;
1178}
1179
Kevin Rocard153f92d2018-12-18 18:33:28 -08001180status_t AudioPolicyManager::getOutputForAttrInt(
1181 audio_attributes_t *resultAttr,
1182 audio_io_handle_t *output,
1183 audio_session_t session,
1184 const audio_attributes_t *attr,
1185 audio_stream_type_t *stream,
1186 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001187 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001188 audio_output_flags_t *flags,
1189 audio_port_handle_t *selectedDeviceId,
1190 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001191 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001192 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001193 bool *isSpatialized,
1194 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001195{
François Gaffiec005e562018-11-06 15:04:49 +01001196 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001197 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001198 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001199 const sp<DeviceDescriptor> requestedDevice =
1200 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1201
Eric Laurent8a1095a2019-11-08 14:44:16 -08001202 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001203 *isSpatialized = false;
1204
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001205 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1206 if (status != NO_ERROR) {
1207 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001208 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001209 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001210 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001211 }
François Gaffiec005e562018-11-06 15:04:49 +01001212 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001213
François Gaffiec005e562018-11-06 15:04:49 +01001214 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1215 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001216
Oscar Azucena873d10f2023-01-12 18:34:42 -08001217 bool usePrimaryOutputFromPolicyMixes = false;
1218
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1220 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1221 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001222 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001223 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1224 .channel_mask = config->channel_mask,
1225 .format = config->format,
1226 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001227 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001228 mAvailableOutputDevices, requestedDevice, primaryMix,
1229 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001230 if (status != OK) {
1231 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001232 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001233
Kevin Rocard153f92d2018-12-18 18:33:28 -08001234 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001235 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1236 && !audio_is_linear_pcm(config->format)) {
1237 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001238 return BAD_VALUE;
1239 }
1240 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001241 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001242 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1243 primaryMix->mDeviceAddress,
1244 AUDIO_FORMAT_DEFAULT);
1245 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001246 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001247 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1248 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001249 // if a direct output can be opened to deliver the track's multi-channel content to the
1250 // output rather than being downmixed by the primary output, then use this direct
1251 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1252 // mix.
1253 bool tryDirectForChannelMask = policyDesc != nullptr
1254 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1255 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001256 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001257 audio_io_handle_t newOutput;
1258 status = openDirectOutput(
1259 *stream, session, config,
1260 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001261 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001262 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001263 policyDesc = mOutputs.valueFor(newOutput);
1264 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001265 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001266 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001267 policyDesc = nullptr;
1268 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001269 }
1270 if (policyDesc != nullptr) {
1271 policyDesc->mPolicyMix = primaryMix;
1272 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001273 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1274 : AUDIO_PORT_HANDLE_NONE;
1275 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1276 // Remove direct flag as it is not on a direct output.
1277 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1278 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001279
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001280 ALOGV("getOutputForAttr() returns output %d", *output);
1281 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1282 *outputType = API_OUT_MIX_PLAYBACK;
1283 } else {
1284 *outputType = API_OUTPUT_LEGACY;
1285 }
1286 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001287 } else {
1288 if (policyMixDevice != nullptr) {
1289 ALOGE("%s, try to use primary mix but no output found", __func__);
1290 return INVALID_OPERATION;
1291 }
1292 // Fallback to default engine selection as the selected primary mix device is not
1293 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001294 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001295 }
François Gaffiec005e562018-11-06 15:04:49 +01001296 // Virtual sources must always be dynamicaly or explicitly routed
1297 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1298 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1299 return BAD_VALUE;
1300 }
1301 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1302 // in order to let the choice of the order to future vendor engine
1303 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001304
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001305 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001306 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001307 }
1308
Nadav Barb2f18162018-07-18 13:01:53 +03001309 // Set incall music only if device was explicitly set, and fallback to the device which is
1310 // chosen by the engine if not.
1311 // FIXME: provide a more generic approach which is not device specific and move this back
1312 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001313 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001314 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001315 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001316 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001317 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001318 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001319 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001320 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001321 }
1322 }
1323
François Gaffiec005e562018-11-06 15:04:49 +01001324 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1325 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1326 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001327
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001328 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001329 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001330 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001331 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001332 ALOGV("%s() Using MSD devices %s instead of devices %s",
1333 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001334 } else {
1335 *output = AUDIO_IO_HANDLE_NONE;
1336 }
1337 }
1338 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001339 sp<PreferredMixerAttributesInfo> info = nullptr;
1340 if (outputDevices.size() == 1) {
1341 info = getPreferredMixerAttributesInfo(
1342 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001343 mEngine->getProductStrategyForAttributes(*resultAttr),
1344 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001345 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1346 // and it is currently active.
1347 if (info != nullptr && info->getUid() != uid &&
1348 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1349 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001350 info = nullptr;
1351 }
1352 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001353 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001354 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001355 // The client will be active if the client is currently preferred mixer owner and the
1356 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001357 *isBitPerfect = (info != nullptr
1358 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001359 && info->getUid() == uid
1360 && *output != AUDIO_IO_HANDLE_NONE
1361 // When bit-perfect output is selected for the preferred mixer attributes owner,
1362 // only need to consider the config matches.
1363 && mOutputs.valueFor(*output)->isConfigurationMatched(
1364 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001365 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001366 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001367 AudioProfileVector profiles;
1368 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1369 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001370 const auto channels = profiles[0]->getChannels();
1371 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1372 config->channel_mask = *channels.begin();
1373 }
1374 const auto sampleRates = profiles[0]->getSampleRates();
1375 if (!sampleRates.empty() &&
1376 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1377 config->sample_rate = *sampleRates.begin();
1378 }
jiabinf1c73972022-04-14 16:28:52 -07001379 config->format = profiles[0]->getFormat();
1380 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001381 return INVALID_OPERATION;
1382 }
Paul McLeanaa981192015-03-21 09:55:15 -07001383
François Gaffiec005e562018-11-06 15:04:49 +01001384 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001385 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001386 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001387 *selectedDeviceId = outputDevice->getId();
1388 break;
1389 }
1390 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001391
Eric Laurent8a1095a2019-11-08 14:44:16 -08001392 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1393 *outputType = API_OUTPUT_TELEPHONY_TX;
1394 } else {
1395 *outputType = API_OUTPUT_LEGACY;
1396 }
1397
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001398 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1399
1400 return NO_ERROR;
1401}
1402
1403status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1404 audio_io_handle_t *output,
1405 audio_session_t session,
1406 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001407 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001408 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001409 audio_output_flags_t *flags,
1410 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001411 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001412 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001413 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001414 bool *isSpatialized,
1415 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001416{
1417 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1418 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1419 return INVALID_OPERATION;
1420 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001421 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001422 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001423 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001424 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001425 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001426 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001427 const sp<DeviceDescriptor> requestedDevice =
1428 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1429
1430 // Prevent from storing invalid requested device id in clients
1431 const audio_port_handle_t sanitizedRequestedPortId =
1432 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1433 *selectedDeviceId = sanitizedRequestedPortId;
1434
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001435 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001436 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001437 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1438 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001439 if (status != NO_ERROR) {
1440 return status;
1441 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001442 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001443 if (secondaryOutputs != nullptr) {
1444 for (auto &secondaryMix : secondaryMixes) {
1445 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1446 if (outputDesc != nullptr &&
1447 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1448 secondaryOutputs->push_back(outputDesc->mIoHandle);
1449 weakSecondaryOutputDescs.push_back(outputDesc);
1450 }
1451 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001452 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001453
Eric Laurent8fc147b2018-07-22 19:13:55 -07001454 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001455 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001456 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001457 };
jiabin4ef93452019-09-10 14:29:54 -07001458 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001459
Eric Laurentc209fe42020-06-05 18:11:23 -07001460 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001461 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001462 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001463 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001464 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001465 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001466 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001467 std::move(weakSecondaryOutputDescs),
1468 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001469 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001470
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001471 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1472 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001473
Eric Laurente83b55d2014-11-14 10:06:21 -08001474 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001475}
1476
Eric Laurentc529cf62020-04-17 18:19:10 -07001477status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1478 audio_session_t session,
1479 const audio_config_t *config,
1480 audio_output_flags_t flags,
1481 const DeviceVector &devices,
1482 audio_io_handle_t *output) {
1483
1484 *output = AUDIO_IO_HANDLE_NONE;
1485
1486 // skip direct output selection if the request can obviously be attached to a mixed output
1487 // and not explicitly requested
1488 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1489 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1490 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1491 return NAME_NOT_FOUND;
1492 }
1493
1494 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1495 // This prevents creating an offloaded track and tearing it down immediately after start
1496 // when audioflinger detects there is an active non offloadable effect.
1497 // FIXME: We should check the audio session here but we do not have it in this context.
1498 // This may prevent offloading in rare situations where effects are left active by apps
1499 // in the background.
1500 sp<IOProfile> profile;
1501 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1502 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1503 profile = getProfileForOutput(
1504 devices, config->sample_rate, config->format, config->channel_mask,
1505 flags, true /* directOnly */);
1506 }
1507
1508 if (profile == nullptr) {
1509 return NAME_NOT_FOUND;
1510 }
1511
1512 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1513 for (size_t i = 0; i < mOutputs.size(); i++) {
1514 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1515 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1516 // reuse direct output if currently open by the same client
1517 // and configured with same parameters
1518 if ((config->sample_rate == desc->getSamplingRate()) &&
1519 (config->format == desc->getFormat()) &&
1520 (config->channel_mask == desc->getChannelMask()) &&
1521 (session == desc->mDirectClientSession)) {
1522 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301523 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001524 mOutputs.keyAt(i), session);
1525 *output = mOutputs.keyAt(i);
1526 return NO_ERROR;
1527 }
1528 }
1529 }
1530
1531 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001532 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301533 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1534 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001535 return NAME_NOT_FOUND;
1536 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1537 // MMAP gracefully handles lack of an exclusive track resource by mixing
1538 // above the audio framework. For AAudio to know that the limit is reached,
1539 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301540 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1541 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001542 return NAME_NOT_FOUND;
1543 } else {
1544 // Close outputs on this profile, if available, to free resources for this request
1545 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1546 const auto desc = mOutputs.valueAt(i);
1547 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301548 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1549 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001550 closeOutput(desc->mIoHandle);
1551 }
1552 }
1553 }
1554 }
1555
1556 // Unable to close streams to find free resources for this request
1557 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301558 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1559 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001560 return NAME_NOT_FOUND;
1561 }
1562
Atneya Nairb16666a2023-12-11 20:18:33 -08001563 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001564
Michael Chan6fb34492020-12-08 15:44:49 +11001565 // An MSD patch may be using the only output stream that can service this request. Release
1566 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001567 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001568
Eric Laurentf1f22e72021-07-13 14:04:14 +02001569 status_t status =
1570 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001571
1572 // only accept an output with the requested parameters
1573 if (status != NO_ERROR ||
1574 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1575 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1576 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1577 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1578 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1579 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1580 config->channel_mask, outputDesc->getChannelMask());
1581 if (*output != AUDIO_IO_HANDLE_NONE) {
1582 outputDesc->close();
1583 }
1584 // fall back to mixer output if possible when the direct output could not be open
1585 if (audio_is_linear_pcm(config->format) &&
1586 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1587 return NAME_NOT_FOUND;
1588 }
1589 *output = AUDIO_IO_HANDLE_NONE;
1590 return BAD_VALUE;
1591 }
1592 outputDesc->mDirectOpenCount = 1;
1593 outputDesc->mDirectClientSession = session;
1594
1595 addOutput(*output, outputDesc);
1596 mPreviousOutputs = mOutputs;
1597 ALOGV("%s returns new direct output %d", __func__, *output);
1598 mpClientInterface->onAudioPortListUpdate();
1599 return NO_ERROR;
1600}
1601
François Gaffie11d30102018-11-02 16:09:09 +01001602audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1603 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001604 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001605 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001606 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001607 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001608 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001609 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001610 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001611{
Andy Hungc88b0642018-04-27 15:42:35 -07001612 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001613
jiabine375d412019-02-26 12:54:53 -08001614 // Discard haptic channel mask when forcing muting haptic channels.
1615 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001616 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1617 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001618
Eric Laurente552edb2014-03-10 17:42:56 -07001619 // open a direct output if required by specified parameters
1620 //force direct flag if offload flag is set: offloading implies a direct output stream
1621 // and all common behaviors are driven by checking only the direct flag
1622 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001623 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1624 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001625 }
Nadav Bar766fb022018-01-07 12:18:03 +02001626 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1627 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001628 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001629
1630 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1631
Eric Laurente83b55d2014-11-14 10:06:21 -08001632 // only allow deep buffering for music stream type
1633 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001634 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001635 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001636 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001637 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1638 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001639 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001640 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001641 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001642 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001643 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001644 audio_is_linear_pcm(config->format) &&
1645 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001646 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001647 AUDIO_OUTPUT_FLAG_DIRECT);
1648 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001649 }
Eric Laurente552edb2014-03-10 17:42:56 -07001650
Carter Hsua3abb402021-10-26 11:11:20 +08001651 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1652 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1653 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1654 }
1655
Eric Laurentf9230d52024-01-26 18:49:09 +01001656 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001657 // was specified and offload or direct playback is not explicitly requested, and there is no
1658 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001659 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001660 if (mSpatializerOutput != nullptr &&
1661 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1662 prefMixerConfigInfo == nullptr &&
1663 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1664 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001665 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001666 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001667 }
1668
Eric Laurentc529cf62020-04-17 18:19:10 -07001669 audio_config_t directConfig = *config;
1670 directConfig.channel_mask = channelMask;
1671 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1672 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001673 return output;
1674 }
1675
Eric Laurent14cbfca2016-03-17 09:42:16 -07001676 // A request for HW A/V sync cannot fallback to a mixed output because time
1677 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001678 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001679 return AUDIO_IO_HANDLE_NONE;
1680 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001681 // A request for Tuner cannot fallback to a mixed output
1682 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1683 return AUDIO_IO_HANDLE_NONE;
1684 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001685
Eric Laurente552edb2014-03-10 17:42:56 -07001686 // ignoring channel mask due to downmix capability in mixer
1687
1688 // open a non direct output
1689
1690 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001691 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001692 // get which output is suitable for the specified stream. The actual
1693 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001694 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001695 if (prefMixerConfigInfo != nullptr) {
1696 for (audio_io_handle_t outputHandle : outputs) {
1697 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1698 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1699 output = outputHandle;
1700 break;
1701 }
1702 }
1703 if (output == AUDIO_IO_HANDLE_NONE) {
1704 // No output open with the preferred profile. Open a new one.
1705 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1706 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1707 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1708 config.format = prefMixerConfigInfo->getConfigBase().format;
1709 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1710 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1711 &config, prefMixerConfigInfo->getFlags());
1712 if (preferredOutput == nullptr) {
1713 ALOGE("%s failed to open output with preferred mixer config", __func__);
1714 } else {
1715 output = preferredOutput->mIoHandle;
1716 }
1717 }
1718 } else {
1719 // at this stage we should ignore the DIRECT flag as no direct output could be
1720 // found earlier
1721 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1722 output = selectOutput(
1723 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1724 }
Eric Laurente552edb2014-03-10 17:42:56 -07001725 }
François Gaffie11d30102018-11-02 16:09:09 +01001726 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001727 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001728 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001729
Eric Laurente552edb2014-03-10 17:42:56 -07001730 return output;
1731}
1732
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001733sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001734 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1735 mAvailableInputDevices);
1736 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1737}
1738
1739DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1740 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1741 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742}
1743
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001745 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001746 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1747 if (msdModule != 0) {
1748 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1749 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1750 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1751 const struct audio_port_config *source = &patch->mPatch.sources[j];
1752 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1753 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001754 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001755 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001756 }
1757 }
1758 }
1759 return msdPatches;
1760}
1761
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001762bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1763 ssize_t index = mAudioPatches.indexOfKey(handle);
1764 if (index < 0) {
1765 return false;
1766 }
1767 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1768 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1769 if (msdModule == nullptr) {
1770 return false;
1771 }
1772 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1773 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1774 return true;
1775 }
1776 index = getMsdOutputPatches().indexOfKey(handle);
1777 if (index < 0) {
1778 return false;
1779 }
1780 return true;
1781}
1782
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001783status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1784 const InputProfileCollection &inputProfiles,
1785 const OutputProfileCollection &outputProfiles,
1786 const sp<DeviceDescriptor> &sourceDevice,
1787 const sp<DeviceDescriptor> &sinkDevice,
1788 AudioProfileVector& sourceProfiles,
1789 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001791 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001792 return NO_INIT;
1793 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001794 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001795 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001796 return NO_INIT;
1797 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001798 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001799 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1800 inProfile->supportsDevice(sourceDevice)) {
1801 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001802 }
1803 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001804 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001805 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001806 outProfile->supportsDevice(sinkDevice)) {
1807 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001808 }
1809 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001810 return NO_ERROR;
1811}
1812
1813status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1814 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1815 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1816{
Dean Wheatley16809da2022-12-09 14:55:46 +11001817 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1818 static const std::vector<audio_format_t> formatsOrder = {{
1819 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001820 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1821 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001822 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1823 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1824 // preferred).
1825 std::vector<audio_channel_mask_t> masks = {{
1826 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1827 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1828 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1829 // insert index masks (higher counts most preferred) as preferred over position masks
1830 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1831 masks.insert(
1832 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1833 }
1834 return masks;
1835 }();
1836
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001837 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001838 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1839 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001841 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1842 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001843 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 }
1845 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1846 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1847 sinkConfig->format = bestSinkConfig.format;
1848 // For encoded streams force direct flag to prevent downstream mixing.
1849 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1850 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001851 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1852 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001854 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1855 // raw and IEC61937 framed streams.
1856 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1857 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1858 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001859 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1860 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001861 sourceConfig->channel_mask =
1862 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1863 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1864 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001865 sourceConfig->format = bestSinkConfig.format;
1866 // Copy input stream directly without any processing (e.g. resampling).
1867 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1868 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1869 if (hwAvSync) {
1870 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1871 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1872 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1873 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1874 }
1875 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1876 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1877 sinkConfig->config_mask |= config_mask;
1878 sourceConfig->config_mask |= config_mask;
1879 return NO_ERROR;
1880}
1881
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1883 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884{
1885 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1887 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1888 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1889 if (deviceModule == nullptr) {
1890 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1891 return patchBuilder;
1892 }
1893 const InputProfileCollection inputProfiles = msdIsSource ?
1894 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1895 const OutputProfileCollection outputProfiles = msdIsSource ?
1896 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1897
1898 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1899 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1900 device : getMsdAudioOutDevices().itemAt(0);
1901 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1902
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1904 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001905 AudioProfileVector sourceProfiles;
1906 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1908 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001909 for (auto hwAvSync : { true, false }) {
1910 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1911 sourceProfiles, sinkProfiles) != NO_ERROR) {
1912 continue;
1913 }
1914 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1915 &sinkConfig) == NO_ERROR) {
1916 // Found a matching config. Re-create PatchBuilder with this config.
1917 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1918 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001919 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001920 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001921 " supporting PCM format conversion.", __func__);
1922 return patchBuilder;
1923}
1924
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001925status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001926 DeviceVector devices;
1927 if (outputDevices != nullptr && outputDevices->size() > 0) {
1928 devices.add(*outputDevices);
1929 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001930 // Use media strategy for unspecified output device. This should only
1931 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1932 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001933 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001934 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001935 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001936 }
Michael Chan6fb34492020-12-08 15:44:49 +11001937 std::vector<PatchBuilder> patchesToCreate;
1938 for (auto i = 0u; i < devices.size(); ++i) {
1939 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001940 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001941 }
1942 // Retain only the MSD patches associated with outputDevices request.
1943 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001944 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001945 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1946 auto retainedPatch = false;
1947 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1948 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1949 patchesToRemove.removeItemsAt(i);
1950 retainedPatch = true;
1951 break;
1952 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001953 }
Michael Chan6fb34492020-12-08 15:44:49 +11001954 if (retainedPatch) {
1955 it = patchesToCreate.erase(it);
1956 continue;
1957 }
1958 ++it;
1959 }
1960 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1961 return NO_ERROR;
1962 }
1963 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1964 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001965 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001966 }
Michael Chan6fb34492020-12-08 15:44:49 +11001967 status_t status = NO_ERROR;
1968 for (const auto &p : patchesToCreate) {
1969 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1970 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1971 char message[256];
1972 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1973 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1974 currStatus == NO_ERROR ? "Success" : "Error",
1975 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1976 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1977 if (currStatus == NO_ERROR) {
1978 ALOGD("%s", message);
1979 } else {
1980 ALOGE("%s", message);
1981 if (status == NO_ERROR) {
1982 status = currStatus;
1983 }
1984 }
1985 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001986 return status;
1987}
1988
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001989void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1990 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001991 for (size_t i = 0; i < msdPatches.size(); i++) {
1992 const auto& patch = msdPatches[i];
1993 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1994 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1995 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1996 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1997 releaseAudioPatch(patch->getHandle(), mUidCached);
1998 break;
1999 }
2000 }
2001 }
2002}
2003
Dorin Drimus94d94412022-02-02 09:05:02 +01002004bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002005 DeviceVector devicesToCheck =
2006 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002007 AudioPatchCollection msdPatches = getMsdOutputPatches();
2008 for (size_t i = 0; i < msdPatches.size(); i++) {
2009 const auto& patch = msdPatches[i];
2010 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2011 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2012 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2013 const auto& foundDevice = devicesToCheck.getDevice(
2014 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2015 if (foundDevice != nullptr) {
2016 devicesToCheck.remove(foundDevice);
2017 if (devicesToCheck.isEmpty()) {
2018 return true;
2019 }
2020 }
2021 }
2022 }
2023 }
2024 return false;
2025}
2026
Eric Laurente0720872014-03-11 09:30:41 -07002027audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002028 audio_output_flags_t flags,
2029 audio_format_t format,
2030 audio_channel_mask_t channelMask,
2031 uint32_t samplingRate,
2032 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002033{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002034 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2035 "%s called with format %#x", __func__, format);
2036
jiabinebb6af42020-06-09 17:31:17 -07002037 // Return the output that haptic-generating attached to when 1) session id is specified,
2038 // 2) haptic-generating effect exists for given session id and 3) the output that
2039 // haptic-generating effect attached to is in given outputs.
2040 if (sessionId != AUDIO_SESSION_NONE) {
2041 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2042 sessionId, FX_IID_HAPTICGENERATOR);
2043 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2044 return hapticGeneratingOutput;
2045 }
2046 }
2047
Eric Laurent16c66dd2019-05-01 17:54:10 -07002048 // Flags disqualifying an output: the match must happen before calling selectOutput()
2049 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2050 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2051
2052 // Flags expressing a functional request: must be honored in priority over
2053 // other criteria
2054 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2055 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002056 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2057 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002058 // Flags expressing a performance request: have lower priority than serving
2059 // requested sampling rate or channel mask
2060 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2061 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2062 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2063
2064 const audio_output_flags_t functionalFlags =
2065 (audio_output_flags_t)(flags & kFunctionalFlags);
2066 const audio_output_flags_t performanceFlags =
2067 (audio_output_flags_t)(flags & kPerformanceFlags);
2068
2069 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2070
Eric Laurente552edb2014-03-10 17:42:56 -07002071 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002072 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002073 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002074 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002075 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002076 // with tiebreak preferring the minimum number of extra functional flags
2077 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002078 // 3: the output supporting the exact channel mask
2079 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002080 // 5: the output with the highest sampling rate if the requested sample rate is
2081 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002082 // 6: the output with the highest number of requested performance flags
2083 // 7: the output with the bit depth the closest to the requested one
2084 // 8: the primary output
2085 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002086
Eric Laurent16c66dd2019-05-01 17:54:10 -07002087 // matching criteria values in priority order for best matching output so far
2088 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002089
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002090 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002091 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2092 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2093 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002094
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002095 for (audio_io_handle_t output : outputs) {
2096 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002097 // matching criteria values in priority order for current output
2098 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002099
Eric Laurent16c66dd2019-05-01 17:54:10 -07002100 if (outputDesc->isDuplicated()) {
2101 continue;
2102 }
2103 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2104 continue;
2105 }
Eric Laurent8838a382014-09-08 16:44:28 -07002106
Eric Laurent16c66dd2019-05-01 17:54:10 -07002107 // If haptic channel is specified, use the haptic output if present.
2108 // When using haptic output, same audio format and sample rate are required.
2109 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002110 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002111 // skip if haptic channel specified but output does not support it, or output support haptic
2112 // but there is no haptic channel requested AND no orphan haptic effect exist
2113 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2114 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002115 continue;
2116 }
Shunkai Yao808da212024-04-05 22:50:56 +00002117 // In the case of audio-coupled-haptic playback, there is no format conversion and
2118 // resampling in the framework, same format/channel/sampleRate for client and the output
2119 // thread is required. In the case of HapticGenerator effect, do not require format
2120 // matching.
2121 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2122 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002123 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002124 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002125 }
2126
2127 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002128 const int matchingFunctionalFlags =
2129 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2130 const int totalFunctionalFlags =
2131 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2132 // Prefer matching functional flags, but subtract unnecessary functional flags.
2133 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002134
2135 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002136 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2137 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002138 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2139 channelCount <= outputChannelCount) {
2140 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002141 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2142 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002143 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002144 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002145 currentMatchCriteria[3] = outputChannelCount;
2146 }
2147
2148 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002149 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002150 int diff; // avoid unsigned integer overflow.
2151 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2152
2153 // prefer the closest output sampling rate greater than or equal to target
2154 // if none exists, prefer the closest output sampling rate less than target.
2155 //
2156 // criteria is offset to make non-negative.
2157 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002158 }
2159
2160 // performance flags match
2161 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2162
2163 // format match
2164 if (format != AUDIO_FORMAT_INVALID) {
2165 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002166 PolicyAudioPort::kFormatDistanceMax -
2167 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002168 }
2169
2170 // primary output match
2171 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2172
2173 // compare match criteria by priority then value
2174 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2175 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2176 bestMatchCriteria = currentMatchCriteria;
2177 bestOutput = output;
2178
2179 std::stringstream result;
2180 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2181 std::ostream_iterator<int>(result, " "));
2182 ALOGV("%s new bestOutput %d criteria %s",
2183 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002184 }
2185 }
2186
Eric Laurent16c66dd2019-05-01 17:54:10 -07002187 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002188}
2189
Eric Laurent8fc147b2018-07-22 19:13:55 -07002190status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002191{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002192 ALOGV("%s portId %d", __FUNCTION__, portId);
2193
2194 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2195 if (outputDesc == 0) {
2196 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002197 return BAD_VALUE;
2198 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002199 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002200
Eric Laurent8fc147b2018-07-22 19:13:55 -07002201 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002202 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002203
Eric Laurent733ce942017-12-07 12:18:25 -08002204 status_t status = outputDesc->start();
2205 if (status != NO_ERROR) {
2206 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002207 }
2208
Eric Laurent97ac8712018-07-27 18:59:02 -07002209 uint32_t delayMs;
2210 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002211
2212 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002213 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002214 if (status == DEAD_OBJECT) {
2215 sp<SwAudioOutputDescriptor> desc =
2216 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2217 if (desc == nullptr) {
2218 // This is not common, it may indicate something wrong with the HAL.
2219 ALOGE("%s unable to open output with default config", __func__);
2220 return status;
2221 }
2222 desc->mUsePreferredMixerAttributes = true;
2223 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002224 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002225 }
jiabina84c3d32022-12-02 18:59:55 +00002226
2227 // If the client is the first one active on preferred mixer parameters, reopen the output
2228 // if the current mixer parameters doesn't match the preferred one.
2229 if (outputDesc->devices().size() == 1) {
2230 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2231 outputDesc->devices()[0]->getId(), client->strategy());
2232 if (info != nullptr && info->getUid() == client->uid()) {
2233 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2234 info->getConfigBase(), info->getFlags())) {
2235 stopSource(outputDesc, client);
2236 outputDesc->stop();
2237 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2238 config.channel_mask = info->getConfigBase().channel_mask;
2239 config.sample_rate = info->getConfigBase().sample_rate;
2240 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002241 sp<SwAudioOutputDescriptor> desc =
2242 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2243 if (desc == nullptr) {
2244 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002245 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002246 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002247 // Intentionally return error to let the client side resending request for
2248 // creating and starting.
2249 return DEAD_OBJECT;
2250 }
2251 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002252 if (info->getActiveClientCount() == 1 &&
2253 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2254 // If it is first bit-perfect client, reroute all clients that will be routed to
2255 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2256 PortHandleVector clientsToInvalidate;
2257 for (size_t i = 0; i < mOutputs.size(); i++) {
2258 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002259 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002260 continue;
2261 }
2262 for (const auto& c : mOutputs[i]->getClientIterable()) {
2263 clientsToInvalidate.push_back(c->portId());
2264 }
2265 }
2266 if (!clientsToInvalidate.empty()) {
2267 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2268 __func__);
2269 mpClientInterface->invalidateTracks(clientsToInvalidate);
2270 }
2271 }
jiabina84c3d32022-12-02 18:59:55 +00002272 }
2273 }
2274
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002275 if (client->hasPreferredDevice()) {
2276 // playback activity with preferred device impacts routing occurred, inform upper layers
2277 mpClientInterface->onRoutingUpdated();
2278 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002279 if (delayMs != 0) {
2280 usleep(delayMs * 1000);
2281 }
2282
2283 return status;
2284}
2285
Eric Laurent96d1dda2022-03-14 17:14:19 +01002286bool AudioPolicyManager::isLeUnicastActive() const {
2287 if (isInCall()) {
2288 return true;
2289 }
2290 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2291}
2292
2293bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2294 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2295 return false;
2296 }
2297 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2298 ALOGV("%s active %d", __func__, active);
2299 return active;
2300}
2301
Eric Laurent97ac8712018-07-27 18:59:02 -07002302status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2303 const sp<TrackClientDescriptor>& client,
2304 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002305{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002306 // cannot start playback of STREAM_TTS if any other output is being used
2307 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002308
2309 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002310 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002311 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002312 auto clientStrategy = client->strategy();
2313 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002314 if (stream == AUDIO_STREAM_TTS) {
2315 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002316 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002317 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002318 return INVALID_OPERATION;
2319 } else {
2320 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2321 }
2322 } else {
2323 // some playback other than beacon starts
2324 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2325 }
2326
Eric Laurent77305a62016-07-25 16:39:22 -07002327 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002328 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002329 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002330
François Gaffie11d30102018-11-02 16:09:09 +01002331 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002332 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002333 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002334 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002335 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002336 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002337 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002338 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002339 } else {
2340 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002341 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002342 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2343 AUDIO_FORMAT_DEFAULT);
2344 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2345 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002346 }
2347
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002348 // requiresMuteCheck is false when we can bypass mute strategy.
2349 // It covers a common case when there is no materially active audio
2350 // and muting would result in unnecessary delay and dropped audio.
2351 const uint32_t outputLatencyMs = outputDesc->latency();
2352 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002353 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002354
Eric Laurente552edb2014-03-10 17:42:56 -07002355 // increment usage count for this stream on the requested output:
2356 // NOTE that the usage count is the same for duplicated output and hardware output which is
2357 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002358 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002359
2360 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002361 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002362 // Preferred device may be exclusive, use only if no other active clients on this output
2363 devices = DeviceVector(
2364 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2365 } else {
2366 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2367 }
François Gaffie11d30102018-11-02 16:09:09 +01002368 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002369 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002370 }
2371 }
Eric Laurente552edb2014-03-10 17:42:56 -07002372
François Gaffiec005e562018-11-06 15:04:49 +01002373 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002374 selectOutputForMusicEffects();
2375 }
2376
François Gaffie1c878552018-11-22 16:53:21 +01002377 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002378 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002379 if (devices.isEmpty()) {
2380 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002381 }
François Gaffiec005e562018-11-06 15:04:49 +01002382 bool shouldWait =
2383 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2384 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2385 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002386 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002387 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002388 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002389 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002390 // An output has a shared device if
2391 // - managed by the same hw module
2392 // - supports the currently selected device
2393 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002394 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002395
Eric Laurent77305a62016-07-25 16:39:22 -07002396 // force a device change if any other output is:
2397 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002398 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002399 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002400 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002401 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002402 // change the device currently selected by the other output.
2403 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002404 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002405 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002406 force = true;
2407 }
2408 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002409 // a notification so that audio focus effect can propagate, or that a mute/unmute
2410 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002411 const uint32_t latencyMs = desc->latency();
2412 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2413
2414 if (shouldWait && isActive && (waitMs < latencyMs)) {
2415 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002416 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002417
2418 // Require mute check if another output is on a shared device
2419 // and currently active to have proper drain and avoid pops.
2420 // Note restoring AudioTracks onto this output needs to invoke
2421 // a volume ramp if there is no mute.
2422 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002423 }
2424 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002425
jiabin3ff8d7d2022-12-13 06:27:44 +00002426 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2427 // If the output is open with preferred mixer attributes, but the routed device is
2428 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2429 // changed.
2430 return DEAD_OBJECT;
2431 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002432 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302433 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2434 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002435
Eric Laurente552edb2014-03-10 17:42:56 -07002436 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002437 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002438 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002439 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002440 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002441 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002442 outputDesc->useHwGain() /*force*/)) {
2443 // request AudioService to reinitialize the volume curves asynchronously
2444 ALOGE("checkAndSetVolume failed, requesting volume range init");
2445 mpClientInterface->onVolumeRangeInitRequest();
2446 };
Eric Laurente552edb2014-03-10 17:42:56 -07002447
2448 // update the outputs if starting an output with a stream that can affect notification
2449 // routing
2450 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002451
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002452 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002453 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002454 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002455 }
Eric Laurentdc462862016-07-19 12:29:53 -07002456
2457 if (waitMs > muteWaitMs) {
2458 *delayMs = waitMs - muteWaitMs;
2459 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002460
2461 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2462 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2463 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2464 // change occurs after the MixerThread starts and causes a stream volume
2465 // glitch.
2466 //
2467 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002468 }
Eric Laurentdc462862016-07-19 12:29:53 -07002469
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002470 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002471 mEngine->getForceUse(
2472 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002473 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002474 }
2475
Eric Laurent97ac8712018-07-27 18:59:02 -07002476 // Automatically enable the remote submix input when output is started on a re routing mix
2477 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002478 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2479 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002480 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2481 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2482 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002483 "remote-submix",
2484 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002485 }
2486
Eric Laurent96d1dda2022-03-14 17:14:19 +01002487 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2488
Eric Laurente552edb2014-03-10 17:42:56 -07002489 return NO_ERROR;
2490}
2491
Eric Laurent96d1dda2022-03-14 17:14:19 +01002492void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2493 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2494 bool isUnicastActive = isLeUnicastActive();
2495
2496 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002497 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002498 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2499 for (size_t i = 0; i < mOutputs.size(); i++) {
2500 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2501 if (desc != ignoredOutput && desc->isActive()
2502 && ((isUnicastActive &&
2503 !desc->devices().
2504 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2505 || (wasUnicastActive &&
2506 !desc->devices().getDevicesFromTypes(
2507 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2508 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2509 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002510 if (desc->mUsePreferredMixerAttributes && force) {
2511 // If the device is using preferred mixer attributes, the output need to reopen
2512 // with default configuration when the new selected devices are different from
2513 // current routing devices.
2514 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2515 continue;
2516 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302517 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002518 // re-apply device specific volume if not done by setOutputDevice()
2519 if (!force) {
2520 applyStreamVolumes(desc, newDevices.types(), delayMs);
2521 }
2522 }
2523 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002524 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002525 }
2526}
2527
Eric Laurent8fc147b2018-07-22 19:13:55 -07002528status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002529{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002530 ALOGV("%s portId %d", __FUNCTION__, portId);
2531
2532 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2533 if (outputDesc == 0) {
2534 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002535 return BAD_VALUE;
2536 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002537 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002538
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002539 if (client->hasPreferredDevice(true)) {
2540 // playback activity with preferred device impacts routing occurred, inform upper layers
2541 mpClientInterface->onRoutingUpdated();
2542 }
2543
Eric Laurent97ac8712018-07-27 18:59:02 -07002544 ALOGV("stopOutput() output %d, stream %d, session %d",
2545 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002546
Eric Laurent97ac8712018-07-27 18:59:02 -07002547 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002548
Eric Laurent733ce942017-12-07 12:18:25 -08002549 if (status == NO_ERROR ) {
2550 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002551 } else {
2552 return status;
2553 }
2554
2555 if (outputDesc->devices().size() == 1) {
2556 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2557 outputDesc->devices()[0]->getId(), client->strategy());
2558 if (info != nullptr && info->getUid() == client->uid()) {
2559 info->decreaseActiveClient();
2560 if (info->getActiveClientCount() == 0) {
2561 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2562 }
2563 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002564 }
2565 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002566}
2567
Eric Laurent97ac8712018-07-27 18:59:02 -07002568status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2569 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002570{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002571 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002572 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002573 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002574 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002575
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002576 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2577
François Gaffie1c878552018-11-22 16:53:21 +01002578 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2579 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002580 // Automatically disable the remote submix input when output is stopped on a
2581 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002582 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002583 if (isSingleDeviceType(
2584 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002585 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002586 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002587 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2588 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002589 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002590 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002591 }
2592 }
2593 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002594 if (client->hasPreferredDevice(true) &&
2595 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002596 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002597 forceDeviceUpdate = true;
2598 }
2599
Eric Laurente552edb2014-03-10 17:42:56 -07002600 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002601 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002602
Eric Laurente552edb2014-03-10 17:42:56 -07002603 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002604 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002605 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002606 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002607
2608 // If the routing does not change, if an output is routed on a device using HwGain
2609 // (aka setAudioPortConfig) and there are still active clients following different
2610 // volume group(s), force reapply volume
2611 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2612 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2613
Eric Laurente552edb2014-03-10 17:42:56 -07002614 // delay the device switch by twice the latency because stopOutput() is executed when
2615 // the track stop() command is received and at that time the audio track buffer can
2616 // still contain data that needs to be drained. The latency only covers the audio HAL
2617 // and kernel buffers. Also the latency does not always include additional delay in the
2618 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302619 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002620 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002621
2622 // force restoring the device selection on other active outputs if it differs from the
2623 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002624 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002625 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002626 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002627 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002628 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002629 desc->isActive() &&
2630 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002631 (newDevices != desc->devices())) {
2632 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2633 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002634
jiabin3ff8d7d2022-12-13 06:27:44 +00002635 if (desc->mUsePreferredMixerAttributes && force) {
2636 // If the device is using preferred mixer attributes, the output need to
2637 // reopen with default configuration when the new selected devices are
2638 // different from current routing devices.
2639 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2640 continue;
2641 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302642 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002643
Eric Laurent57de36c2016-09-28 16:59:11 -07002644 // re-apply device specific volume if not done by setOutputDevice()
2645 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002646 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002647 }
Eric Laurente552edb2014-03-10 17:42:56 -07002648 }
2649 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002650 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002651 // update the outputs if stopping one with a stream that can affect notification routing
2652 handleNotificationRoutingForStream(stream);
2653 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002654
2655 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2656 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002657 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002658 }
2659
François Gaffiec005e562018-11-06 15:04:49 +01002660 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002661 selectOutputForMusicEffects();
2662 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002663
2664 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2665
Eric Laurente552edb2014-03-10 17:42:56 -07002666 return NO_ERROR;
2667 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002668 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002669 return INVALID_OPERATION;
2670 }
2671}
2672
jiabinbce0c1d2020-10-05 11:20:18 -07002673bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002674{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002675 ALOGV("%s portId %d", __FUNCTION__, portId);
2676
2677 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2678 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002679 // If an output descriptor is closed due to a device routing change,
2680 // then there are race conditions with releaseOutput from tracks
2681 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2682 // destroyed shortly thereafter.
2683 //
2684 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002685 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002686 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002687 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002688
2689 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002690
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302691 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2692 if (outputDesc->isClientActive(client)) {
2693 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2694 stopOutput(portId);
2695 }
2696
Eric Laurent8fc147b2018-07-22 19:13:55 -07002697 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2698 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002699 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002700 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002701 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002702 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002703 if (--outputDesc->mDirectOpenCount == 0) {
2704 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002705 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002706 }
2707 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302708
Andy Hung39efb7a2018-09-26 15:39:28 -07002709 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002710 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2711 // The output is pending reopened to query dynamic profiles and
2712 // there is no active clients
2713 closeOutput(outputDesc->mIoHandle);
2714 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2715 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2716 if (newOutputDesc == nullptr) {
2717 ALOGE("%s failed to open output", __func__);
2718 }
2719 return true;
2720 }
2721 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002722}
2723
Eric Laurentcaf7f482014-11-25 17:50:47 -08002724status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2725 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002726 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002727 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002728 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002729 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002730 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002731 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002732 input_type_t *inputType,
2733 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002734{
François Gaffiec005e562018-11-06 15:04:49 +01002735 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002736 "flags %#x attributes=%s requested device ID %d",
2737 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2738 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002739
Eric Laurentad2e7b92017-09-14 20:06:42 -07002740 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002741 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002742 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002743 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002744 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002745 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002746 sp<RecordClientDescriptor> clientDesc;
2747 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002748 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002749 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002750
2751 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2752 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2753 return INVALID_OPERATION;
2754 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002755
Francois Gaffie716e1432019-01-14 16:58:59 +01002756 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2757 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002758 }
2759
Paul McLean466dc8e2015-04-17 13:15:36 -06002760 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002761 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002762 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002763
Eric Laurentad2e7b92017-09-14 20:06:42 -07002764 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2765 // possible
2766 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2767 *input != AUDIO_IO_HANDLE_NONE) {
2768 ssize_t index = mInputs.indexOfKey(*input);
2769 if (index < 0) {
2770 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2771 status = BAD_VALUE;
2772 goto error;
2773 }
2774 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002775 RecordClientVector clients = inputDesc->getClientsForSession(session);
2776 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002777 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2778 status = BAD_VALUE;
2779 goto error;
2780 }
2781 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2782 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002783 // corresponds to a new client and is only permitted from the same UID.
2784 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002785 if (clients.size() > 1) {
2786 for (const auto& client : clients) {
2787 // The client map is ordered by key values (portId) and portIds are allocated
2788 // incrementaly. So the first client in this list is the one opened by audio flinger
2789 // when the mmap stream is created and should be ignored as it does not correspond
2790 // to an actual client
2791 if (client == *clients.cbegin()) {
2792 continue;
2793 }
2794 if (uid != client->uid() && !client->isSilenced()) {
2795 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2796 uid, client->portId(), client->uid());
2797 status = INVALID_OPERATION;
2798 goto error;
2799 }
Eric Laurent331679c2018-04-16 17:03:16 -07002800 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002801 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002802 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002803 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002804
Eric Laurentfecbceb2021-02-09 14:46:43 +01002805 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002806 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002807 }
2808
2809 *input = AUDIO_IO_HANDLE_NONE;
2810 *inputType = API_INPUT_INVALID;
2811
Francois Gaffie716e1432019-01-14 16:58:59 +01002812 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002813 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002814 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002815 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002816 ALOGW("%s could not find input mix for attr %s",
2817 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002818 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002819 }
jiabinc1de2df2019-05-07 14:26:40 -07002820 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2821 String8(attr->tags + strlen("addr=")),
2822 AUDIO_FORMAT_DEFAULT);
2823 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002824 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002825 __func__, attributes.source, attributes.tags);
2826 status = BAD_VALUE;
2827 goto error;
2828 }
2829
Kevin Rocard25f9b052019-02-27 15:08:54 -08002830 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2831 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2832 } else {
2833 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2834 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002835 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002836 if (explicitRoutingDevice != nullptr) {
2837 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002838 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002839 // Prevent from storing invalid requested device id in clients
2840 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002841 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002842 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2843 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002844 }
François Gaffie11d30102018-11-02 16:09:09 +01002845 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002846 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002847 status = BAD_VALUE;
2848 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002849 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002850 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2851 *inputType = API_INPUT_MIX_CAPTURE;
2852 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002853 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2854 // there is an external policy, but this input is attached to a mix of recorders,
2855 // meaning it receives audio injected into the framework, so the recorder doesn't
2856 // know about it and is therefore considered "legacy"
2857 *inputType = API_INPUT_LEGACY;
2858 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002859 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002860 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002861 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002862 } else {
2863 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002864 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002865
Eric Laurent599c7582015-12-07 18:05:55 -08002866 }
2867
François Gaffiec005e562018-11-06 15:04:49 +01002868 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002869 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002870 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002871 AudioProfileVector profiles;
2872 status_t ret = getProfilesForDevices(
2873 DeviceVector(device), profiles, flags, true /*isInput*/);
2874 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002875 const auto channels = profiles[0]->getChannels();
2876 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2877 config->channel_mask = *channels.begin();
2878 }
2879 const auto sampleRates = profiles[0]->getSampleRates();
2880 if (!sampleRates.empty() &&
2881 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2882 config->sample_rate = *sampleRates.begin();
2883 }
jiabinf1c73972022-04-14 16:28:52 -07002884 config->format = profiles[0]->getFormat();
2885 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002886 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002887 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002888
Eric Laurent8f42ea12018-08-08 09:08:25 -07002889exit:
2890
François Gaffiec005e562018-11-06 15:04:49 +01002891 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2892 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002893
Francois Gaffie716e1432019-01-14 16:58:59 +01002894 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002895 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002896 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002897
Mikhail Naganov2996f672019-04-18 12:29:59 -07002898 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002899 requestedDeviceId, attributes.source, flags,
2900 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002901 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002902 // Move (if found) effect for the client session to its input
2903 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002904 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002905
2906 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2907 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002908
Eric Laurent599c7582015-12-07 18:05:55 -08002909 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002910
2911error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002912 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002913}
2914
2915
François Gaffie11d30102018-11-02 16:09:09 +01002916audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002917 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002918 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002919 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002920 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002921 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002922{
2923 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002924 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002925 bool isSoundTrigger = false;
2926
François Gaffiec005e562018-11-06 15:04:49 +01002927 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002928 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2929 if (index >= 0) {
2930 input = mSoundTriggerSessions.valueFor(session);
2931 isSoundTrigger = true;
2932 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2933 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2934 } else {
2935 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002936 }
François Gaffiec005e562018-11-06 15:04:49 +01002937 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002938 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002939 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002940 }
2941
Carter Hsua3abb402021-10-26 11:11:20 +08002942 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2943 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2944 }
2945
Eric Laurentfe231122017-11-17 17:48:06 -08002946 // sampling rate and flags may be updated by getInputProfile
2947 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2948 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002949 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002950 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002951 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002952 // find a compatible input profile (not necessarily identical in parameters)
2953 sp<IOProfile> profile = getInputProfile(
2954 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2955 if (profile == nullptr) {
2956 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002957 }
jiabin2fd710d2022-05-02 23:20:22 +00002958
Glenn Kasten05ddca52016-02-11 08:17:12 -08002959 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002960 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002961 if (samplingRate == 0) {
2962 samplingRate = profileSamplingRate;
2963 }
Eric Laurente552edb2014-03-10 17:42:56 -07002964
Eric Laurent322b4d22015-04-03 15:57:54 -07002965 if (profile->getModuleHandle() == 0) {
2966 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002967 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002968 }
2969
Eric Laurentec376dc2021-04-08 20:41:22 +02002970 // Reuse an already opened input if a client with the same session ID already exists
2971 // on that input
2972 for (size_t i = 0; i < mInputs.size(); i++) {
2973 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2974 if (desc->mProfile != profile) {
2975 continue;
2976 }
2977 RecordClientVector clients = desc->clientsList();
2978 for (const auto &client : clients) {
2979 if (session == client->session()) {
2980 return desc->mIoHandle;
2981 }
2982 }
2983 }
2984
Eric Laurent3974e3b2017-12-07 17:58:43 -08002985 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002986 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002987 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002988 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002989 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002990 continue;
2991 }
2992 // if sound trigger, reuse input if used by other sound trigger on same session
2993 // else
2994 // reuse input if active client app is not in IDLE state
2995 //
2996 RecordClientVector clients = desc->clientsList();
2997 bool doClose = false;
2998 for (const auto& client : clients) {
2999 if (isSoundTrigger != client->isSoundTrigger()) {
3000 continue;
3001 }
3002 if (client->isSoundTrigger()) {
3003 if (session == client->session()) {
3004 return desc->mIoHandle;
3005 }
3006 continue;
3007 }
3008 if (client->active() && client->appState() != APP_STATE_IDLE) {
3009 return desc->mIoHandle;
3010 }
3011 doClose = true;
3012 }
3013 if (doClose) {
3014 closeInput(desc->mIoHandle);
3015 } else {
3016 i++;
3017 }
3018 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003019 }
3020
Eric Laurentfe231122017-11-17 17:48:06 -08003021 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003022
Eric Laurentfe231122017-11-17 17:48:06 -08003023 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3024 lConfig.sample_rate = profileSamplingRate;
3025 lConfig.channel_mask = profileChannelMask;
3026 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003027
François Gaffie11d30102018-11-02 16:09:09 +01003028 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003029
3030 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003031 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003032 (profileSamplingRate != lConfig.sample_rate) ||
3033 !audio_formats_match(profileFormat, lConfig.format) ||
3034 (profileChannelMask != lConfig.channel_mask)) {
3035 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003036 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003037 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003038 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003039 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003040 }
Eric Laurent599c7582015-12-07 18:05:55 -08003041 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003042 }
3043
Eric Laurentc722f302014-12-10 11:21:49 -08003044 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003045
Eric Laurent599c7582015-12-07 18:05:55 -08003046 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003047 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003048
Eric Laurent599c7582015-12-07 18:05:55 -08003049 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003050}
3051
Eric Laurent4eb58f12018-12-07 16:41:02 -08003052status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003053{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003054 ALOGV("%s portId %d", __FUNCTION__, portId);
3055
3056 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3057 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003059 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003060 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003061 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003062 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003063 if (client->active()) {
3064 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3065 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003066 }
3067
Eric Laurent8f42ea12018-08-08 09:08:25 -07003068 audio_session_t session = client->session();
3069
Eric Laurent4eb58f12018-12-07 16:41:02 -08003070 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071
Eric Laurent4eb58f12018-12-07 16:41:02 -08003072 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003073
Eric Laurent4eb58f12018-12-07 16:41:02 -08003074 status_t status = inputDesc->start();
3075 if (status != NO_ERROR) {
3076 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003077 }
Eric Laurente552edb2014-03-10 17:42:56 -07003078
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003079 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003080 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003081 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003082
Eric Laurent8f42ea12018-08-08 09:08:25 -07003083 // indicate active capture to sound trigger service if starting capture from a mic on
3084 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003085 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003086 if (device != nullptr) {
3087 status = setInputDevice(input, device, true /* force */);
3088 } else {
3089 ALOGW("%s no new input device can be found for descriptor %d",
3090 __FUNCTION__, inputDesc->getId());
3091 status = BAD_VALUE;
3092 }
Eric Laurente552edb2014-03-10 17:42:56 -07003093
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003094 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003095 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003096 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003097 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003098 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3099 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003101 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003102
François Gaffie11d30102018-11-02 16:09:09 +01003103 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3104 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003106 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003107 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003108
Eric Laurent8f42ea12018-08-08 09:08:25 -07003109 // automatically enable the remote submix output when input is started if not
3110 // used by a policy mix of type MIX_TYPE_RECORDERS
3111 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003112 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003113 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003114 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003115 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003116 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3117 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003118 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003119 if (address != "") {
3120 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3121 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003122 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003123 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003124 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003125 } else if (status != NO_ERROR) {
3126 // Restore client activity state.
3127 inputDesc->setClientActive(client, false);
3128 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003129 }
3130
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003131 ALOGV("%s input %d source = %d status = %d exit",
3132 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003133
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003134 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003135}
3136
Eric Laurent8fc147b2018-07-22 19:13:55 -07003137status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003138{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003139 ALOGV("%s portId %d", __FUNCTION__, portId);
3140
3141 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3142 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003144 return BAD_VALUE;
3145 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003146 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003147 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003148 if (!client->active()) {
3149 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003150 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003151 }
Carter Hsue6139d52021-07-08 10:30:20 +08003152 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003153 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003154
Eric Laurent8f42ea12018-08-08 09:08:25 -07003155 inputDesc->stop();
3156 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003157 auto current_source = inputDesc->source();
3158 setInputDevice(input, getNewInputDevice(inputDesc),
3159 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003160 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003161 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003162 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003163 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003164 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3165 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003166 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003167 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003168
3169 // automatically disable the remote submix output when input is stopped if not
3170 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003171 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003172 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003173 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003174 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003175 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3176 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003177 }
3178 if (address != "") {
3179 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3180 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003181 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003182 }
3183 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003184 resetInputDevice(input);
3185
3186 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3187 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003188 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3189 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003190 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003191 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003192 }
3193 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003194 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003195 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003196}
3197
Eric Laurent8fc147b2018-07-22 19:13:55 -07003198void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003199{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003200 ALOGV("%s portId %d", __FUNCTION__, portId);
3201
3202 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3203 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003204 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003205 return;
3206 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003207 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003208 audio_io_handle_t input = inputDesc->mIoHandle;
3209
Eric Laurent8f42ea12018-08-08 09:08:25 -07003210 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003211
Andy Hung39efb7a2018-09-26 15:39:28 -07003212 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003213 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003214 if (inputDesc->getClientCount() > 0) {
3215 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003216 return;
3217 }
3218
Eric Laurent05b90f82014-08-27 15:32:29 -07003219 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003220 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003221 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003222}
3223
Eric Laurent8f42ea12018-08-08 09:08:25 -07003224void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003225{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003226 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003227
3228 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003229 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003230 }
3231}
3232
Eric Laurent8f42ea12018-08-08 09:08:25 -07003233void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3234{
3235 stopInput(portId);
3236 releaseInput(portId);
3237}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003238
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003239bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3240 if (input->clientsList().size() == 0
3241 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3242 return true;
3243 }
3244 for (const auto& client : input->clientsList()) {
3245 sp<DeviceDescriptor> device =
3246 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3247 client->session());
3248 if (!input->supportedDevices().contains(device)) {
3249 return true;
3250 }
3251 }
3252 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3253 return false;
3254}
3255
Eric Laurent0dd51852019-04-19 18:18:58 -07003256void AudioPolicyManager::checkCloseInputs() {
3257 // After connecting or disconnecting an input device, close input if:
3258 // - it has no client (was just opened to check profile) OR
3259 // - none of its supported devices are connected anymore OR
3260 // - one of its clients cannot be routed to one of its supported
3261 // devices anymore. Otherwise update device selection
3262 std::vector<audio_io_handle_t> inputsToClose;
3263 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003264 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003265 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003266 }
3267 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003268 for (const audio_io_handle_t handle : inputsToClose) {
3269 ALOGV("%s closing input %d", __func__, handle);
3270 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003271 }
Eric Laurentd4692962014-05-05 18:13:44 -07003272}
3273
François Gaffie251c7f02018-11-07 10:41:08 +01003274void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003275{
3276 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003277 if (indexMin < 0 || indexMax < 0) {
3278 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3279 return;
3280 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003281 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003282
3283 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003284 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3285 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003286 continue;
3287 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003288 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003289 }
Eric Laurente552edb2014-03-10 17:42:56 -07003290}
3291
Eric Laurente0720872014-03-11 09:30:41 -07003292status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003293 int index,
3294 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003295{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003296 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003297 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3298 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3299 return NO_ERROR;
3300 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303301 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3302 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003303 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003304}
3305
Eric Laurente0720872014-03-11 09:30:41 -07003306status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003307 int *index,
3308 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003309{
François Gaffiec005e562018-11-06 15:04:49 +01003310 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3311 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003312 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003313 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003314 deviceTypes = mEngine->getOutputDevicesForStream(
3315 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003316 }
jiabin9a3361e2019-10-01 09:38:30 -07003317 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003318}
3319
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003320status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003321 int index,
3322 audio_devices_t device)
3323{
3324 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003325 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3326 if (group == VOLUME_GROUP_NONE) {
3327 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003328 return BAD_VALUE;
3329 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003330 ALOGV("%s: group %d matching with %s index %d",
3331 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003332 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003333 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003334 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003335 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3336 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3337 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3338 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003339 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3340
3341 status = setVolumeCurveIndex(index, device, curves);
3342 if (status != NO_ERROR) {
3343 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3344 return status;
3345 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003346
jiabin9a3361e2019-10-01 09:38:30 -07003347 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003348 auto curCurvAttrs = curves.getAttributes();
3349 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3350 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003351 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003352 } else if (!curves.getStreamTypes().empty()) {
3353 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003354 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003355 } else {
3356 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3357 return BAD_VALUE;
3358 }
jiabin9a3361e2019-10-01 09:38:30 -07003359 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3360 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003361
François Gaffiecfe17322018-11-07 13:41:29 +01003362 // update volume on all outputs and streams matching the following:
3363 // - The requested stream (or a stream matching for volume control) is active on the output
3364 // - The device (or devices) selected by the engine for this stream includes
3365 // the requested device
3366 // - For non default requested device, currently selected device on the output is either the
3367 // requested device or one of the devices selected by the engine for this stream
3368 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3369 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003370 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003371 for (size_t i = 0; i < mOutputs.size(); i++) {
3372 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003373 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003374
jiabin9a3361e2019-10-01 09:38:30 -07003375 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3376 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003377 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003378
3379 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003380 continue;
3381 }
3382 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3383 curDevices.find(device) == curDevices.end()) {
3384 continue;
3385 }
3386 bool applyVolume = false;
3387 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3388 curSrcDevices.insert(device);
3389 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003390 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3391 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003392 } else {
3393 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3394 }
3395 if (!applyVolume) {
3396 continue; // next output
3397 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003398 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3399 // If a higher priority strategy is active, and the output is routed to a device with a
3400 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003401 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003402 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003403 // If the volume source is active with higher priority source, ensure at least Sw Muted
3404 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003405 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3406 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3407 false /*preferredDevice*/);
3408 if (activeClients.empty()) {
3409 continue;
3410 }
3411 bool isPreempted = false;
3412 bool isHigherPriority = productStrategy < strategy;
3413 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003414 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003415 ALOGV("%s: Strategy=%d (\nrequester:\n"
3416 " group %d, volumeGroup=%d attributes=%s)\n"
3417 " higher priority source active:\n"
3418 " volumeGroup=%d attributes=%s) \n"
3419 " on output %zu, bailing out", __func__, productStrategy,
3420 group, group, toString(attributes).c_str(),
3421 client->volumeSource(), toString(client->attributes()).c_str(), i);
3422 applyVolume = false;
3423 isPreempted = true;
3424 break;
3425 }
3426 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003427 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003428 applyVolume = true;
3429 }
3430 }
3431 if (isPreempted || applyVolume) {
3432 break;
3433 }
3434 }
3435 if (!applyVolume) {
3436 continue; // next output
3437 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003438 }
François Gaffieed91f582020-01-31 10:35:37 +01003439 //FIXME: workaround for truncated touch sounds
3440 // delayed volume change for system stream to be removed when the problem is
3441 // handled by system UI
3442 status_t volStatus = checkAndSetVolume(
3443 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003444 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003445 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3446 if (volStatus != NO_ERROR) {
3447 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003448 }
3449 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003450
3451 // update voice volume if the an active call route exists
3452 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3453 && (curSrcDevices.find(
3454 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3455 != curSrcDevices.end())) {
3456 bool isVoiceVolSrc;
3457 bool isBtScoVolSrc;
3458 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3459 isVoiceVolSrc, isBtScoVolSrc, __func__)
3460 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003461 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3462 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3463 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003464 }
3465 }
3466
François Gaffiecfe17322018-11-07 13:41:29 +01003467 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3468 return status;
3469}
3470
François Gaffieaaac0fd2018-11-22 17:56:39 +01003471status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003472 audio_devices_t device,
3473 IVolumeCurves &volumeCurves)
3474{
3475 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3476 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003477 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3478 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003479 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303480 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3481 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003482 return BAD_VALUE;
3483 }
3484 if (!audio_is_output_device(device)) {
3485 return BAD_VALUE;
3486 }
3487
3488 // Force max volume if stream cannot be muted
3489 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3490
François Gaffieaaac0fd2018-11-22 17:56:39 +01003491 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003492 volumeCurves.addCurrentVolumeIndex(device, index);
3493 return NO_ERROR;
3494}
3495
3496status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3497 int &index,
3498 audio_devices_t device)
3499{
3500 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3501 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003502 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003503 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003504 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003505 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003506 }
jiabin9a3361e2019-10-01 09:38:30 -07003507 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003508}
3509
3510status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3511 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003512 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003513{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003514 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003515 return BAD_VALUE;
3516 }
jiabin9a3361e2019-10-01 09:38:30 -07003517 index = curves.getVolumeIndex(deviceTypes);
3518 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003519 return NO_ERROR;
3520}
3521
3522status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3523 int &index)
3524{
3525 index = getVolumeCurves(attr).getVolumeIndexMin();
3526 return NO_ERROR;
3527}
3528
3529status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3530 int &index)
3531{
3532 index = getVolumeCurves(attr).getVolumeIndexMax();
3533 return NO_ERROR;
3534}
3535
Eric Laurent36829f92017-04-07 19:04:42 -07003536audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003537{
3538 // select one output among several suitable for global effects.
3539 // The priority is as follows:
3540 // 1: An offloaded output. If the effect ends up not being offloadable,
3541 // AudioFlinger will invalidate the track and the offloaded output
3542 // will be closed causing the effect to be moved to a PCM output.
3543 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003544 // 3: The primary output
3545 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003546
François Gaffiec005e562018-11-06 15:04:49 +01003547 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3548 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003549 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003550
Eric Laurent36829f92017-04-07 19:04:42 -07003551 if (outputs.size() == 0) {
3552 return AUDIO_IO_HANDLE_NONE;
3553 }
Eric Laurente552edb2014-03-10 17:42:56 -07003554
Eric Laurent36829f92017-04-07 19:04:42 -07003555 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3556 bool activeOnly = true;
3557
3558 while (output == AUDIO_IO_HANDLE_NONE) {
3559 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3560 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3561 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3562
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003563 for (audio_io_handle_t output : outputs) {
3564 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003565 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003566 continue;
3567 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003568 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3569 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003570 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003571 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003572 }
3573 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003574 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003575 }
3576 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003577 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003578 }
3579 }
3580 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3581 output = outputOffloaded;
3582 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3583 output = outputDeepBuffer;
3584 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3585 output = outputPrimary;
3586 } else {
3587 output = outputs[0];
3588 }
3589 activeOnly = false;
3590 }
3591
3592 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003593 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3594 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003595 mMusicEffectOutput = output;
3596 }
3597
3598 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003599 return output;
3600}
3601
Eric Laurent36829f92017-04-07 19:04:42 -07003602audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3603{
3604 return selectOutputForMusicEffects();
3605}
3606
Eric Laurente0720872014-03-11 09:30:41 -07003607status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003608 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003609 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003610 int session,
3611 int id)
3612{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003613 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003614 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003615 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003616 index = mInputs.indexOfKey(io);
3617 if (index < 0) {
3618 ALOGW("registerEffect() unknown io %d", io);
3619 return INVALID_OPERATION;
3620 }
Eric Laurente552edb2014-03-10 17:42:56 -07003621 }
3622 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003623 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3624 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3625 || strategy == PRODUCT_STRATEGY_NONE));
3626 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003627}
3628
Eric Laurentc241b0d2018-11-28 09:08:49 -08003629status_t AudioPolicyManager::unregisterEffect(int id)
3630{
3631 if (mEffects.getEffect(id) == nullptr) {
3632 return INVALID_OPERATION;
3633 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003634 if (mEffects.isEffectEnabled(id)) {
3635 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3636 setEffectEnabled(id, false);
3637 }
3638 return mEffects.unregisterEffect(id);
3639}
3640
3641status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3642{
3643 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3644 if (effect == nullptr) {
3645 return INVALID_OPERATION;
3646 }
3647
3648 status_t status = mEffects.setEffectEnabled(id, enabled);
3649 if (status == NO_ERROR) {
3650 mInputs.trackEffectEnabled(effect, enabled);
3651 }
3652 return status;
3653}
3654
Eric Laurent6c796322019-04-09 14:13:17 -07003655
3656status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3657{
3658 mEffects.moveEffects(ids, io);
3659 return NO_ERROR;
3660}
3661
Eric Laurentc75307b2015-03-17 15:29:32 -07003662bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3663{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003664 auto vs = toVolumeSource(stream, false);
3665 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003666}
3667
3668bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3669{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003670 auto vs = toVolumeSource(stream, false);
3671 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003672}
3673
Eric Laurente0720872014-03-11 09:30:41 -07003674bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003675{
3676 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003677 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003678 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003679 return true;
3680 }
3681 }
3682 return false;
3683}
3684
Eric Laurent275e8e92014-11-30 15:14:47 -08003685// Register a list of custom mixes with their attributes and format.
3686// When a mix is registered, corresponding input and output profiles are
3687// added to the remote submix hw module. The profile contains only the
3688// parameters (sampling rate, format...) specified by the mix.
3689// The corresponding input remote submix device is also connected.
3690//
3691// When a remote submix device is connected, the address is checked to select the
3692// appropriate profile and the corresponding input or output stream is opened.
3693//
3694// When capture starts, getInputForAttr() will:
3695// - 1 look for a mix matching the address passed in attribtutes tags if any
3696// - 2 if none found, getDeviceForInputSource() will:
3697// - 2.1 look for a mix matching the attributes source
3698// - 2.2 if none found, default to device selection by policy rules
3699// At this time, the corresponding output remote submix device is also connected
3700// and active playback use cases can be transferred to this mix if needed when reconnecting
3701// after AudioTracks are invalidated
3702//
3703// When playback starts, getOutputForAttr() will:
3704// - 1 look for a mix matching the address passed in attribtutes tags if any
3705// - 2 if none found, look for a mix matching the attributes usage
3706// - 3 if none found, default to device and output selection by policy rules.
3707
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003708status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003709{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003710 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3711 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003712 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003713 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003714 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003715 // examine each mix's route type
3716 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003717 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003718 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3719 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3720 ALOGE("Unsupported Policy Mix %zu of %zu: "
3721 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3722 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003723 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003724 break;
3725 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003726 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3727 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003728 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003729 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3730 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003731 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003732 rSubmixModule = mHwModules.getModuleFromName(
3733 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3734 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003735 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003736 i);
3737 res = INVALID_OPERATION;
3738 break;
3739 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003740 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003741
Eric Laurent97ac8712018-07-27 18:59:02 -07003742 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003743 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003744 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003745 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003746 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3747 } else {
3748 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3749 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003750 }
François Gaffie036e1e92015-03-19 10:16:24 +01003751
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003752 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003753 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003754 res = INVALID_OPERATION;
3755 break;
3756 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003757 audio_config_t outputConfig = mix.mFormat;
3758 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003759 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3760 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003761 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3762 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003763 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003764 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3765 audio_is_linear_pcm(outputConfig.format)
3766 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003767 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003768 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3769 audio_is_linear_pcm(inputConfig.format)
3770 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003771
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003772 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003773 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003774 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003775 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003776 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003777 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003778 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003779 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3780 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003781 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003782 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003783 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003784
3785 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3786 mix.mDeviceType, mix.mDeviceAddress,
3787 String8(), AUDIO_FORMAT_DEFAULT);
3788 if (device == nullptr) {
3789 res = INVALID_OPERATION;
3790 break;
3791 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003792
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003793 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003794 // First try to find an already opened output supporting the device
3795 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003796 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003797
Eric Laurentc529cf62020-04-17 18:19:10 -07003798 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003799 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003800 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003801 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003802 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003803 } else {
3804 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003805 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003806 }
3807 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003808 // If no output found, try to find a direct output profile supporting the device
3809 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3810 sp<HwModule> module = mHwModules[i];
3811 for (size_t j = 0;
3812 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3813 j++) {
3814 sp<IOProfile> profile = module->getOutputProfiles()[j];
3815 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3816 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3817 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003818 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003819 res = INVALID_OPERATION;
3820 } else {
3821 foundOutput = true;
3822 }
3823 }
3824 }
3825 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003826 if (res != NO_ERROR) {
3827 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003828 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003829 res = INVALID_OPERATION;
3830 break;
3831 } else if (!foundOutput) {
3832 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003833 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003834 res = INVALID_OPERATION;
3835 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003836 } else {
3837 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003838 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003839 }
Eric Laurentc722f302014-12-10 11:21:49 -08003840 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003841 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003842 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003843 if (audio_flags::audio_mix_ownership()) {
3844 // Only unregister mixes that were actually registered to not accidentally unregister
3845 // mixes that already existed previously.
3846 unregisterPolicyMixes(registeredMixes);
3847 registeredMixes.clear();
3848 } else {
3849 unregisterPolicyMixes(mixes);
3850 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003851 } else if (checkOutputs) {
3852 checkForDeviceAndOutputChanges();
3853 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003854 }
3855 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003856}
3857
3858status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3859{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003860 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Marvin Raminabd9b892023-11-17 16:36:27 +01003861 status_t endResult = NO_ERROR;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003862 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003863 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003864 sp<HwModule> rSubmixModule;
3865 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003866 for (const auto& mix : mixes) {
3867 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003868
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003869 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003870 rSubmixModule = mHwModules.getModuleFromName(
3871 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3872 if (rSubmixModule == 0) {
3873 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003874 endResult = INVALID_OPERATION;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003875 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003876 }
3877 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003878
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003879 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003880
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003881 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003882 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003883 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003884 continue;
3885 }
3886
Kevin Rocard04ed0462019-05-02 17:53:24 -07003887 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003888 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003889 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3890 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003891 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003892 AUDIO_FORMAT_DEFAULT);
3893 if (res != OK) {
3894 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003895 "with type %d, address %s", device, address.c_str());
Marvin Raminabd9b892023-11-17 16:36:27 +01003896 endResult = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07003897 }
3898 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003899 }
jiabin5740f082019-08-19 15:08:30 -07003900 rSubmixModule->removeOutputProfile(address.c_str());
3901 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003902
Kevin Rocard153f92d2018-12-18 18:33:28 -08003903 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003904 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003905 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003906 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003907 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003908 } else {
3909 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003910 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003911 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003912 }
Marvin Raminabd9b892023-11-17 16:36:27 +01003913 if (audio_flags::audio_mix_ownership()) {
3914 res = endResult;
3915 if (res == NO_ERROR && checkOutputs) {
3916 checkForDeviceAndOutputChanges();
3917 updateCallAndOutputRouting();
3918 }
3919 } else {
3920 if (res == NO_ERROR && checkOutputs) {
3921 checkForDeviceAndOutputChanges();
3922 updateCallAndOutputRouting();
3923 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003924 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003925 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003926}
3927
Marvin Raminbdefaf02023-11-01 09:10:32 +01003928status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
3929 if (!audio_flags::audio_mix_test_api()) {
3930 return INVALID_OPERATION;
3931 }
3932
3933 _aidl_return.clear();
3934 _aidl_return.reserve(mPolicyMixes.size());
3935 for (const auto &policyMix: mPolicyMixes) {
3936 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
3937 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
3938 policyMix->mCbFlags);
3939 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01003940 _aidl_return.back().mToken = policyMix->mToken;
Marvin Raminbdefaf02023-11-01 09:10:32 +01003941 }
3942
3943 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return->size());
3944 return OK;
3945}
3946
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003947status_t AudioPolicyManager::updatePolicyMix(
3948 const AudioMix& mix,
3949 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3950 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3951 if (res == NO_ERROR) {
3952 checkForDeviceAndOutputChanges();
3953 updateCallAndOutputRouting();
3954 }
3955 return res;
3956}
3957
Mikhail Naganov100f0122018-11-29 11:22:16 -08003958void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3959{
3960 size_t i = 0;
3961 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3962 for (const auto& fmt : mManualSurroundFormats) {
3963 if (i++ != 0) dst->append(", ");
3964 std::string sfmt;
3965 FormatConverter::toString(fmt, sfmt);
3966 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3967 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3968 }
3969}
3970
Eric Laurentc529cf62020-04-17 18:19:10 -07003971// Returns true if all devices types match the predicate and are supported by one HW module
3972bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003973 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003974 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003975 const char *context,
3976 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003977 for (size_t i = 0; i < devices.size(); i++) {
3978 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003979 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003980 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003981 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003982 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003983 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003984 return false;
3985 }
3986 }
3987 return true;
3988}
3989
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003990void AudioPolicyManager::changeOutputDevicesMuteState(
3991 const AudioDeviceTypeAddrVector& devices) {
3992 ALOGVV("%s() num devices %zu", __func__, devices.size());
3993
3994 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3995 getSoftwareOutputsForDevices(devices);
3996
3997 for (size_t i = 0; i < outputs.size(); i++) {
3998 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3999 DeviceVector prevDevices = outputDesc->devices();
4000 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4001 }
4002}
4003
4004std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4005 const AudioDeviceTypeAddrVector& devices) const
4006{
4007 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4008 DeviceVector deviceDescriptors;
4009 for (size_t j = 0; j < devices.size(); j++) {
4010 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4011 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4012 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4013 ALOGE("%s: device type %#x address %s not supported or not an output device",
4014 __func__, devices[j].mType, devices[j].getAddress());
4015 continue;
4016 }
4017 deviceDescriptors.add(desc);
4018 }
4019 for (size_t i = 0; i < mOutputs.size(); i++) {
4020 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4021 continue;
4022 }
4023 outputs.push_back(mOutputs.valueAt(i));
4024 }
4025 return outputs;
4026}
4027
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004028status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004029 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004030 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004031 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4032 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004033 }
4034 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004035 if (res != NO_ERROR) {
4036 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4037 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004038 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004039
4040 checkForDeviceAndOutputChanges();
4041 updateCallAndOutputRouting();
4042
4043 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004044}
4045
4046status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4047 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004048 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4049 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004050 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004051 __FUNCTION__, uid);
4052 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004053 }
4054
Eric Laurentc529cf62020-04-17 18:19:10 -07004055 checkForDeviceAndOutputChanges();
4056 updateCallAndOutputRouting();
4057
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004058 return res;
4059}
4060
Eric Laurent2517af32020-11-25 15:31:27 +01004061
jiabin0a488932020-08-07 17:32:40 -07004062status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4063 device_role_t role,
4064 const AudioDeviceTypeAddrVector &devices) {
4065 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4066 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004067
Eric Laurentc529cf62020-04-17 18:19:10 -07004068 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004069 return BAD_VALUE;
4070 }
jiabin0a488932020-08-07 17:32:40 -07004071 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004072 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004073 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4074 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004075 return status;
4076 }
4077
4078 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004079
4080 bool forceVolumeReeval = false;
4081 // FIXME: workaround for truncated touch sounds
4082 // to be removed when the problem is handled by system UI
4083 uint32_t delayMs = 0;
4084 if (strategy == mCommunnicationStrategy) {
4085 forceVolumeReeval = true;
4086 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4087 updateInputRouting();
4088 }
4089 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004090
4091 return NO_ERROR;
4092}
4093
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004094void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4095 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004096{
4097 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004098 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004099 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004100 // Only apply special touch sound delay once
4101 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004102 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004103 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004104 for (size_t i = 0; i < mOutputs.size(); i++) {
4105 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4106 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004107 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4108 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004109 // As done in setDeviceConnectionState, we could also fix default device issue by
4110 // preventing the force re-routing in case of default dev that distinguishes on address.
4111 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004112 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004113 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4114 // If the device is using preferred mixer attributes, the output need to reopen
4115 // with default configuration when the new selected devices are different from
4116 // current routing devices.
4117 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4118 continue;
4119 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304120
4121 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4122 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004123 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004124 // Only apply special touch sound delay once
4125 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004126 }
4127 if (forceVolumeReeval && !newDevices.isEmpty()) {
4128 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4129 }
4130 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004131 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004132 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004133}
4134
Eric Laurent2517af32020-11-25 15:31:27 +01004135void AudioPolicyManager::updateInputRouting() {
4136 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304137 // Skip for hotword recording as the input device switch
4138 // is handled within sound trigger HAL
4139 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4140 continue;
4141 }
Eric Laurent2517af32020-11-25 15:31:27 +01004142 auto newDevice = getNewInputDevice(activeDesc);
4143 // Force new input selection if the new device can not be reached via current input
4144 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4145 setInputDevice(activeDesc->mIoHandle, newDevice);
4146 } else {
4147 closeInput(activeDesc->mIoHandle);
4148 }
4149 }
4150}
4151
Paul Wang5d7cdb52022-11-22 09:45:06 +00004152status_t
4153AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4154 device_role_t role,
4155 const AudioDeviceTypeAddrVector &devices) {
4156 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4157 dumpAudioDeviceTypeAddrVector(devices).c_str());
4158
Eric Laurent78fedbf2023-03-09 14:40:44 +01004159 if (!areAllDevicesSupported(
4160 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004161 return BAD_VALUE;
4162 }
4163 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4164 if (status != NO_ERROR) {
4165 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4166 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4167 return status;
4168 }
4169
4170 checkForDeviceAndOutputChanges();
4171
4172 bool forceVolumeReeval = false;
4173 // TODO(b/263479999): workaround for truncated touch sounds
4174 // to be removed when the problem is handled by system UI
4175 uint32_t delayMs = 0;
4176 if (strategy == mCommunnicationStrategy) {
4177 forceVolumeReeval = true;
4178 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4179 updateInputRouting();
4180 }
4181 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4182
4183 return NO_ERROR;
4184}
4185
4186status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4187 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004188{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004189 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004190
Paul Wang5d7cdb52022-11-22 09:45:06 +00004191 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004192 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004193 ALOGW_IF(status != NAME_NOT_FOUND,
4194 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004195 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004196 return status;
4197 }
4198
4199 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004200
4201 bool forceVolumeReeval = false;
4202 // FIXME: workaround for truncated touch sounds
4203 // to be removed when the problem is handled by system UI
4204 uint32_t delayMs = 0;
4205 if (strategy == mCommunnicationStrategy) {
4206 forceVolumeReeval = true;
4207 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4208 updateInputRouting();
4209 }
4210 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004211
4212 return NO_ERROR;
4213}
4214
jiabin0a488932020-08-07 17:32:40 -07004215status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4216 device_role_t role,
4217 AudioDeviceTypeAddrVector &devices) {
4218 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004219}
4220
Jiabin Huang3b98d322020-09-03 17:54:16 +00004221status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4222 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4223 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4224 dumpAudioDeviceTypeAddrVector(devices).c_str());
4225
Mikhail Naganov55773032020-10-01 15:08:13 -07004226 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004227 return BAD_VALUE;
4228 }
4229 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4230 ALOGW_IF(status != NO_ERROR,
4231 "Engine could not set preferred devices %s for audio source %d role %d",
4232 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4233
4234 return status;
4235}
4236
4237status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4238 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4239 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4240 dumpAudioDeviceTypeAddrVector(devices).c_str());
4241
Mikhail Naganov55773032020-10-01 15:08:13 -07004242 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004243 return BAD_VALUE;
4244 }
4245 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4246 ALOGW_IF(status != NO_ERROR,
4247 "Engine could not add preferred devices %s for audio source %d role %d",
4248 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4249
Eric Laurent2517af32020-11-25 15:31:27 +01004250 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004251 return status;
4252}
4253
4254status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4255 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4256{
4257 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4258 dumpAudioDeviceTypeAddrVector(devices).c_str());
4259
Eric Laurent78fedbf2023-03-09 14:40:44 +01004260 if (!areAllDevicesSupported(
4261 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004262 return BAD_VALUE;
4263 }
4264
4265 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4266 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004267 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004268 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004269 if (status == NO_ERROR) {
4270 updateInputRouting();
4271 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004272 return status;
4273}
4274
4275status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4276 device_role_t role) {
4277 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4278
4279 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004280 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004281 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004282 if (status == NO_ERROR) {
4283 updateInputRouting();
4284 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004285 return status;
4286}
4287
4288status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4289 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4290 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4291}
4292
Oscar Azucena90e77632019-11-27 17:12:28 -08004293status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004294 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004295 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004296 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4297 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004298 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004299 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4300 if (status != NO_ERROR) {
4301 ALOGE("%s() could not set device affinity for userId %d",
4302 __FUNCTION__, userId);
4303 return status;
4304 }
4305
4306 // reevaluate outputs for all devices
4307 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004308 changeOutputDevicesMuteState(devices);
4309 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4310 true /* skipDelays */);
4311 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004312
4313 return NO_ERROR;
4314}
4315
4316status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004317 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004318 AudioDeviceTypeAddrVector devices;
4319 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004320 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4321 if (status != NO_ERROR) {
4322 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4323 __FUNCTION__, userId);
4324 return status;
4325 }
4326
4327 // reevaluate outputs for all devices
4328 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004329 changeOutputDevicesMuteState(devices);
4330 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4331 true /* skipDelays */);
4332 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004333
4334 return NO_ERROR;
4335}
4336
Andy Hungc29d82b2018-10-05 12:23:17 -07004337void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004338{
Andy Hungc29d82b2018-10-05 12:23:17 -07004339 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004340 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004341 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004342 std::string stateLiteral;
4343 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004344 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004345 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4346 "communications", "media", "record", "dock", "system",
4347 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4348 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4349 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004350 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4351 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4352 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4353 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4354 dst->append(" (MANUAL: ");
4355 dumpManualSurroundFormats(dst);
4356 dst->append(")");
4357 }
4358 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004359 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004360 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4361 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004362 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004363 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004364
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004365 dst->append("\n");
4366 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4367 dst->append("\n");
4368 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004369 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004370 mOutputs.dump(dst);
4371 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004372 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004373 mAudioPatches.dump(dst);
4374 mPolicyMixes.dump(dst);
4375 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004376
Kevin Rocardb99cc752019-03-21 20:52:24 -07004377 dst->appendFormat(" AllowedCapturePolicies:\n");
4378 for (auto& policy : mAllowedCapturePolicies) {
4379 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4380 }
4381
jiabina84c3d32022-12-02 18:59:55 +00004382 dst->appendFormat(" Preferred mixer audio configuration:\n");
4383 for (const auto it : mPreferredMixerAttrInfos) {
4384 dst->appendFormat(" - device port id: %d\n", it.first);
4385 for (const auto preferredMixerInfoIt : it.second) {
4386 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4387 preferredMixerInfoIt.second->dump(dst);
4388 }
4389 }
4390
François Gaffiec005e562018-11-06 15:04:49 +01004391 dst->appendFormat("\nPolicy Engine dump:\n");
4392 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004393}
4394
4395status_t AudioPolicyManager::dump(int fd)
4396{
4397 String8 result;
4398 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004399 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004400 return NO_ERROR;
4401}
4402
Kevin Rocardb99cc752019-03-21 20:52:24 -07004403status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4404{
4405 mAllowedCapturePolicies[uid] = capturePolicy;
4406 return NO_ERROR;
4407}
4408
Eric Laurente552edb2014-03-10 17:42:56 -07004409// This function checks for the parameters which can be offloaded.
4410// This can be enhanced depending on the capability of the DSP and policy
4411// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004412audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004413{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004414 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004415 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004416 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004417 offloadInfo.format,
4418 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4419 offloadInfo.has_video);
4420
jiabin2b9d5a12021-12-10 01:06:29 +00004421 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004422 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004423 }
4424
4425 // See if there is a profile to support this.
4426 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004427 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004428 offloadInfo.sample_rate,
4429 offloadInfo.format,
4430 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004431 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4432 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004433 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4434 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4435 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004436 if (profile == nullptr) {
4437 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4438 }
4439 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4440 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4441 }
4442 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004443}
4444
Michael Chana94fbb22018-04-24 14:31:19 +10004445bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4446 const audio_attributes_t& attributes) {
4447 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004448 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004449 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4450 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004451 config.sample_rate,
4452 config.format,
4453 config.channel_mask,
4454 output_flags,
4455 true /* directOnly */);
4456 ALOGV("%s() profile %sfound with name: %s, "
4457 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4458 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004459 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004460 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004461
4462 // also try the MSD module if compatible profile not found
4463 if (profile == nullptr) {
4464 profile = getMsdProfileForOutput(outputDevices,
4465 config.sample_rate,
4466 config.format,
4467 config.channel_mask,
4468 output_flags,
4469 true /* directOnly */);
4470 ALOGV("%s() MSD profile %sfound with name: %s, "
4471 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4472 __FUNCTION__, profile != 0 ? "" : "NOT ",
4473 (profile != 0 ? profile->getTagName().c_str() : "null"),
4474 config.sample_rate, config.format, config.channel_mask, output_flags);
4475 }
4476 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004477}
4478
jiabin2b9d5a12021-12-10 01:06:29 +00004479bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4480 bool durationIgnored) {
4481 if (mMasterMono) {
4482 return false; // no offloading if mono is set.
4483 }
4484
4485 // Check if offload has been disabled
4486 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4487 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4488 return false;
4489 }
4490
4491 // Check if stream type is music, then only allow offload as of now.
4492 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4493 {
4494 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4495 return false;
4496 }
4497
4498 //TODO: enable audio offloading with video when ready
4499 const bool allowOffloadWithVideo =
4500 property_get_bool("audio.offload.video", false /* default_value */);
4501 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4502 ALOGV("%s: has_video == true, returning false", __func__);
4503 return false;
4504 }
4505
4506 //If duration is less than minimum value defined in property, return false
4507 const int min_duration_secs = property_get_int32(
4508 "audio.offload.min.duration.secs", -1 /* default_value */);
4509 if (!durationIgnored) {
4510 if (min_duration_secs >= 0) {
4511 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4512 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4513 __func__, min_duration_secs);
4514 return false;
4515 }
4516 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4517 ALOGV("%s: Offload denied by duration < default min(=%u)",
4518 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4519 return false;
4520 }
4521 }
4522
4523 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4524 // creating an offloaded track and tearing it down immediately after start when audioflinger
4525 // detects there is an active non offloadable effect.
4526 // FIXME: We should check the audio session here but we do not have it in this context.
4527 // This may prevent offloading in rare situations where effects are left active by apps
4528 // in the background.
4529 if (mEffects.isNonOffloadableEffectEnabled()) {
4530 return false;
4531 }
4532
4533 return true;
4534}
4535
4536audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4537 const audio_config_t *config) {
4538 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4539 offloadInfo.format = config->format;
4540 offloadInfo.sample_rate = config->sample_rate;
4541 offloadInfo.channel_mask = config->channel_mask;
4542 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4543 offloadInfo.has_video = false;
4544 offloadInfo.is_streaming = false;
4545 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4546
4547 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4548 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4549 audio_flags_to_audio_output_flags(attr->flags, &flags);
4550 // only retain flags that will drive compressed offload or passthrough
4551 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4552 if (offloadPossible) {
4553 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4554 }
4555 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4556
Dorin Drimusfae3c642022-03-17 18:36:30 +01004557 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004558 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004559 DeviceVector outputDevices = engineOutputDevices;
4560 // the MSD module checks for different conditions and output devices
4561 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4562 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4563 continue;
4564 }
4565 outputDevices = getMsdAudioOutDevices();
4566 }
jiabin2b9d5a12021-12-10 01:06:29 +00004567 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004568 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004569 config->sample_rate, nullptr /*updatedSamplingRate*/,
4570 config->format, nullptr /*updatedFormat*/,
4571 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004572 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004573 continue;
4574 }
4575 // reject profiles not corresponding to a device currently available
4576 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4577 continue;
4578 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004579 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4580 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004581 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004582 != AUDIO_DIRECT_NOT_SUPPORTED) {
4583 // Already reports offload gapless supported. No need to report offload support.
4584 continue;
4585 }
4586 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4587 != AUDIO_OUTPUT_FLAG_NONE) {
4588 // If offload gapless is reported, no need to report offload support.
4589 directMode = (audio_direct_mode_t) ((directMode &
4590 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4591 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4592 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004593 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004594 }
4595 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004596 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004597 }
4598 }
4599 }
4600 return directMode;
4601}
4602
Dorin Drimusf2196d82022-01-03 12:11:18 +01004603status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4604 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004605 if (mEffects.isNonOffloadableEffectEnabled()) {
4606 return OK;
4607 }
jiabinf1c73972022-04-14 16:28:52 -07004608 DeviceVector devices;
4609 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004610 if (status != OK) {
4611 return status;
4612 }
4613 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4614 if (devices.empty()) {
4615 return OK; // no output devices for the attributes
4616 }
jiabinf1c73972022-04-14 16:28:52 -07004617 return getProfilesForDevices(devices, audioProfilesVector,
4618 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004619}
4620
jiabina84c3d32022-12-02 18:59:55 +00004621status_t AudioPolicyManager::getSupportedMixerAttributes(
4622 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4623 ALOGV("%s, portId=%d", __func__, portId);
4624 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4625 if (deviceDescriptor == nullptr) {
4626 ALOGE("%s the requested device is currently unavailable", __func__);
4627 return BAD_VALUE;
4628 }
jiabin96daffc2023-05-11 17:51:55 +00004629 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4630 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4631 deviceDescriptor->type());
4632 return BAD_VALUE;
4633 }
jiabina84c3d32022-12-02 18:59:55 +00004634 for (const auto& hwModule : mHwModules) {
4635 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4636 if (curProfile->supportsDevice(deviceDescriptor)) {
4637 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4638 }
4639 }
4640 }
4641 return NO_ERROR;
4642}
4643
4644status_t AudioPolicyManager::setPreferredMixerAttributes(
4645 const audio_attributes_t *attr,
4646 audio_port_handle_t portId,
4647 uid_t uid,
4648 const audio_mixer_attributes_t *mixerAttributes) {
4649 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4650 "mixerBehavior=%d}, uid=%d, portId=%u",
4651 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4652 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4653 mixerAttributes->mixer_behavior, uid, portId);
4654 if (attr->usage != AUDIO_USAGE_MEDIA) {
4655 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4656 return BAD_VALUE;
4657 }
4658 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4659 if (deviceDescriptor == nullptr) {
4660 ALOGE("%s the requested device is currently unavailable", __func__);
4661 return BAD_VALUE;
4662 }
4663 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4664 ALOGE("%s(%d), type=%d, is not a usb output device",
4665 __func__, portId, deviceDescriptor->type());
4666 return BAD_VALUE;
4667 }
4668
4669 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4670 audio_flags_to_audio_output_flags(attr->flags, &flags);
4671 flags = (audio_output_flags_t) (flags |
4672 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4673 sp<IOProfile> profile = nullptr;
4674 DeviceVector devices(deviceDescriptor);
4675 for (const auto& hwModule : mHwModules) {
4676 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4677 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004678 && curProfile->getCompatibilityScore(
4679 devices,
4680 mixerAttributes->config.sample_rate,
4681 nullptr /*updatedSamplingRate*/,
4682 mixerAttributes->config.format,
4683 nullptr /*updatedFormat*/,
4684 mixerAttributes->config.channel_mask,
4685 nullptr /*updatedChannelMask*/,
4686 flags,
4687 false /*exactMatchRequiredForInputFlags*/)
4688 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004689 profile = curProfile;
4690 break;
4691 }
4692 }
4693 }
4694 if (profile == nullptr) {
4695 ALOGE("%s, there is no compatible profile found", __func__);
4696 return BAD_VALUE;
4697 }
4698
4699 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4700 sp<PreferredMixerAttributesInfo>::make(
4701 uid, portId, profile, flags, *mixerAttributes);
4702 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4703 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4704
4705 // If 1) there is any client from the preferred mixer configuration owner that is currently
4706 // active and matches the strategy and 2) current output is on the preferred device and the
4707 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4708 // configuration.
4709 std::vector<audio_io_handle_t> outputsToReopen;
4710 for (size_t i = 0; i < mOutputs.size(); i++) {
4711 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004712 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4713 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4714 output->mUsePreferredMixerAttributes = true;
4715 } else {
4716 for (const auto &client: output->getActiveClients()) {
4717 if (client->uid() == uid && client->strategy() == strategy) {
4718 client->setIsInvalid();
4719 outputsToReopen.push_back(output->mIoHandle);
4720 }
jiabina84c3d32022-12-02 18:59:55 +00004721 }
4722 }
4723 }
4724 }
4725 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4726 config.sample_rate = mixerAttributes->config.sample_rate;
4727 config.channel_mask = mixerAttributes->config.channel_mask;
4728 config.format = mixerAttributes->config.format;
4729 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004730 sp<SwAudioOutputDescriptor> desc =
4731 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4732 if (desc == nullptr) {
4733 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4734 continue;
4735 }
4736 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004737 }
4738
4739 return NO_ERROR;
4740}
4741
4742sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004743 audio_port_handle_t devicePortId,
4744 product_strategy_t strategy,
4745 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004746 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4747 if (it == mPreferredMixerAttrInfos.end()) {
4748 return nullptr;
4749 }
jiabind9a58d32023-06-01 17:57:30 +00004750 if (activeBitPerfectPreferred) {
4751 for (auto [strategy, info] : it->second) {
4752 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4753 && info->getActiveClientCount() != 0) {
4754 return info;
4755 }
4756 }
jiabina84c3d32022-12-02 18:59:55 +00004757 }
jiabind9a58d32023-06-01 17:57:30 +00004758 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4759 return strategyMatchedMixerAttrInfoIt == it->second.end()
4760 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004761}
4762
4763status_t AudioPolicyManager::getPreferredMixerAttributes(
4764 const audio_attributes_t *attr,
4765 audio_port_handle_t portId,
4766 audio_mixer_attributes_t* mixerAttributes) {
4767 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4768 portId, mEngine->getProductStrategyForAttributes(*attr));
4769 if (info == nullptr) {
4770 return NAME_NOT_FOUND;
4771 }
4772 *mixerAttributes = info->getMixerAttributes();
4773 return NO_ERROR;
4774}
4775
4776status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4777 audio_port_handle_t portId,
4778 uid_t uid) {
4779 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4780 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4781 if (preferredMixerAttrInfo == nullptr) {
4782 return NAME_NOT_FOUND;
4783 }
4784 if (preferredMixerAttrInfo->getUid() != uid) {
4785 ALOGE("%s, requested uid=%d, owned uid=%d",
4786 __func__, uid, preferredMixerAttrInfo->getUid());
4787 return PERMISSION_DENIED;
4788 }
4789 mPreferredMixerAttrInfos[portId].erase(strategy);
4790 if (mPreferredMixerAttrInfos[portId].empty()) {
4791 mPreferredMixerAttrInfos.erase(portId);
4792 }
4793
4794 // Reconfig existing output
4795 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4796 for (size_t i = 0; i < mOutputs.size(); i++) {
4797 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4798 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4799 }
4800 }
4801 for (const auto output : potentialOutputsToReopen) {
4802 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4803 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4804 preferredMixerAttrInfo->getFlags())) {
4805 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4806 }
4807 }
4808 return NO_ERROR;
4809}
4810
Eric Laurent6a94d692014-05-20 11:18:06 -07004811status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4812 audio_port_type_t type,
4813 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004814 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 unsigned int *generation)
4816{
jiabin19cdba52020-11-24 11:28:58 -08004817 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4818 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004819 return BAD_VALUE;
4820 }
4821 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004822 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004823 *num_ports = 0;
4824 }
4825
4826 size_t portsWritten = 0;
4827 size_t portsMax = *num_ports;
4828 *num_ports = 0;
4829 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004830 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4831 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004833 for (const auto& dev : mAvailableOutputDevices) {
4834 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004835 continue;
4836 }
4837 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004838 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004839 }
4840 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004841 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004842 }
4843 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004844 for (const auto& dev : mAvailableInputDevices) {
4845 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004846 continue;
4847 }
4848 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004849 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004850 }
4851 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004852 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004853 }
4854 }
4855 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4856 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4857 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4858 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4859 }
4860 *num_ports += mInputs.size();
4861 }
4862 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004863 size_t numOutputs = 0;
4864 for (size_t i = 0; i < mOutputs.size(); i++) {
4865 if (!mOutputs[i]->isDuplicated()) {
4866 numOutputs++;
4867 if (portsWritten < portsMax) {
4868 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4869 }
4870 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004871 }
Eric Laurent84c70242014-06-23 08:46:27 -07004872 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004873 }
4874 }
jiabina84c3d32022-12-02 18:59:55 +00004875
Eric Laurent6a94d692014-05-20 11:18:06 -07004876 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004877 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 return NO_ERROR;
4879}
4880
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004881status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4882 std::vector<media::AudioPortFw>* _aidl_return) {
4883 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4884 audio_port_v7 port;
4885 dev->toAudioPort(&port);
4886 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4887 _aidl_return->push_back(std::move(aidlPort));
4888 return OK;
4889 };
4890
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004891 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004892 for (const auto& dev : module->getDeclaredDevices()) {
4893 if (role == media::AudioPortRole::NONE ||
4894 ((role == media::AudioPortRole::SOURCE)
4895 == audio_is_input_device(dev->type()))) {
4896 RETURN_STATUS_IF_ERROR(pushPort(dev));
4897 }
4898 }
4899 }
4900 return OK;
4901}
4902
jiabin19cdba52020-11-24 11:28:58 -08004903status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004904{
Eric Laurent99fcae42018-05-17 16:59:18 -07004905 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4906 return BAD_VALUE;
4907 }
4908 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4909 if (dev != 0) {
4910 dev->toAudioPort(port);
4911 return NO_ERROR;
4912 }
4913 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4914 if (dev != 0) {
4915 dev->toAudioPort(port);
4916 return NO_ERROR;
4917 }
4918 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4919 if (out != 0) {
4920 out->toAudioPort(port);
4921 return NO_ERROR;
4922 }
4923 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4924 if (in != 0) {
4925 in->toAudioPort(port);
4926 return NO_ERROR;
4927 }
4928 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004929}
4930
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004931status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4932 audio_patch_handle_t *handle,
4933 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004934{
François Gaffieafd4cea2019-11-18 15:50:22 +01004935 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 if (handle == NULL || patch == NULL) {
4937 return BAD_VALUE;
4938 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004939 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004940 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004941 return BAD_VALUE;
4942 }
4943 // only one source per audio patch supported for now
4944 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 return INVALID_OPERATION;
4946 }
Eric Laurent874c42872014-08-08 15:13:39 -07004947 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004948 return INVALID_OPERATION;
4949 }
Eric Laurent874c42872014-08-08 15:13:39 -07004950 for (size_t i = 0; i < patch->num_sinks; i++) {
4951 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4952 return INVALID_OPERATION;
4953 }
4954 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004955
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004956 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4957 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4958 if (srcDevice == nullptr || sinkDevice == nullptr) {
4959 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4960 return BAD_VALUE;
4961 }
4962 ALOGV("%s between source %s and sink %s", __func__,
4963 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4964 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4965 // Default attributes, default volume priority, not to infer with non raw audio patches.
4966 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4967 const struct audio_port_config *source = &patch->sources[0];
4968 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004969 new SourceClientDescriptor(
4970 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4971 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4972 true);
4973 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004974
4975 status_t status =
4976 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4977
4978 if (status != NO_ERROR) {
4979 return INVALID_OPERATION;
4980 }
4981 mAudioSources.add(portId, sourceDesc);
4982 return NO_ERROR;
4983}
4984
4985status_t AudioPolicyManager::connectAudioSourceToSink(
4986 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4987 const struct audio_patch *patch,
4988 audio_patch_handle_t &handle,
4989 uid_t uid, uint32_t delayMs)
4990{
4991 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4992 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4993 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4994 return INVALID_OPERATION;
4995 }
4996 sourceDesc->connect(handle, sinkDevice);
4997 if (isMsdPatch(handle)) {
4998 return NO_ERROR;
4999 }
5000 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5001 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5002 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5003 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5004 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5005 goto FailurePatchAdded;
5006 }
5007 status = swOutput->start();
5008 if (status != NO_ERROR) {
5009 goto FailureSourceAdded;
5010 }
5011 swOutput->addClient(sourceDesc);
5012 status = startSource(swOutput, sourceDesc, &delayMs);
5013 if (status != NO_ERROR) {
5014 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5015 goto FailureSourceActive;
5016 }
5017 if (delayMs != 0) {
5018 usleep(delayMs * 1000);
5019 }
5020 return NO_ERROR;
5021
5022FailureSourceActive:
5023 swOutput->stop();
5024 releaseOutput(sourceDesc->portId());
5025FailureSourceAdded:
5026 sourceDesc->setSwOutput(nullptr);
5027FailurePatchAdded:
5028 releaseAudioPatchInternal(handle);
5029 return INVALID_OPERATION;
5030}
5031
5032status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5033 audio_patch_handle_t *handle,
5034 uid_t uid, uint32_t delayMs,
5035 const sp<SourceClientDescriptor>& sourceDesc)
5036{
5037 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005038 sp<AudioPatch> patchDesc;
5039 ssize_t index = mAudioPatches.indexOfKey(*handle);
5040
François Gaffieafd4cea2019-11-18 15:50:22 +01005041 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5042 patch->sources[0].role,
5043 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005044#if LOG_NDEBUG == 0
5045 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005046 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5047 patch->sinks[i].role,
5048 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005049 }
5050#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005051
5052 if (index >= 0) {
5053 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005054 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5055 __func__, mUidCached, patchDesc->getUid(), uid);
5056 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005057 return INVALID_OPERATION;
5058 }
5059 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005060 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005061 }
5062
5063 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005064 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005066 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005067 return BAD_VALUE;
5068 }
Eric Laurent84c70242014-06-23 08:46:27 -07005069 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5070 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005071 if (patchDesc != 0) {
5072 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005073 ALOGV("%s source id differs for patch current id %d new id %d",
5074 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 return BAD_VALUE;
5076 }
5077 }
Eric Laurent874c42872014-08-08 15:13:39 -07005078 DeviceVector devices;
5079 for (size_t i = 0; i < patch->num_sinks; i++) {
5080 // Only support mix to devices connection
5081 // TODO add support for mix to mix connection
5082 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005083 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005084 return INVALID_OPERATION;
5085 }
5086 sp<DeviceDescriptor> devDesc =
5087 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5088 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005089 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005090 return BAD_VALUE;
5091 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005092
jiabin66acc432024-02-06 00:57:36 +00005093 if (outputDesc->mProfile->getCompatibilityScore(
5094 DeviceVector(devDesc),
5095 patch->sources[0].sample_rate,
5096 nullptr, // updatedSamplingRate
5097 patch->sources[0].format,
5098 nullptr, // updatedFormat
5099 patch->sources[0].channel_mask,
5100 nullptr, // updatedChannelMask
5101 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005102 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005103 return INVALID_OPERATION;
5104 }
5105 devices.add(devDesc);
5106 }
5107 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005108 return INVALID_OPERATION;
5109 }
Eric Laurent874c42872014-08-08 15:13:39 -07005110
Eric Laurent6a94d692014-05-20 11:18:06 -07005111 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005112 ALOGV("%s setting device %s on output %d",
5113 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305114 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005115 index = mAudioPatches.indexOfKey(*handle);
5116 if (index >= 0) {
5117 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005118 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 }
5120 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005121 patchDesc->setUid(uid);
5122 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005123 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005124 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005125 return INVALID_OPERATION;
5126 }
5127 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5128 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5129 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005130 // only one sink supported when connecting an input device to a mix
5131 if (patch->num_sinks > 1) {
5132 return INVALID_OPERATION;
5133 }
François Gaffie53615e22015-03-19 09:24:12 +01005134 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005135 if (inputDesc == NULL) {
5136 return BAD_VALUE;
5137 }
5138 if (patchDesc != 0) {
5139 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5140 return BAD_VALUE;
5141 }
5142 }
François Gaffie11d30102018-11-02 16:09:09 +01005143 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005144 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005145 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005146 return BAD_VALUE;
5147 }
5148
jiabin66acc432024-02-06 00:57:36 +00005149 if (inputDesc->mProfile->getCompatibilityScore(
5150 DeviceVector(device),
5151 patch->sinks[0].sample_rate,
5152 nullptr, /*updatedSampleRate*/
5153 patch->sinks[0].format,
5154 nullptr, /*updatedFormat*/
5155 patch->sinks[0].channel_mask,
5156 nullptr, /*updatedChannelMask*/
5157 // FIXME for the parameter type,
5158 // and the NONE
5159 (audio_output_flags_t)
5160 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005161 return INVALID_OPERATION;
5162 }
5163 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005164 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005165 device->toString().c_str(), inputDesc->mIoHandle);
5166 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005167 index = mAudioPatches.indexOfKey(*handle);
5168 if (index >= 0) {
5169 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005170 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005171 }
5172 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005173 patchDesc->setUid(uid);
5174 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005175 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005176 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005177 return INVALID_OPERATION;
5178 }
5179 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5180 // device to device connection
5181 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005182 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005183 return BAD_VALUE;
5184 }
5185 }
François Gaffie11d30102018-11-02 16:09:09 +01005186 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005187 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005188 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005189 return BAD_VALUE;
5190 }
Eric Laurent874c42872014-08-08 15:13:39 -07005191
Eric Laurent6a94d692014-05-20 11:18:06 -07005192 //update source and sink with our own data as the data passed in the patch may
5193 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005194 PatchBuilder patchBuilder;
5195 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005196
5197 // if first sink is to MSD, establish single MSD patch
5198 if (getMsdAudioOutDevices().contains(
5199 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5200 ALOGV("%s patching to MSD", __FUNCTION__);
5201 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5202 goto installPatch;
5203 }
5204
François Gaffieafd4cea2019-11-18 15:50:22 +01005205 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5206 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005207
Eric Laurent874c42872014-08-08 15:13:39 -07005208 for (size_t i = 0; i < patch->num_sinks; i++) {
5209 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005210 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005211 return INVALID_OPERATION;
5212 }
François Gaffie11d30102018-11-02 16:09:09 +01005213 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005214 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005215 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005216 return BAD_VALUE;
5217 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005218 audio_port_config sinkPortConfig = {};
5219 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5220 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005221
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005222 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5223 // volume management purpose (tracking activity)
5224 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5225 // in config XML to reach the sink so that is can be declared as available.
5226 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005227 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005228 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005229 // take care of dynamic routing for SwOutput selection,
5230 audio_attributes_t attributes = sourceDesc->attributes();
5231 audio_stream_type_t stream = sourceDesc->stream();
5232 audio_attributes_t resultAttr;
5233 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5234 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005235 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5236 config.channel_mask =
5237 (audio_channel_mask_get_representation(sourceMask)
5238 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5239 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005240 config.format = sourceDesc->config().format;
5241 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5242 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5243 bool isRequestedDeviceForExclusiveUse = false;
5244 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005245 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005246 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005247 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5248 &stream, sourceDesc->uid(), &config, &flags,
5249 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005250 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005251 if (output == AUDIO_IO_HANDLE_NONE) {
5252 ALOGV("%s no output for device %s",
5253 __FUNCTION__, sinkDevice->toString().c_str());
5254 return INVALID_OPERATION;
5255 }
5256 outputDesc = mOutputs.valueFor(output);
5257 if (outputDesc->isDuplicated()) {
5258 ALOGE("%s output is duplicated", __func__);
5259 return INVALID_OPERATION;
5260 }
François Gaffie7e39df22022-04-26 12:48:49 +02005261 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5262 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005263 } else {
5264 // Same for "raw patches" aka created from createAudioPatch API
5265 SortedVector<audio_io_handle_t> outputs =
5266 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5267 // if the sink device is reachable via an opened output stream, request to
5268 // go via this output stream by adding a second source to the patch
5269 // description
5270 output = selectOutput(outputs);
5271 if (output == AUDIO_IO_HANDLE_NONE) {
5272 ALOGE("%s no output available for internal patch sink", __func__);
5273 return INVALID_OPERATION;
5274 }
5275 outputDesc = mOutputs.valueFor(output);
5276 if (outputDesc->isDuplicated()) {
5277 ALOGV("%s output for device %s is duplicated",
5278 __func__, sinkDevice->toString().c_str());
5279 return INVALID_OPERATION;
5280 }
François Gaffie7e39df22022-04-26 12:48:49 +02005281 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005282 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005283 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005284 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005285 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005286 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005287 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5288 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005289 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5290 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005291 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005292 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005293 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005294 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005295 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005296 return INVALID_OPERATION;
5297 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005298 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005299 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005300 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005301 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005302 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005303 srcMixPortConfig.ext.mix.usecase.stream =
5304 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005305 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5306 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005307 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005308 }
Eric Laurent83b88082014-06-20 18:31:16 -07005309 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005310 }
5311 // TODO: check from routing capabilities in config file and other conflicting patches
5312
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005313installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005314 status_t status = installPatch(
5315 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005316 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005317 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 return INVALID_OPERATION;
5319 }
5320 } else {
5321 return BAD_VALUE;
5322 }
5323 } else {
5324 return BAD_VALUE;
5325 }
5326 return NO_ERROR;
5327}
5328
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005329status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005330{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005331 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005332 ssize_t index = mAudioPatches.indexOfKey(handle);
5333
5334 if (index < 0) {
5335 return BAD_VALUE;
5336 }
5337 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005338 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5339 __func__, mUidCached, patchDesc->getUid(), uid);
5340 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005341 return INVALID_OPERATION;
5342 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005343 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5344 for (size_t i = 0; i < mAudioSources.size(); i++) {
5345 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5346 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5347 portId = sourceDesc->portId();
5348 break;
5349 }
5350 }
5351 return portId != AUDIO_PORT_HANDLE_NONE ?
5352 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005353}
Eric Laurent6a94d692014-05-20 11:18:06 -07005354
François Gaffieafd4cea2019-11-18 15:50:22 +01005355status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005356 uint32_t delayMs,
5357 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005358{
5359 ALOGV("%s patch %d", __func__, handle);
5360 if (mAudioPatches.indexOfKey(handle) < 0) {
5361 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5362 return BAD_VALUE;
5363 }
5364 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005365 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005366 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005367 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005368 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005369 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005370 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005371 return BAD_VALUE;
5372 }
5373
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305374 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005375 getNewOutputDevices(outputDesc, true /*fromCache*/),
5376 true,
5377 0,
5378 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005379 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5380 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005381 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005382 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005383 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005384 return BAD_VALUE;
5385 }
5386 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005387 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005388 true,
5389 NULL);
5390 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005391 status_t status =
5392 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5393 ALOGV("%s patch panel returned %d patchHandle %d",
5394 __func__, status, patchDesc->getAfHandle());
5395 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005396 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005397 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005398 // SW or HW Bridge
5399 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5400 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005401 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005402 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5403 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5404 outputDesc = sourceDesc->swOutput().promote();
5405 }
5406 if (outputDesc == nullptr) {
5407 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5408 // releaseOutput has already called closeOutput in case of direct output
5409 return NO_ERROR;
5410 }
François Gaffie7e39df22022-04-26 12:48:49 +02005411 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005412 // While using a HwBridge, force reconsidering device only if not reusing an existing
5413 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005414 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005415 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5416 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5417 // Reconsider device only for cases:
5418 // 1 / Active Output
5419 // 2 / Inactive Output previously hosting HwBridge
5420 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5421 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5422 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305423 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005424 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5425 outputDesc->devices(),
5426 force,
5427 0,
5428 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005429 } else {
5430 return BAD_VALUE;
5431 }
5432 } else {
5433 return BAD_VALUE;
5434 }
5435 return NO_ERROR;
5436}
5437
5438status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5439 struct audio_patch *patches,
5440 unsigned int *generation)
5441{
François Gaffie53615e22015-03-19 09:24:12 +01005442 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005443 return BAD_VALUE;
5444 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005445 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005446 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005447}
5448
Eric Laurente1715a42014-05-20 11:30:42 -07005449status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005450{
Eric Laurente1715a42014-05-20 11:30:42 -07005451 ALOGV("setAudioPortConfig()");
5452
5453 if (config == NULL) {
5454 return BAD_VALUE;
5455 }
5456 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5457 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005458 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5459 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005460 }
5461
Eric Laurenta121f902014-06-03 13:32:54 -07005462 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005463 if (config->type == AUDIO_PORT_TYPE_MIX) {
5464 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005465 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005466 if (outputDesc == NULL) {
5467 return BAD_VALUE;
5468 }
Eric Laurent84c70242014-06-23 08:46:27 -07005469 ALOG_ASSERT(!outputDesc->isDuplicated(),
5470 "setAudioPortConfig() called on duplicated output %d",
5471 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005472 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005473 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005474 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005475 if (inputDesc == NULL) {
5476 return BAD_VALUE;
5477 }
Eric Laurenta121f902014-06-03 13:32:54 -07005478 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005479 } else {
5480 return BAD_VALUE;
5481 }
5482 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5483 sp<DeviceDescriptor> deviceDesc;
5484 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5485 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5486 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5487 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5488 } else {
5489 return BAD_VALUE;
5490 }
5491 if (deviceDesc == NULL) {
5492 return BAD_VALUE;
5493 }
Eric Laurenta121f902014-06-03 13:32:54 -07005494 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005495 } else {
5496 return BAD_VALUE;
5497 }
5498
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005499 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005500 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5501 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005502 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005503 audioPortConfig->toAudioPortConfig(&newConfig, config);
5504 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005505 }
Eric Laurenta121f902014-06-03 13:32:54 -07005506 if (status != NO_ERROR) {
5507 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005508 }
Eric Laurente1715a42014-05-20 11:30:42 -07005509
5510 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005511}
5512
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005513void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5514{
Eric Laurentd60560a2015-04-10 11:31:20 -07005515 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005516 clearAudioPatches(uid);
5517 clearSessionRoutes(uid);
5518}
5519
Eric Laurent6a94d692014-05-20 11:18:06 -07005520void AudioPolicyManager::clearAudioPatches(uid_t uid)
5521{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005522 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005523 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005524 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005525 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005526 }
5527 }
5528}
5529
François Gaffiec005e562018-11-06 15:04:49 +01005530void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005531{
François Gaffiec005e562018-11-06 15:04:49 +01005532 // Take the first attributes following the product strategy as it is used to retrieve the routed
5533 // device. All attributes wihin a strategy follows the same "routing strategy"
5534 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5535 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005536 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005537 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005538 for (size_t j = 0; j < mOutputs.size(); j++) {
5539 if (mOutputs.keyAt(j) == ouptutToSkip) {
5540 continue;
5541 }
5542 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005543 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005544 continue;
5545 }
5546 // If the default device for this strategy is on another output mix,
5547 // invalidate all tracks in this strategy to force re connection.
5548 // Otherwise select new device on the output mix.
5549 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005550 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005551 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005552 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5553 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5554 // If the device is using preferred mixer attributes, the output need to reopen
5555 // with default configuration when the new selected devices are different from
5556 // current routing devices.
5557 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5558 continue;
5559 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305560 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005561 }
5562 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005563 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005564}
5565
5566void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5567{
5568 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005569 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005570 for (size_t i = 0; i < mOutputs.size(); i++) {
5571 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005572 for (const auto& client : outputDesc->getClientIterable()) {
5573 if (client->hasPreferredDevice() && client->uid() == uid) {
5574 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005575 auto clientStrategy = client->strategy();
5576 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5577 end(affectedStrategies)) {
5578 continue;
5579 }
5580 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005581 }
5582 }
5583 }
5584 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005585 for (const auto& strategy : affectedStrategies) {
5586 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005587 }
5588
5589 // remove input routes associated with this uid
5590 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005591 for (size_t i = 0; i < mInputs.size(); i++) {
5592 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005593 for (const auto& client : inputDesc->getClientIterable()) {
5594 if (client->hasPreferredDevice() && client->uid() == uid) {
5595 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5596 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005597 }
5598 }
5599 }
5600 // reroute inputs if necessary
5601 SortedVector<audio_io_handle_t> inputsToClose;
5602 for (size_t i = 0; i < mInputs.size(); i++) {
5603 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005604 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005605 inputsToClose.add(inputDesc->mIoHandle);
5606 }
5607 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005608 for (const auto& input : inputsToClose) {
5609 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005610 }
5611}
5612
Eric Laurentd60560a2015-04-10 11:31:20 -07005613void AudioPolicyManager::clearAudioSources(uid_t uid)
5614{
5615 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005616 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5617 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005618 stopAudioSource(mAudioSources.keyAt(i));
5619 }
5620 }
5621}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005622
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005623status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5624 audio_io_handle_t *ioHandle,
5625 audio_devices_t *device)
5626{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005627 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5628 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005629 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005630 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5631 if (deviceDesc == nullptr) {
5632 return INVALID_OPERATION;
5633 }
5634 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005635
François Gaffiedf372692015-03-19 10:43:27 +01005636 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005637}
5638
Eric Laurentd60560a2015-04-10 11:31:20 -07005639status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005640 const audio_attributes_t *attributes,
5641 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005642 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005643{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005644 ALOGV("%s", __FUNCTION__);
5645 *portId = AUDIO_PORT_HANDLE_NONE;
5646
5647 if (source == NULL || attributes == NULL || portId == NULL) {
5648 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5649 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005650 return BAD_VALUE;
5651 }
5652
Eric Laurentd60560a2015-04-10 11:31:20 -07005653 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5654 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005655 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5656 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005657 return INVALID_OPERATION;
5658 }
5659
François Gaffie11d30102018-11-02 16:09:09 +01005660 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005661 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005662 String8(source->ext.device.address),
5663 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005664 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005665 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005666 return BAD_VALUE;
5667 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005668
jiabin4ef93452019-09-10 14:29:54 -07005669 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005670
François Gaffieaaac0fd2018-11-22 17:56:39 +01005671 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005672 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005673 mEngine->getStreamTypeForAttributes(*attributes),
5674 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005675 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005676
5677 status_t status = connectAudioSource(sourceDesc);
5678 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005679 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005680 }
5681 return status;
5682}
5683
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005684status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005685{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005686 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005687
5688 // make sure we only have one patch per source.
5689 disconnectAudioSource(sourceDesc);
5690
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005691 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005692 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5693 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5694 sourceDesc->srcDevice()->type(),
5695 String8(sourceDesc->srcDevice()->address().c_str()),
5696 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005697 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005698 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005699 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005700 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005701 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5702 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5703 return INVALID_OPERATION;
5704 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005705 PatchBuilder patchBuilder;
5706 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5707 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005708
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005709 return connectAudioSourceToSink(
5710 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005711}
5712
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005713status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005714{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005715 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5716 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005717 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005718 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005719 return BAD_VALUE;
5720 }
5721 status_t status = disconnectAudioSource(sourceDesc);
5722
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005723 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005724 return status;
5725}
5726
Andy Hung2ddee192015-12-18 17:34:44 -08005727status_t AudioPolicyManager::setMasterMono(bool mono)
5728{
5729 if (mMasterMono == mono) {
5730 return NO_ERROR;
5731 }
5732 mMasterMono = mono;
5733 // if enabling mono we close all offloaded devices, which will invalidate the
5734 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5735 // for recreating the new AudioTrack as non-offloaded PCM.
5736 //
5737 // If disabling mono, we leave all tracks as is: we don't know which clients
5738 // and tracks are able to be recreated as offloaded. The next "song" should
5739 // play back offloaded.
5740 if (mMasterMono) {
5741 Vector<audio_io_handle_t> offloaded;
5742 for (size_t i = 0; i < mOutputs.size(); ++i) {
5743 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5744 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5745 offloaded.push(desc->mIoHandle);
5746 }
5747 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005748 for (const auto& handle : offloaded) {
5749 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005750 }
5751 }
5752 // update master mono for all remaining outputs
5753 for (size_t i = 0; i < mOutputs.size(); ++i) {
5754 updateMono(mOutputs.keyAt(i));
5755 }
5756 return NO_ERROR;
5757}
5758
5759status_t AudioPolicyManager::getMasterMono(bool *mono)
5760{
5761 *mono = mMasterMono;
5762 return NO_ERROR;
5763}
5764
Eric Laurentac9cef52017-06-09 15:46:26 -07005765float AudioPolicyManager::getStreamVolumeDB(
5766 audio_stream_type_t stream, int index, audio_devices_t device)
5767{
jiabin9a3361e2019-10-01 09:38:30 -07005768 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005769}
5770
jiabin81772902018-04-02 17:52:27 -07005771status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5772 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005773 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005774{
Kriti Dang6537def2021-03-02 13:46:59 +01005775 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5776 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005777 return BAD_VALUE;
5778 }
Kriti Dang6537def2021-03-02 13:46:59 +01005779 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5780 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005781
5782 size_t formatsWritten = 0;
5783 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005784
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005785 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005786 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5787 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005788 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005789 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005790 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005791 bool formatEnabled = true;
5792 switch (forceUse) {
5793 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005794 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005795 break;
5796 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5797 formatEnabled = false;
5798 break;
5799 default: // AUTO or ALWAYS => true
5800 break;
jiabin81772902018-04-02 17:52:27 -07005801 }
5802 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5803 }
jiabin81772902018-04-02 17:52:27 -07005804 }
5805 return NO_ERROR;
5806}
5807
Kriti Dang6537def2021-03-02 13:46:59 +01005808status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5809 audio_format_t *surroundFormats) {
5810 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5811 return BAD_VALUE;
5812 }
5813 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5814 __func__, *numSurroundFormats, surroundFormats);
5815
5816 size_t formatsWritten = 0;
5817 size_t formatsMax = *numSurroundFormats;
5818 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5819
5820 // Return formats from all device profiles that have already been resolved by
5821 // checkOutputsForDevice().
5822 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5823 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5824 audio_devices_t deviceType = device->type();
5825 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5826 // returns formats reported by HDMI devices.
5827 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5828 continue;
5829 }
5830 // Formats reported by sink devices
5831 std::unordered_set<audio_format_t> formatset;
5832 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5833 formatset.insert(it->second.begin(), it->second.end());
5834 }
5835
5836 // Formats hard-coded in the in policy configuration file (if any).
5837 FormatVector encodedFormats = device->encodedFormats();
5838 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5839 // Filter the formats which are supported by the vendor hardware.
5840 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005841 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005842 formats.insert(*it);
5843 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005844 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005845 if (pair.second.count(*it) != 0) {
5846 formats.insert(pair.first);
5847 break;
5848 }
5849 }
5850 }
5851 }
5852 }
5853 *numSurroundFormats = formats.size();
5854 for (const auto& format: formats) {
5855 if (formatsWritten < formatsMax) {
5856 surroundFormats[formatsWritten++] = format;
5857 }
5858 }
5859 return NO_ERROR;
5860}
5861
jiabin81772902018-04-02 17:52:27 -07005862status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5863{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005864 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005865 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5866 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005867 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005868 return BAD_VALUE;
5869 }
5870
Mikhail Naganov100f0122018-11-29 11:22:16 -08005871 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5872 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005873 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005874 return INVALID_OPERATION;
5875 }
5876
Mikhail Naganov100f0122018-11-29 11:22:16 -08005877 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005878 return NO_ERROR;
5879 }
5880
Mikhail Naganov100f0122018-11-29 11:22:16 -08005881 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005882 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005883 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005884 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005885 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005886 }
5887 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005888 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005889 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005890 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005891 }
5892 }
5893
5894 sp<SwAudioOutputDescriptor> outputDesc;
5895 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005896 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5897 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005898 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5899 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005900 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005901 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005902 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5903 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5904 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005905 name.c_str(),
5906 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005907 if (status != NO_ERROR) {
5908 continue;
5909 }
5910 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5911 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5912 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005913 name.c_str(),
5914 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005915 profileUpdated |= (status == NO_ERROR);
5916 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005917 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005918 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005919 AUDIO_DEVICE_IN_HDMI);
5920 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5921 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005922 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005923 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005924 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5925 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5926 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005927 name.c_str(),
5928 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005929 if (status != NO_ERROR) {
5930 continue;
5931 }
5932 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5933 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5934 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005935 name.c_str(),
5936 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005937 profileUpdated |= (status == NO_ERROR);
5938 }
5939
jiabin81772902018-04-02 17:52:27 -07005940 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005941 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005942 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005943 }
5944
5945 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5946}
5947
Eric Laurent5ada82e2019-08-29 17:53:54 -07005948void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005949{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005950 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005951 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005952 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005953 }
5954}
5955
jiabin6012f912018-11-02 17:06:30 -07005956bool AudioPolicyManager::isHapticPlaybackSupported()
5957{
5958 for (const auto& hwModule : mHwModules) {
5959 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5960 for (const auto &outProfile : outputProfiles) {
5961 struct audio_port audioPort;
5962 outProfile->toAudioPort(&audioPort);
5963 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5964 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5965 return true;
5966 }
5967 }
5968 }
5969 }
5970 return false;
5971}
5972
Carter Hsu325a8eb2022-01-19 19:56:51 +08005973bool AudioPolicyManager::isUltrasoundSupported()
5974{
5975 bool hasUltrasoundOutput = false;
5976 bool hasUltrasoundInput = false;
5977 for (const auto& hwModule : mHwModules) {
5978 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5979 if (!hasUltrasoundOutput) {
5980 for (const auto &outProfile : outputProfiles) {
5981 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5982 hasUltrasoundOutput = true;
5983 break;
5984 }
5985 }
5986 }
5987
5988 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5989 if (!hasUltrasoundInput) {
5990 for (const auto &inputProfile : inputProfiles) {
5991 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5992 hasUltrasoundInput = true;
5993 break;
5994 }
5995 }
5996 }
5997
5998 if (hasUltrasoundOutput && hasUltrasoundInput)
5999 return true;
6000 }
6001 return false;
6002}
6003
Atneya Nair698f5ef2022-12-15 16:15:09 -08006004bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6005{
6006 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6007 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6008 for (const auto& hwModule : mHwModules) {
6009 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6010 for (const auto &inputProfile : inputProfiles) {
6011 if ((inputProfile->getFlags() & mask) == mask) {
6012 return true;
6013 }
6014 }
6015 }
6016 return false;
6017}
6018
Eric Laurent8340e672019-11-06 11:01:08 -08006019bool AudioPolicyManager::isCallScreenModeSupported()
6020{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006021 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006022}
6023
6024
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006025status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006026{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006027 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006028 if (!sourceDesc->isConnected()) {
6029 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6030 return NO_ERROR;
6031 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006032 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6033 if (swOutput != 0) {
6034 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006035 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006036 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006037 }
jiabinbce0c1d2020-10-05 11:20:18 -07006038 if (releaseOutput(sourceDesc->portId())) {
6039 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6040 // no need to release audio patch here but just return NO_ERROR.
6041 return NO_ERROR;
6042 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006043 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006044 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006045 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006046 // close Hwoutput and remove from mHwOutputs
6047 } else {
6048 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6049 }
6050 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006051 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006052 sourceDesc->disconnect();
6053 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006054}
6055
François Gaffiec005e562018-11-06 15:04:49 +01006056sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6057 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006058{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006059 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006060 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006061 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006062 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006063 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6064 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006065 source = sourceDesc;
6066 break;
6067 }
6068 }
6069 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006070}
6071
Eric Laurentb4f42a92022-01-17 17:37:31 +01006072bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006073 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006074 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006075{
6076 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6077 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006078 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006079 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006080 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6081 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6082 return false;
6083 }
6084 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6085 return false;
6086 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006087 }
6088
Eric Laurentd332bc82023-08-04 11:45:23 +02006089 // The caller can have the audio config criteria ignored by either passing a null ptr or
6090 // the AUDIO_CONFIG_INITIALIZER value.
6091 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006092 // some positional channel masks and PCM format and for stereo if low latency performance
6093 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006094
6095 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006096 static const bool stereo_spatialization_enabled =
6097 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006098 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006099 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006100 ? audio_channel_mask_contains_stereo(config->channel_mask)
6101 : audio_is_channel_mask_spatialized(config->channel_mask);
6102 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006103 return false;
6104 }
6105 if (!audio_is_linear_pcm(config->format)) {
6106 return false;
6107 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006108 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6109 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6110 return false;
6111 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006112 }
6113
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006114 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006115 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006116 if (profile == nullptr) {
6117 return false;
6118 }
6119
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006120 return true;
6121}
6122
Shunkai Yao57b93392024-04-26 04:12:21 +00006123// The Spatializer output is compatible with Haptic use cases if:
6124// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6125// with client if client haptic channel bits were set, or
6126// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6127// including the haptic bits or creating the HapticGenerator effect for same session.
6128bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6129 const audio_config_t* config, audio_session_t sessionId) const {
6130 const auto clientHapticChannel =
6131 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6132 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6133 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6134
6135 if (threadOutputHapticChannel) {
6136 // check format and sampleRate match if client haptic channel mask exist
6137 if (clientHapticChannel) {
6138 return mSpatializerOutput->getFormat() == config->format &&
6139 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6140 }
6141 return true;
6142 } else {
6143 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6144 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6145 // HapticGenerator effect for this session) are not supported.
6146 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006147 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006148 }
6149}
6150
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006151void AudioPolicyManager::checkVirtualizerClientRoutes() {
6152 std::set<audio_stream_type_t> streamsToInvalidate;
6153 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006154 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6155 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006156 audio_attributes_t attr = client->attributes();
6157 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6158 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6159 audio_config_base_t clientConfig = client->config();
6160 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006161 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006162 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006163 streamsToInvalidate.insert(client->stream());
6164 }
6165 }
6166 }
6167
jiabinc44b3462022-12-08 12:52:31 -08006168 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006169}
6170
Eric Laurente191d1b2022-04-15 11:59:25 +02006171
6172bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6173 const sp<SwAudioOutputDescriptor>& outputDesc) {
6174 if (outputDesc->isDuplicated()) {
6175 return false;
6176 }
6177 DeviceVector devices = outputDesc->supportedDevices();
6178 for (size_t i = 0; i < mOutputs.size(); i++) {
6179 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6180 if (desc == outputDesc || desc->isDuplicated()) {
6181 continue;
6182 }
6183 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6184 if (!sharedDevices.isEmpty()
6185 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6186 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6187 return false;
6188 }
6189 }
6190 return true;
6191}
6192
6193
Eric Laurentfa0f6742021-08-17 18:39:44 +02006194status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006195 const audio_attributes_t *attr,
6196 audio_io_handle_t *output) {
6197 *output = AUDIO_IO_HANDLE_NONE;
6198
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006199 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6200 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6201 audio_config_t *configPtr = nullptr;
6202 audio_config_t config;
6203 if (mixerConfig != nullptr) {
6204 config = audio_config_initializer(mixerConfig);
6205 configPtr = &config;
6206 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006207 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006208 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006209 return BAD_VALUE;
6210 }
6211
6212 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006213 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006214 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006215 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006216 return BAD_VALUE;
6217 }
6218
Eric Laurente191d1b2022-04-15 11:59:25 +02006219 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006220 for (size_t i = 0; i < mOutputs.size(); i++) {
6221 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006222 if (!desc->isDuplicated()
6223 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6224 spatializerOutputs.push_back(desc);
6225 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006226 }
6227 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006228 mSpatializerOutput.clear();
6229 bool outputsChanged = false;
6230 for (const auto& desc : spatializerOutputs) {
6231 if (desc->mProfile == profile
6232 && (configPtr == nullptr
6233 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6234 mSpatializerOutput = desc;
6235 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6236 } else {
6237 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6238 " and devices %s", __func__, desc->mIoHandle,
6239 configPtr != nullptr ? configPtr->channel_mask : 0,
6240 devices.toString().c_str());
6241 closeOutput(desc->mIoHandle);
6242 outputsChanged = true;
6243 }
Eric Laurent39095982021-08-24 18:29:27 +02006244 }
6245
Eric Laurente191d1b2022-04-15 11:59:25 +02006246 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006247 sp<SwAudioOutputDescriptor> desc =
6248 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006249 if (desc != nullptr) {
6250 mSpatializerOutput = desc;
6251 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006252 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006253 }
6254
6255 checkVirtualizerClientRoutes();
6256
Eric Laurente191d1b2022-04-15 11:59:25 +02006257 if (outputsChanged) {
6258 mPreviousOutputs = mOutputs;
6259 mpClientInterface->onAudioPortListUpdate();
6260 }
6261
6262 if (mSpatializerOutput == nullptr) {
6263 ALOGV("%s could not open spatializer output with requested config", __func__);
6264 return BAD_VALUE;
6265 }
Eric Laurent39095982021-08-24 18:29:27 +02006266 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006267 ALOGV("%s returning new spatializer output %d", __func__, *output);
6268 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006269}
6270
Eric Laurentfa0f6742021-08-17 18:39:44 +02006271status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6272 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006273 return INVALID_OPERATION;
6274 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006275 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006276 return BAD_VALUE;
6277 }
Eric Laurent39095982021-08-24 18:29:27 +02006278
Eric Laurente191d1b2022-04-15 11:59:25 +02006279 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6280 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6281 closeOutput(mSpatializerOutput->mIoHandle);
6282 //from now on mSpatializerOutput is null
6283 checkVirtualizerClientRoutes();
6284 }
Eric Laurent39095982021-08-24 18:29:27 +02006285
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006286 return NO_ERROR;
6287}
6288
Eric Laurente552edb2014-03-10 17:42:56 -07006289// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006290// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006291// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006292uint32_t AudioPolicyManager::nextAudioPortGeneration()
6293{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006294 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006295}
6296
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006297AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006298 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006299 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006300 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006301 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006302 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006303 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006304 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006305 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006306 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006307 mAudioPortGeneration(1),
6308 mBeaconMuteRefCount(0),
6309 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006310 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006311 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006312 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006313 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006314{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006315}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006316
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006317status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006318 if (mEngine == nullptr) {
6319 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006320 }
6321 mEngine->setObserver(this);
6322 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006323 if (status != NO_ERROR) {
6324 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6325 return status;
6326 }
François Gaffie2110e042015-03-24 08:41:51 +01006327
jiabin29230182023-04-04 21:02:36 +00006328 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6329 // at the end of this function.
6330 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006331 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6332 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6333
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006334 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006335 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006336 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006337
Eric Laurent3a4311c2014-03-17 12:00:47 -07006338 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006339 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6340 defaultOutputDevice == nullptr ||
6341 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6342 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6343 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006344 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006345 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006346 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006347
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006348 // Silence ALOGV statements
6349 property_set("log.tag." LOG_TAG, "D");
6350
Eric Laurente552edb2014-03-10 17:42:56 -07006351 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006352 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006353}
6354
Eric Laurente0720872014-03-11 09:30:41 -07006355AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006356{
Eric Laurente552edb2014-03-10 17:42:56 -07006357 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006358 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006359 }
6360 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006361 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006362 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006363 mAvailableOutputDevices.clear();
6364 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006365 mOutputs.clear();
6366 mInputs.clear();
6367 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006368 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006369 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006370}
6371
Eric Laurente0720872014-03-11 09:30:41 -07006372status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006373{
Eric Laurent87ffa392015-05-22 10:32:38 -07006374 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006375}
6376
Eric Laurente552edb2014-03-10 17:42:56 -07006377// ---
6378
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006379void AudioPolicyManager::onNewAudioModulesAvailable()
6380{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006381 DeviceVector newDevices;
6382 onNewAudioModulesAvailableInt(&newDevices);
6383 if (!newDevices.empty()) {
6384 nextAudioPortGeneration();
6385 mpClientInterface->onAudioPortListUpdate();
6386 }
6387}
6388
6389void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6390{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006391 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006392 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6393 continue;
6394 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006395 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006396 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6397 handle != AUDIO_MODULE_HANDLE_NONE) {
6398 hwModule->setHandle(handle);
6399 } else {
6400 ALOGW("could not load HW module %s", hwModule->getName());
6401 continue;
6402 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006403 }
6404 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006405 // open all output streams needed to access attached devices.
6406 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006407 // This also validates mAvailableOutputDevices list
6408 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6409 if (!outProfile->canOpenNewIo()) {
6410 ALOGE("Invalid Output profile max open count %u for profile %s",
6411 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6412 continue;
6413 }
6414 if (!outProfile->hasSupportedDevices()) {
6415 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6416 continue;
6417 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006418 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6419 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006420 mTtsOutputAvailable = true;
6421 }
6422
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006423 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006424 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006425 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006426 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6427 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006428 } else {
6429 // choose first device present in profile's SupportedDevices also part of
6430 // mAvailableOutputDevices.
6431 if (availProfileDevices.isEmpty()) {
6432 continue;
6433 }
6434 supportedDevice = availProfileDevices.itemAt(0);
6435 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006436 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006437 continue;
6438 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306439
6440 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6441 && availProfileDevices.areAllDevicesAttached()) {
6442 ALOGV("%s skip opening output for mmap profile %s", __func__,
6443 outProfile->getTagName().c_str());
6444 continue;
6445 }
6446
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006447 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6448 mpClientInterface);
6449 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006450 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6451 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006452 AUDIO_STREAM_DEFAULT,
6453 AUDIO_OUTPUT_FLAG_NONE, &output);
6454 if (status != NO_ERROR) {
6455 ALOGW("Cannot open output stream for devices %s on hw module %s",
6456 supportedDevice->toString().c_str(), hwModule->getName());
6457 continue;
6458 }
6459 for (const auto &device : availProfileDevices) {
6460 // give a valid ID to an attached device once confirmed it is reachable
6461 if (!device->isAttached()) {
6462 device->attach(hwModule);
6463 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006464 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006465 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006466 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6467 }
6468 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006469 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006470 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6471 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006472 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006473 }
Eric Laurent39095982021-08-24 18:29:27 +02006474 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006475 outputDesc->close();
6476 } else {
6477 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306478 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006479 DeviceVector(supportedDevice),
6480 true,
6481 0,
6482 NULL);
6483 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006484 }
6485 // open input streams needed to access attached devices to validate
6486 // mAvailableInputDevices list
6487 for (const auto& inProfile : hwModule->getInputProfiles()) {
6488 if (!inProfile->canOpenNewIo()) {
6489 ALOGE("Invalid Input profile max open count %u for profile %s",
6490 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6491 continue;
6492 }
6493 if (!inProfile->hasSupportedDevices()) {
6494 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6495 continue;
6496 }
6497 // chose first device present in profile's SupportedDevices also part of
6498 // available input devices
6499 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006500 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006501 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006502 ALOGV("%s: Input device list is empty! for profile %s",
6503 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006504 continue;
6505 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306506
6507 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6508 && availProfileDevices.areAllDevicesAttached()) {
6509 ALOGV("%s skip opening input for mmap profile %s", __func__,
6510 inProfile->getTagName().c_str());
6511 continue;
6512 }
6513
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006514 sp<AudioInputDescriptor> inputDesc =
6515 new AudioInputDescriptor(inProfile, mpClientInterface);
6516
6517 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6518 status_t status = inputDesc->open(nullptr,
6519 availProfileDevices.itemAt(0),
6520 AUDIO_SOURCE_MIC,
Liana Kazanovaa31591a2024-07-11 20:09:39 +00006521 AUDIO_INPUT_FLAG_NONE,
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006522 &input);
6523 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306524 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6525 __func__, availProfileDevices.toString().c_str(),
6526 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006527 continue;
6528 }
6529 for (const auto &device : availProfileDevices) {
6530 // give a valid ID to an attached device once confirmed it is reachable
6531 if (!device->isAttached()) {
6532 device->attach(hwModule);
6533 device->importAudioPortAndPickAudioProfile(inProfile, true);
6534 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006535 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006536 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6537 }
6538 }
6539 inputDesc->close();
6540 }
6541 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006542
6543 // Check if spatializer outputs can be closed until used.
6544 // mOutputs vector never contains duplicated outputs at this point.
6545 std::vector<audio_io_handle_t> outputsClosed;
6546 for (size_t i = 0; i < mOutputs.size(); i++) {
6547 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6548 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6549 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6550 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006551 nextAudioPortGeneration();
6552 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6553 if (index >= 0) {
6554 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6555 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6556 patchDesc->getAfHandle(), 0);
6557 mAudioPatches.removeItemsAt(index);
6558 mpClientInterface->onAudioPatchListUpdate();
6559 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006560 desc->close();
6561 }
6562 }
6563 for (auto output : outputsClosed) {
6564 removeOutput(output);
6565 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006566}
6567
Eric Laurent98e38192018-02-15 18:31:53 -08006568void AudioPolicyManager::addOutput(audio_io_handle_t output,
6569 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006570{
Eric Laurent1c333e22014-05-20 10:48:17 -07006571 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006572 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006573 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006574 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006575 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006576}
6577
François Gaffie53615e22015-03-19 09:24:12 +01006578void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6579{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006580 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6581 ALOGV("%s: removing primary output", __func__);
6582 mPrimaryOutput = nullptr;
6583 }
François Gaffie53615e22015-03-19 09:24:12 +01006584 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006585 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006586}
6587
Eric Laurent98e38192018-02-15 18:31:53 -08006588void AudioPolicyManager::addInput(audio_io_handle_t input,
6589 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006590{
Eric Laurent1c333e22014-05-20 10:48:17 -07006591 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006592 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006593}
Eric Laurente552edb2014-03-10 17:42:56 -07006594
François Gaffie11d30102018-11-02 16:09:09 +01006595status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006596 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006597 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006598{
François Gaffie11d30102018-11-02 16:09:09 +01006599 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006600 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006601 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006602
François Gaffie11d30102018-11-02 16:09:09 +01006603 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006604 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006605 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006606 }
Eric Laurente552edb2014-03-10 17:42:56 -07006607
Eric Laurent3b73df72014-03-11 09:06:29 -07006608 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006609 // first call getAudioPort to get the supported attributes from the HAL
6610 struct audio_port_v7 port = {};
6611 device->toAudioPort(&port);
6612 status_t status = mpClientInterface->getAudioPort(&port);
6613 if (status == NO_ERROR) {
6614 device->importAudioPort(port);
6615 }
6616
6617 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006618 for (size_t i = 0; i < mOutputs.size(); i++) {
6619 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006620 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006621 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006622 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6623 mOutputs.keyAt(i), device->toString().c_str());
6624 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006625 }
6626 }
6627 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006628 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006629 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006630 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6631 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006632 if (profile->supportsDevice(device)) {
6633 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306634 ALOGV("%s(): adding profile %s from module %s",
6635 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006636 }
6637 }
6638 }
6639
Eric Laurent7b279bb2015-12-14 10:18:23 -08006640 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006641
Eric Laurente552edb2014-03-10 17:42:56 -07006642 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006643 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006644 return BAD_VALUE;
6645 }
6646
6647 // open outputs for matching profiles if needed. Direct outputs are also opened to
6648 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6649 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006650 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006651
6652 // nothing to do if one output is already opened for this profile
6653 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006654 for (j = 0; j < outputs.size(); j++) {
6655 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006656 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006657 // matching profile: save the sample rates, format and channel masks supported
6658 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006659 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006660 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006661 }
Eric Laurente552edb2014-03-10 17:42:56 -07006662 break;
6663 }
6664 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006665 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006666 continue;
6667 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306668 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6669 ALOGV("%s skip opening output for mmap profile %s",
6670 __func__, profile->getTagName().c_str());
6671 continue;
6672 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006673 if (!profile->canOpenNewIo()) {
6674 ALOGW("Max Output number %u already opened for this profile %s",
6675 profile->maxOpenCount, profile->getTagName().c_str());
6676 continue;
6677 }
6678
Eric Laurent83efe1c2017-07-09 16:51:08 -07006679 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006680 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006681 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6682 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006683 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006684 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006685 profiles.removeAt(profile_index);
6686 profile_index--;
6687 } else {
6688 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006689 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006690 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006691 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6692 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006693 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006694 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006695
François Gaffie11d30102018-11-02 16:09:09 +01006696 if (device_distinguishes_on_address(deviceType)) {
6697 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6698 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306699 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6700 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006701 }
Eric Laurente552edb2014-03-10 17:42:56 -07006702 ALOGV("checkOutputsForDevice(): adding output %d", output);
6703 }
6704 }
6705
6706 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006707 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006708 return BAD_VALUE;
6709 }
Eric Laurentd4692962014-05-05 18:13:44 -07006710 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006711 // check if one opened output is not needed any more after disconnecting one device
6712 for (size_t i = 0; i < mOutputs.size(); i++) {
6713 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006714 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006715 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006716 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006717 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006718 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006719 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006720 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6721 mOutputs.keyAt(i));
6722 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006723 }
Eric Laurente552edb2014-03-10 17:42:56 -07006724 }
6725 }
Eric Laurentd4692962014-05-05 18:13:44 -07006726 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006727 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006728 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6729 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006730 if (!profile->supportsDevice(device)) {
6731 continue;
6732 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306733 ALOGV("%s(): clearing direct output profile %s on module %s",
6734 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006735 profile->clearAudioProfiles();
6736 if (!profile->hasDynamicAudioProfile()) {
6737 continue;
6738 }
6739 // When a device is disconnected, if there is an IOProfile that contains dynamic
6740 // profiles and supports the disconnected device, call getAudioPort to repopulate
6741 // the capabilities of the devices that is supported by the IOProfile.
6742 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6743 if (supportedDevice == device ||
6744 !mAvailableOutputDevices.contains(supportedDevice)) {
6745 continue;
6746 }
6747 struct audio_port_v7 port;
6748 supportedDevice->toAudioPort(&port);
6749 status_t status = mpClientInterface->getAudioPort(&port);
6750 if (status == NO_ERROR) {
6751 supportedDevice->importAudioPort(port);
6752 }
Eric Laurente552edb2014-03-10 17:42:56 -07006753 }
6754 }
6755 }
6756 }
6757 return NO_ERROR;
6758}
6759
François Gaffie11d30102018-11-02 16:09:09 +01006760status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006761 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006762{
François Gaffie11d30102018-11-02 16:09:09 +01006763 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006764 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006765 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006766 }
6767
Eric Laurentd4692962014-05-05 18:13:44 -07006768 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006769 sp<AudioInputDescriptor> desc;
6770
jiabinbf5f4262023-04-12 21:48:34 +00006771 // first call getAudioPort to get the supported attributes from the HAL
6772 struct audio_port_v7 port = {};
6773 device->toAudioPort(&port);
6774 status_t status = mpClientInterface->getAudioPort(&port);
6775 if (status == NO_ERROR) {
6776 device->importAudioPort(port);
6777 }
6778
Eric Laurent0dd51852019-04-19 18:18:58 -07006779 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006780 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006781 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006782 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006783 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006784 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006785 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006786
François Gaffie11d30102018-11-02 16:09:09 +01006787 if (profile->supportsDevice(device)) {
6788 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306789 ALOGV("%s : adding profile %s from module %s", __func__,
6790 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006791 }
6792 }
6793 }
6794
Eric Laurent0dd51852019-04-19 18:18:58 -07006795 if (profiles.isEmpty()) {
6796 ALOGW("%s: No input profile available for device %s",
6797 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006798 return BAD_VALUE;
6799 }
6800
6801 // open inputs for matching profiles if needed. Direct inputs are also opened to
6802 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6803 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6804
Eric Laurent1c333e22014-05-20 10:48:17 -07006805 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006806
Eric Laurentd4692962014-05-05 18:13:44 -07006807 // nothing to do if one input is already opened for this profile
6808 size_t input_index;
6809 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6810 desc = mInputs.valueAt(input_index);
6811 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006812 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006813 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006814 }
Eric Laurentd4692962014-05-05 18:13:44 -07006815 break;
6816 }
6817 }
6818 if (input_index != mInputs.size()) {
6819 continue;
6820 }
6821
Jaideep Sharma44824a22024-06-18 16:32:34 +05306822 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6823 ALOGV("%s skip opening input for mmap profile %s",
6824 __func__, profile->getTagName().c_str());
6825 continue;
6826 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006827 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306828 ALOGW("%s Max Input number %u already opened for this profile %s",
6829 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08006830 continue;
6831 }
6832
Eric Laurentfe231122017-11-17 17:48:06 -08006833 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006834 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306835 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Liana Kazanovaa31591a2024-07-11 20:09:39 +00006836 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006837
Eric Laurentcf2c0212014-07-25 16:20:43 -07006838 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006839 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006840 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006841 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006842 mpClientInterface->setParameters(input, String8(param));
6843 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006844 }
jiabin12537fc2023-10-12 17:56:08 +00006845 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006846 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306847 ALOGW("%s direct input missing param for profile %s", __func__,
6848 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08006849 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006850 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006851 }
6852
Eric Laurent0dd51852019-04-19 18:18:58 -07006853 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006854 addInput(input, desc);
6855 }
6856 } // endif input != 0
6857
Eric Laurentcf2c0212014-07-25 16:20:43 -07006858 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306859 ALOGW("%s could not open input for device %s on profile %s", __func__,
6860 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006861 profiles.removeAt(profile_index);
6862 profile_index--;
6863 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006864 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006865 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006866 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306867 ALOGV("%s: adding input %d for profile %s", __func__,
6868 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006869
6870 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306871 ALOGV("%s: closing input %d for profile %s", __func__,
6872 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006873 closeInput(input);
6874 }
Eric Laurentd4692962014-05-05 18:13:44 -07006875 }
6876 } // end scan profiles
6877
6878 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006879 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006880 return BAD_VALUE;
6881 }
6882 } else {
6883 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006884 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006885 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006886 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006887 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006888 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006889 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006890 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306891 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
6892 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006893 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006894 }
6895 }
6896 }
6897 } // end disconnect
6898
6899 return NO_ERROR;
6900}
6901
6902
Eric Laurente0720872014-03-11 09:30:41 -07006903void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006904{
6905 ALOGV("closeOutput(%d)", output);
6906
François Gaffie1c878552018-11-22 16:53:21 +01006907 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6908 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006909 ALOGW("closeOutput() unknown output %d", output);
6910 return;
6911 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006912 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006913 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006914
Eric Laurente552edb2014-03-10 17:42:56 -07006915 // look for duplicated outputs connected to the output being removed.
6916 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006917 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6918 if (dupOutput->isDuplicated() &&
6919 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6920 sp<SwAudioOutputDescriptor> remainingOutput =
6921 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006922 // As all active tracks on duplicated output will be deleted,
6923 // and as they were also referenced on the other output, the reference
6924 // count for their stream type must be adjusted accordingly on
6925 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006926 const bool wasActive = remainingOutput->isActive();
6927 // Note: no-op on the closing output where all clients has already been set inactive
6928 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006929 // stop() will be a no op if the output is still active but is needed in case all
6930 // active streams refcounts where cleared above
6931 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006932 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006933 }
Eric Laurente552edb2014-03-10 17:42:56 -07006934 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6935 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6936
6937 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006938 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006939 }
6940 }
6941
Eric Laurent05b90f82014-08-27 15:32:29 -07006942 nextAudioPortGeneration();
6943
François Gaffie1c878552018-11-22 16:53:21 +01006944 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006945 if (index >= 0) {
6946 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006947 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6948 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006949 mAudioPatches.removeItemsAt(index);
6950 mpClientInterface->onAudioPatchListUpdate();
6951 }
6952
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006953 if (closingOutputWasActive) {
6954 closingOutput->stop();
6955 }
François Gaffie1c878552018-11-22 16:53:21 +01006956 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006957 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6958 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6959 for (const auto device : closingOutput->devices()) {
6960 device->setPreferredConfig(nullptr);
6961 }
6962 }
Eric Laurente552edb2014-03-10 17:42:56 -07006963
François Gaffie53615e22015-03-19 09:24:12 +01006964 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006965 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006966 if (closingOutput == mSpatializerOutput) {
6967 mSpatializerOutput.clear();
6968 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006969
6970 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6971 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006972 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006973 bool directOutputOpen = false;
6974 for (size_t i = 0; i < mOutputs.size(); i++) {
6975 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6976 directOutputOpen = true;
6977 break;
6978 }
6979 }
6980 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006981 ALOGV("no direct outputs open, reset MSD patches");
6982 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6983 // how output devices for patching are resolved. Avoid by caching and reusing the
6984 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6985 // devices to patch to. This may be complicated by the fact that devices may become
6986 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006987 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006988 }
6989 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006990}
6991
6992void AudioPolicyManager::closeInput(audio_io_handle_t input)
6993{
6994 ALOGV("closeInput(%d)", input);
6995
6996 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6997 if (inputDesc == NULL) {
6998 ALOGW("closeInput() unknown input %d", input);
6999 return;
7000 }
7001
Eric Laurent6a94d692014-05-20 11:18:06 -07007002 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007003
François Gaffie11d30102018-11-02 16:09:09 +01007004 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007005 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007006 if (index >= 0) {
7007 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007008 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7009 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007010 mAudioPatches.removeItemsAt(index);
7011 mpClientInterface->onAudioPatchListUpdate();
7012 }
7013
François Gaffie6ebbce02023-07-19 13:27:53 +02007014 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007015 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007016 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007017
François Gaffie11d30102018-11-02 16:09:09 +01007018 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7019 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007020 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007021 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007022 }
Eric Laurente552edb2014-03-10 17:42:56 -07007023}
7024
François Gaffie11d30102018-11-02 16:09:09 +01007025SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7026 const DeviceVector &devices,
7027 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007028{
7029 SortedVector<audio_io_handle_t> outputs;
7030
François Gaffie11d30102018-11-02 16:09:09 +01007031 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007032 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007033 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007034 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007035 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007036 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007037 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007038 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007039 outputs.add(openOutputs.keyAt(i));
7040 }
7041 }
7042 return outputs;
7043}
7044
Mikhail Naganov37977152018-07-11 15:54:44 -07007045void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7046{
7047 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7048 // output is suspended before any tracks are moved to it
7049 checkA2dpSuspend();
7050 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007051 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007052 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007053 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007054 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007055 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7056 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7057 // configuration changes will ultimately be rerouted correctly. We can still avoid
7058 // unnecessary rerouting by caching and reusing the arguments to
7059 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7060 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007061 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007062 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007063 // an event that changed routing likely occurred, inform upper layers
7064 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007065}
7066
François Gaffiec005e562018-11-06 15:04:49 +01007067bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7068 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007069{
François Gaffiec005e562018-11-06 15:04:49 +01007070 return mEngine->getProductStrategyForAttributes(lAttr) ==
7071 mEngine->getProductStrategyForAttributes(rAttr);
7072}
7073
Francois Gaffieff1eb522020-05-06 18:37:04 +02007074void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7075{
7076 for (size_t i = 0; i < mAudioSources.size(); i++) {
7077 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7078 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007079 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007080 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007081 connectAudioSource(sourceDesc);
7082 }
7083 }
7084}
7085
7086void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7087{
7088 for (size_t i = 0; i < mAudioSources.size(); i++) {
7089 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7090 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7091 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7092 disconnectAudioSource(sourceDesc);
7093 }
7094 }
7095}
7096
François Gaffiec005e562018-11-06 15:04:49 +01007097void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7098{
7099 auto psId = mEngine->getProductStrategyForAttributes(attr);
7100
7101 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7102 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007103
François Gaffie11d30102018-11-02 16:09:09 +01007104 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7105 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007106
Eric Laurentc209fe42020-06-05 18:11:23 -07007107 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007108 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007109 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007110 // take into account dynamic audio policies related changes: if a client is now associated
7111 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007112 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007113 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7114 if (desc->isDuplicated()) {
7115 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007116 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007117 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7118 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7119 continue;
7120 }
7121 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007122 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007123 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7124 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7125 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007126 if (status != OK) {
7127 continue;
7128 }
yucliuf4de36d2020-09-14 14:57:56 -07007129 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007130 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007131 maxLatency = desc->latency();
7132 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007133 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007134 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007135 }
7136 }
7137
Eric Laurent56ed8842022-11-15 16:04:41 +01007138 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007139 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7140 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007141 for (audio_io_handle_t srcOut : srcOutputs) {
7142 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007143 if (desc == nullptr) continue;
7144
7145 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007146 maxLatency = desc->latency();
7147 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007148
Eric Laurent56ed8842022-11-15 16:04:41 +01007149 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007150 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007151 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007152 // a client on a non direct outputs has necessarily a linear PCM format
7153 // so we can call selectOutput() safely
7154 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7155 client->flags(),
7156 client->config().format,
7157 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007158 client->config().sample_rate,
7159 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007160 if (newOutput != srcOut) {
7161 invalidate = true;
7162 break;
7163 }
7164 } else {
7165 sp<IOProfile> profile = getProfileForOutput(newDevices,
7166 client->config().sample_rate,
7167 client->config().format,
7168 client->config().channel_mask,
7169 client->flags(),
7170 true /* directOnly */);
7171 if (profile != desc->mProfile) {
7172 invalidate = true;
7173 break;
7174 }
7175 }
7176 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007177 // mute strategy while moving tracks from one output to another
7178 if (invalidate) {
7179 invalidatedOutputs.push_back(desc);
7180 if (desc->isStrategyActive(psId)) {
7181 setStrategyMute(psId, true, desc);
7182 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7183 newDevices.types());
7184 }
Eric Laurente552edb2014-03-10 17:42:56 -07007185 }
François Gaffiec005e562018-11-06 15:04:49 +01007186 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007187 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007188 connectAudioSource(source);
7189 }
Eric Laurente552edb2014-03-10 17:42:56 -07007190 }
7191
Eric Laurent56ed8842022-11-15 16:04:41 +01007192 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7193 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7194 std::to_string(srcOutputs[0]).c_str(),
7195 std::to_string(dstOutputs[0]).c_str());
7196
François Gaffiec005e562018-11-06 15:04:49 +01007197 // Move effects associated to this stream from previous output to new output
7198 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007199 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007200 }
François Gaffiec005e562018-11-06 15:04:49 +01007201 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007202 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007203 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007204 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007205 desc->setTracksInvalidatedStatusByStrategy(psId);
7206 }
Eric Laurente552edb2014-03-10 17:42:56 -07007207 }
7208 }
7209}
7210
Eric Laurente0720872014-03-11 09:30:41 -07007211void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007212{
François Gaffiec005e562018-11-06 15:04:49 +01007213 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7214 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7215 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007216 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007217 }
Eric Laurente552edb2014-03-10 17:42:56 -07007218}
7219
Kevin Rocard153f92d2018-12-18 18:33:28 -08007220void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007221 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007222 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007223 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007224 for (size_t i = 0; i < mOutputs.size(); i++) {
7225 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7226 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007227 sp<AudioPolicyMix> primaryMix;
7228 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007229 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007230 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7231 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7232 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007233 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7234 for (auto &secondaryMix : secondaryMixes) {
7235 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7236 if (outputDesc != nullptr &&
7237 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7238 secondaryDescs.push_back(outputDesc);
7239 }
7240 }
7241
jiabinc44b3462022-12-08 12:52:31 -08007242 if (status != OK &&
7243 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7244 // When it failed to query secondary output, only invalidate the client that is not
7245 // MMAP. The reason is that MMAP stream will not support secondary output.
7246 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007247 } else if (!std::equal(
7248 client->getSecondaryOutputs().begin(),
7249 client->getSecondaryOutputs().end(),
7250 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007251 if (!audio_is_linear_pcm(client->config().format)) {
7252 // If the format is not PCM, the tracks should be invalidated to get correct
7253 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007254 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007255 } else {
7256 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7257 std::vector<audio_io_handle_t> secondaryOutputIds;
7258 for (const auto &secondaryDesc: secondaryDescs) {
7259 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7260 weakSecondaryDescs.push_back(secondaryDesc);
7261 }
7262 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7263 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007264 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007265 }
7266 }
7267 }
jiabin10a03f12021-05-07 23:46:28 +00007268 if (!trackSecondaryOutputs.empty()) {
7269 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7270 }
jiabinc44b3462022-12-08 12:52:31 -08007271 if (!clientsToInvalidate.empty()) {
7272 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7273 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007274 }
7275}
7276
Eric Laurent2517af32020-11-25 15:31:27 +01007277bool AudioPolicyManager::isScoRequestedForComm() const {
7278 AudioDeviceTypeAddrVector devices;
7279 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7280 for (const auto &device : devices) {
7281 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7282 return true;
7283 }
7284 }
7285 return false;
7286}
7287
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007288bool AudioPolicyManager::isHearingAidUsedForComm() const {
7289 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7290 true /*fromCache*/);
7291 for (const auto &device : devices) {
7292 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7293 return true;
7294 }
7295 }
7296 return false;
7297}
7298
7299
Eric Laurente0720872014-03-11 09:30:41 -07007300void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007301{
François Gaffie53615e22015-03-19 09:24:12 +01007302 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007303 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007304 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007305 return;
7306 }
7307
Eric Laurent3a4311c2014-03-17 12:00:47 -07007308 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007309 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7310 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007311 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007312
7313 // if suspended, restore A2DP output if:
7314 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007315 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007316 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007317 //
Eric Laurentf732e072016-08-03 19:30:28 -07007318 // if not suspended, suspend A2DP output if:
7319 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007320 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007321 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007322 //
7323 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007324 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007325 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007326 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007327 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007328
7329 mpClientInterface->restoreOutput(a2dpOutput);
7330 mA2dpSuspended = false;
7331 }
7332 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007333 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007334 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007335 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007336 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007337
7338 mpClientInterface->suspendOutput(a2dpOutput);
7339 mA2dpSuspended = true;
7340 }
7341 }
7342}
7343
François Gaffie11d30102018-11-02 16:09:09 +01007344DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7345 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007346{
François Gaffiedb1755b2023-09-01 11:50:35 +02007347 if (outputDesc == nullptr) {
7348 return DeviceVector{};
7349 }
François Gaffie11d30102018-11-02 16:09:09 +01007350
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007351 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007352 if (index >= 0) {
7353 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007354 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007355 ALOGV("%s device %s forced by patch %d", __func__,
7356 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7357 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007358 }
7359 }
7360
Dean Wheatley514b4312020-06-17 21:45:00 +10007361 // Do not retrieve engine device for outputs through MSD
7362 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7363 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7364 return outputDesc->devices();
7365 }
7366
Eric Laurent97ac8712018-07-27 18:59:02 -07007367 // Honor explicit routing requests only if no client using default routing is active on this
7368 // input: a specific app can not force routing for other apps by setting a preferred device.
7369 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007370 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007371 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007372 if (device != nullptr) {
7373 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007374 }
7375
François Gaffiea807ef92018-11-05 10:44:33 +01007376 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7377 // of setForceUse / Default Bus device here
7378 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7379 if (device != nullptr) {
7380 return DeviceVector(device);
7381 }
7382
François Gaffiedb1755b2023-09-01 11:50:35 +02007383 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007384 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7385 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307386 auto hasStreamActive = [&](auto stream) {
7387 return hasStream(streams, stream) && isStreamActive(stream, 0);
7388 };
Eric Laurent484e9272018-06-07 17:29:23 -07007389
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307390 auto doGetOutputDevicesForVoice = [&]() {
7391 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007392 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307393 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007394 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7395 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307396 };
7397
7398 // With low-latency playing on speaker, music on WFD, when the first low-latency
7399 // output is stopped, getNewOutputDevices checks for a product strategy
7400 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007401 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307402 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7403 // stream is associated to the output descriptor.
7404 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7405 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7406 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7407 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007408 // Retrieval of devices for voice DL is done on primary output profile, cannot
7409 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007410 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007411 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7412 break;
7413 }
Eric Laurente552edb2014-03-10 17:42:56 -07007414 }
François Gaffiec005e562018-11-06 15:04:49 +01007415 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007416 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007417}
7418
François Gaffie11d30102018-11-02 16:09:09 +01007419sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7420 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007421{
François Gaffie11d30102018-11-02 16:09:09 +01007422 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007423
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007424 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007425 if (index >= 0) {
7426 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007427 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007428 ALOGV("getNewInputDevice() device %s forced by patch %d",
7429 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7430 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007431 }
7432 }
7433
Eric Laurent97ac8712018-07-27 18:59:02 -07007434 // Honor explicit routing requests only if no client using default routing is active on this
7435 // input: a specific app can not force routing for other apps by setting a preferred device.
7436 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007437 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7438 if (device != nullptr) {
7439 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007440 }
7441
Eric Laurentdc95a252018-04-12 12:46:56 -07007442 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007443 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007444 audio_attributes_t attributes;
7445 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007446 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007447 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7448 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007449 attributes = topClient->attributes();
7450 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007451 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007452 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007453 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7454 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007455 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007456 }
7457
Francois Gaffie716e1432019-01-14 16:58:59 +01007458 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7459 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007460 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007461 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007462 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007463 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007464
Eric Laurente552edb2014-03-10 17:42:56 -07007465 return device;
7466}
7467
Eric Laurent794fde22016-03-11 09:50:45 -08007468bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7469 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007470 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007471}
7472
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007473status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007474 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007475 if (devices == nullptr) {
7476 return BAD_VALUE;
7477 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007478
Andy Hung6d23c0f2022-02-16 09:37:15 -08007479 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007480 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7481 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007482 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007483 for (const auto& device : curDevices) {
7484 devices->push_back(device->getDeviceTypeAddr());
7485 }
7486 return NO_ERROR;
7487}
7488
Eric Laurente0720872014-03-11 09:30:41 -07007489void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007490 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007491 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007492 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007493 updateDevicesAndOutputs();
7494 break;
7495 default:
7496 break;
7497 }
7498}
7499
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007500uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007501
7502 // skip beacon mute management if a dedicated TTS output is available
7503 if (mTtsOutputAvailable) {
7504 return 0;
7505 }
7506
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007507 switch(event) {
7508 case STARTING_OUTPUT:
7509 mBeaconMuteRefCount++;
7510 break;
7511 case STOPPING_OUTPUT:
7512 if (mBeaconMuteRefCount > 0) {
7513 mBeaconMuteRefCount--;
7514 }
7515 break;
7516 case STARTING_BEACON:
7517 mBeaconPlayingRefCount++;
7518 break;
7519 case STOPPING_BEACON:
7520 if (mBeaconPlayingRefCount > 0) {
7521 mBeaconPlayingRefCount--;
7522 }
7523 break;
7524 }
7525
7526 if (mBeaconMuteRefCount > 0) {
7527 // any playback causes beacon to be muted
7528 return setBeaconMute(true);
7529 } else {
7530 // no other playback: unmute when beacon starts playing, mute when it stops
7531 return setBeaconMute(mBeaconPlayingRefCount == 0);
7532 }
7533}
7534
7535uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7536 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7537 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7538 // keep track of muted state to avoid repeating mute/unmute operations
7539 if (mBeaconMuted != mute) {
7540 // mute/unmute AUDIO_STREAM_TTS on all outputs
7541 ALOGV("\t muting %d", mute);
7542 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007543 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7544 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7545 ALOGV("\t no tts volume source available");
7546 return 0;
7547 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007548 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007549 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007550 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007551 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007552 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007553 maxLatency = latency;
7554 }
7555 }
7556 mBeaconMuted = mute;
7557 return maxLatency;
7558 }
7559 return 0;
7560}
7561
Eric Laurente0720872014-03-11 09:30:41 -07007562void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007563{
François Gaffiec005e562018-11-06 15:04:49 +01007564 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007565 mPreviousOutputs = mOutputs;
7566}
7567
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007568uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007569 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007570 uint32_t delayMs)
7571{
7572 // mute/unmute strategies using an incompatible device combination
7573 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7574 // if unmuting, unmute only after the specified delay
7575 if (outputDesc->isDuplicated()) {
7576 return 0;
7577 }
7578
7579 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007580 DeviceVector devices = outputDesc->devices();
7581 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007582
François Gaffiec005e562018-11-06 15:04:49 +01007583 auto productStrategies = mEngine->getOrderedProductStrategies();
7584 for (const auto &productStrategy : productStrategies) {
7585 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7586 DeviceVector curDevices =
7587 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7588 curDevices = curDevices.filter(outputDesc->supportedDevices());
7589 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007590 bool doMute = false;
7591
François Gaffiec005e562018-11-06 15:04:49 +01007592 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007593 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007594 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7595 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007596 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007597 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007598 }
Eric Laurent99401132014-05-07 19:48:15 -07007599 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007600 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007601 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007602 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007603 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007604 continue;
7605 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307606 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007607 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7608 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7609 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007610 if (mute) {
7611 // FIXME: should not need to double latency if volume could be applied
7612 // immediately by the audioflinger mixer. We must account for the delay
7613 // between now and the next time the audioflinger thread for this output
7614 // will process a buffer (which corresponds to one buffer size,
7615 // usually 1/2 or 1/4 of the latency).
7616 if (muteWaitMs < desc->latency() * 2) {
7617 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007618 }
7619 }
7620 }
7621 }
7622 }
7623 }
7624
Eric Laurent99401132014-05-07 19:48:15 -07007625 // temporary mute output if device selection changes to avoid volume bursts due to
7626 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007627 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007628 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007629
Eric Laurentdc462862016-07-19 12:29:53 -07007630 if (muteWaitMs < tempMuteWaitMs) {
7631 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007632 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007633
7634 // If recommended duration is defined, replace temporary mute duration to avoid
7635 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7636 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7637 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7638 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7639 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7640
François Gaffieaaac0fd2018-11-22 17:56:39 +01007641 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7642 // make sure that we do not start the temporary mute period too early in case of
7643 // delayed device change
7644 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7645 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007646 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007647 }
7648 }
7649
Eric Laurente552edb2014-03-10 17:42:56 -07007650 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7651 if (muteWaitMs > delayMs) {
7652 muteWaitMs -= delayMs;
7653 usleep(muteWaitMs * 1000);
7654 return muteWaitMs;
7655 }
7656 return 0;
7657}
7658
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307659uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7660 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007661 const DeviceVector &devices,
7662 bool force,
7663 int delayMs,
7664 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007665 bool requiresMuteCheck, bool requiresVolumeCheck,
7666 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007667{
jiabin3ff8d7d2022-12-13 06:27:44 +00007668 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307669 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7670 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7671 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007672 uint32_t muteWaitMs;
7673
7674 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307675 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007676 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307677 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007678 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007679 return muteWaitMs;
7680 }
Eric Laurente552edb2014-03-10 17:42:56 -07007681
7682 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007683 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007684 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007685 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007686
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307687 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7688 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007689
7690 if (!filteredDevices.isEmpty()) {
7691 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007692 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007693
7694 // if the outputs are not materially active, there is no need to mute.
7695 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007696 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007697 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307698 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7699 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007700 muteWaitMs = 0;
7701 }
Eric Laurente552edb2014-03-10 17:42:56 -07007702
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007703 bool outputRouted = outputDesc->isRouted();
7704
Eric Laurent79ea9582020-06-11 18:49:24 -07007705 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7706 // output profile or if new device is not supported AND previous device(s) is(are) still
7707 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007708 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307709 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7710 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007711 // restore previous device after evaluating strategy mute state
7712 outputDesc->setDevices(prevDevices);
7713 return muteWaitMs;
7714 }
7715
Eric Laurente552edb2014-03-10 17:42:56 -07007716 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007717 // the requested device is AUDIO_DEVICE_NONE
7718 // OR the requested device is the same as current device
7719 // AND force is not specified
7720 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007721 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007722 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307723 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7724 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7725 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007726 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307727 ALOGV("%s %s setting same device on routed output, force apply volumes",
7728 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007729 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7730 }
Eric Laurente552edb2014-03-10 17:42:56 -07007731 return muteWaitMs;
7732 }
7733
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307734 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7735 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007736
Eric Laurente552edb2014-03-10 17:42:56 -07007737 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007738 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007739 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007740 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007741 PatchBuilder patchBuilder;
7742 patchBuilder.addSource(outputDesc);
7743 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7744 for (const auto &filteredDevice : filteredDevices) {
7745 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007746 }
7747
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007748 // Add half reported latency to delayMs when muteWaitMs is null in order
7749 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007750 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7751 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7752 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007753 }
Eric Laurente552edb2014-03-10 17:42:56 -07007754
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007755 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7756 if (!skipMuteDelay) {
7757 // update stream volumes according to new device
7758 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7759 }
Eric Laurente552edb2014-03-10 17:42:56 -07007760
7761 return muteWaitMs;
7762}
7763
Eric Laurentc75307b2015-03-17 15:29:32 -07007764status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007765 int delayMs,
7766 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007767{
Eric Laurent6a94d692014-05-20 11:18:06 -07007768 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007769 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7770 return INVALID_OPERATION;
7771 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007772 if (patchHandle) {
7773 index = mAudioPatches.indexOfKey(*patchHandle);
7774 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007775 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007776 }
7777 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007778 return INVALID_OPERATION;
7779 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007780 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007781 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007782 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007783 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007784 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007785 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007786 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007787 return status;
7788}
7789
7790status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007791 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007792 bool force,
7793 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007794{
7795 status_t status = NO_ERROR;
7796
Eric Laurent1f2f2232014-06-02 12:01:23 -07007797 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007798 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7799 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007800
François Gaffie11d30102018-11-02 16:09:09 +01007801 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007802 PatchBuilder patchBuilder;
7803 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007804 // AUDIO_SOURCE_HOTWORD is for internal use only:
7805 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007806 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7807 auto result = usecase;
7808 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7809 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7810 }
7811 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007812 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007813 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007814 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007815 }
7816 }
7817 return status;
7818}
7819
Eric Laurent6a94d692014-05-20 11:18:06 -07007820status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7821 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007822{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007823 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007824 ssize_t index;
7825 if (patchHandle) {
7826 index = mAudioPatches.indexOfKey(*patchHandle);
7827 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007828 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007829 }
7830 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007831 return INVALID_OPERATION;
7832 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007833 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007834 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007835 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007836 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007837 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007838 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007839 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007840 return status;
7841}
7842
François Gaffie11d30102018-11-02 16:09:09 +01007843sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007844 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007845 audio_format_t& format,
7846 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007847 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007848{
7849 // Choose an input profile based on the requested capture parameters: select the first available
7850 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007851 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007852
Atneya Nair0f0a8032022-12-12 16:20:12 -08007853 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7854 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7855 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7856
7857 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007858
jiabin2fd710d2022-05-02 23:20:22 +00007859 for (;;) {
7860 sp<IOProfile> firstInexact = nullptr;
7861 uint32_t updatedSamplingRate = 0;
7862 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7863 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7864 for (const auto& hwModule : mHwModules) {
7865 for (const auto& profile : hwModule->getInputProfiles()) {
7866 // profile->log();
7867 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007868 if (profile->getCompatibilityScore(
7869 DeviceVector(device),
7870 samplingRate,
7871 &updatedSamplingRate,
7872 format,
7873 &updatedFormat,
7874 channelMask,
7875 &updatedChannelMask,
7876 // FIXME ugly cast
7877 (audio_output_flags_t) flags,
7878 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7879 samplingRate = updatedSamplingRate;
7880 format = updatedFormat;
7881 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007882 return profile;
7883 }
jiabin66acc432024-02-06 00:57:36 +00007884 if (firstInexact == nullptr
7885 && profile->getCompatibilityScore(
7886 DeviceVector(device),
7887 samplingRate,
7888 &updatedSamplingRate,
7889 format,
7890 &updatedFormat,
7891 channelMask,
7892 &updatedChannelMask,
7893 // FIXME ugly cast
7894 (audio_output_flags_t) flags,
7895 false /*exactMatchRequiredForInputFlags*/)
7896 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007897 firstInexact = profile;
7898 }
7899 }
7900 }
7901
7902 if (firstInexact != nullptr) {
7903 samplingRate = updatedSamplingRate;
7904 format = updatedFormat;
7905 channelMask = updatedChannelMask;
7906 return firstInexact;
7907 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7908 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7909 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7910 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7911 flags = AUDIO_INPUT_FLAG_NONE;
7912 } else { // fail
7913 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7914 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7915 samplingRate, format, channelMask, oriFlags);
7916 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007917 }
7918 }
jiabin2fd710d2022-05-02 23:20:22 +00007919
7920 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007921}
7922
François Gaffieaaac0fd2018-11-22 17:56:39 +01007923float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7924 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007925 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007926 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007927{
jiabin9a3361e2019-10-01 09:38:30 -07007928 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007929
7930 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7931 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7932 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7933 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007934 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7935 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7936 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7937 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7938 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena5300db62023-08-30 18:45:18 -07007939 // Verify that the current volume source is not the ringer volume to prevent recursively
7940 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7941 // to the same volume group.
7942 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007943 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7944 mOutputs.isActive(ringVolumeSrc, 0)) {
7945 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007946 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007947 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007948 }
7949
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007950 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007951 if ((volumeSource != callVolumeSrc && (isInCall() ||
7952 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007953 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007954 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7955 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007956 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7957 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7958 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007959 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007960 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007961 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007962 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007963 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007964 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007965 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7966 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7967 // programmatically muted.
7968 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7969 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7970 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007971 bool exemptFromCapping =
7972 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7973 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007974 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7975 volumeSource, volumeDb);
7976 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007977 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7978 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7979 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007980 }
7981 }
Eric Laurente552edb2014-03-10 17:42:56 -07007982 // if a headset is connected, apply the following rules to ring tones and notifications
7983 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007984 // - always attenuate notifications volume by 6dB
7985 // - attenuate ring tones volume by 6dB unless music is not playing and
7986 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007987 // - if music is playing, always limit the volume to current music volume,
7988 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007989 if (!Intersection(deviceTypes,
7990 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7991 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007992 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7993 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007994 ((volumeSource == alarmVolumeSrc ||
7995 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007996 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7997 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7998 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007999 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8000 curves.canBeMuted()) {
8001
Eric Laurente552edb2014-03-10 17:42:56 -07008002 // when the phone is ringing we must consider that music could have been paused just before
8003 // by the music application and behave as if music was active if the last music track was
8004 // just stopped
Oscar Azucena5300db62023-08-30 18:45:18 -07008005 // Verify that the current volume source is not the music volume to prevent recursively
8006 // calling to compute volume. This could happen in cases where music and
8007 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
8008 if (volumeSource != musicVolumeSrc &&
8009 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8010 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01008011 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008012 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008013 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8014 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008015 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008016 float musicVolDb = computeVolume(musicCurves,
8017 musicVolumeSrc,
8018 musicCurves.getVolumeIndex(musicDevice),
8019 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008020 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8021 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8022 if (volumeDb > minVolDb) {
8023 volumeDb = minVolDb;
8024 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008025 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008026 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8027 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008028 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8029 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8030 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8031 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008032 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008033 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008034 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8035 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008036 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8037 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008038 }
8039 }
jiabin9a3361e2019-10-01 09:38:30 -07008040 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008041 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008042 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008043 }
8044 }
8045
François Gaffie43c73442018-11-08 08:21:55 +01008046 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008047}
8048
Eric Laurent3839bc02018-07-10 18:33:34 -07008049int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008050 VolumeSource fromVolumeSource,
8051 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008052{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008053 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008054 return srcIndex;
8055 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008056 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8057 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008058 float minSrc = (float)srcCurves.getVolumeIndexMin();
8059 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8060 float minDst = (float)dstCurves.getVolumeIndexMin();
8061 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008062
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008063 // preserve mute request or correct range
8064 if (srcIndex < minSrc) {
8065 if (srcIndex == 0) {
8066 return 0;
8067 }
8068 srcIndex = minSrc;
8069 } else if (srcIndex > maxSrc) {
8070 srcIndex = maxSrc;
8071 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008072 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8073}
8074
François Gaffieaaac0fd2018-11-22 17:56:39 +01008075status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8076 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008077 int index,
8078 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008079 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008080 int delayMs,
8081 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008082{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008083 // do not change actual attributes volume if the attributes is muted
8084 if (outputDesc->isMuted(volumeSource)) {
8085 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8086 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008087 return NO_ERROR;
8088 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008089
Eric Laurent5baf07c2024-01-11 16:57:27 +00008090 bool isVoiceVolSrc;
8091 bool isBtScoVolSrc;
8092 if (!isVolumeConsistentForCalls(
8093 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008094 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008095 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008096 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008097 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008098
jiabin9a3361e2019-10-01 09:38:30 -07008099 if (deviceTypes.empty()) {
8100 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008101 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008102 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008103 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008104 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008105
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008106 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8107 ALOGE("invalid volume index range");
8108 return BAD_VALUE;
8109 }
8110
jiabin9a3361e2019-10-01 09:38:30 -07008111 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8112 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008113 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008114 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008115 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8116 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008117 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008118 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008119 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008120 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8121 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008122
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008123 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008124 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8125 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8126 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008127 }
Eric Laurente552edb2014-03-10 17:42:56 -07008128 return NO_ERROR;
8129}
8130
Eric Laurent5baf07c2024-01-11 16:57:27 +00008131void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008132 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008133 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008134 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008135 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008136 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008137 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8138 } else {
8139 voiceVolume = index == 0 ? 0.0 : 1.0;
8140 }
8141 if (voiceVolume != mLastVoiceVolume) {
8142 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8143 mLastVoiceVolume = voiceVolume;
8144 }
8145}
8146
8147bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8148 const DeviceTypeSet& deviceTypes,
8149 bool& isVoiceVolSrc,
8150 bool& isBtScoVolSrc,
8151 const char* caller) {
8152 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8153 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8154 const bool isScoRequested = isScoRequestedForComm();
8155 const bool isHAUsed = isHearingAidUsedForComm();
8156
8157 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8158 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8159
8160 if ((callVolSrc != btScoVolSrc) &&
8161 ((isVoiceVolSrc && isScoRequested) ||
8162 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8163 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8164 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8165 volumeSource, isScoRequested ? " " : " not ");
8166 return false;
8167 }
8168 return true;
8169}
8170
Eric Laurentc75307b2015-03-17 15:29:32 -07008171void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008172 const DeviceTypeSet& deviceTypes,
8173 int delayMs,
8174 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008175{
jiabincd510522020-01-22 09:40:55 -08008176 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008177 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8178 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8179 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008180 curves.getVolumeIndex(deviceTypes),
8181 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008182 }
8183}
8184
François Gaffiec005e562018-11-06 15:04:49 +01008185void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8186 bool on,
8187 const sp<AudioOutputDescriptor>& outputDesc,
8188 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008189 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008190{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008191 std::vector<VolumeSource> sourcesToMute;
8192 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8193 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8194 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008195 VolumeSource source = toVolumeSource(attributes, false);
8196 if ((source != VOLUME_SOURCE_NONE) &&
8197 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8198 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008199 sourcesToMute.push_back(source);
8200 }
Eric Laurente552edb2014-03-10 17:42:56 -07008201 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008202 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008203 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008204 }
8205
Eric Laurente552edb2014-03-10 17:42:56 -07008206}
8207
François Gaffieaaac0fd2018-11-22 17:56:39 +01008208void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8209 bool on,
8210 const sp<AudioOutputDescriptor>& outputDesc,
8211 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008212 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008213{
jiabin9a3361e2019-10-01 09:38:30 -07008214 if (deviceTypes.empty()) {
8215 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008216 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008217 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008218 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008219 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008220 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008221 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008222 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8223 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008224 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008225 }
8226 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008227 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8228 // ignored
8229 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008230 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008231 if (!outputDesc->isMuted(volumeSource)) {
8232 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008233 return;
8234 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008235 if (outputDesc->decMuteCount(volumeSource) == 0) {
8236 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008237 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008238 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008239 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008240 delayMs);
8241 }
8242 }
8243}
8244
François Gaffie53615e22015-03-19 09:24:12 +01008245bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8246{
François Gaffiec005e562018-11-06 15:04:49 +01008247 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008248 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8249 return true;
8250 }
8251
8252 // has known usage?
8253 switch (paa->usage) {
8254 case AUDIO_USAGE_UNKNOWN:
8255 case AUDIO_USAGE_MEDIA:
8256 case AUDIO_USAGE_VOICE_COMMUNICATION:
8257 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8258 case AUDIO_USAGE_ALARM:
8259 case AUDIO_USAGE_NOTIFICATION:
8260 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8261 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8262 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8263 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8264 case AUDIO_USAGE_NOTIFICATION_EVENT:
8265 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8266 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8267 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8268 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008269 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008270 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008271 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008272 case AUDIO_USAGE_EMERGENCY:
8273 case AUDIO_USAGE_SAFETY:
8274 case AUDIO_USAGE_VEHICLE_STATUS:
8275 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008276 break;
8277 default:
8278 return false;
8279 }
8280 return true;
8281}
8282
François Gaffie2110e042015-03-24 08:41:51 +01008283audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8284{
8285 return mEngine->getForceUse(usage);
8286}
8287
Eric Laurent96d1dda2022-03-14 17:14:19 +01008288bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008289 return isStateInCall(mEngine->getPhoneState());
8290}
8291
Eric Laurent96d1dda2022-03-14 17:14:19 +01008292bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008293 return is_state_in_call(state);
8294}
8295
Eric Laurentf9cccec2022-11-16 19:12:00 +01008296bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008297 audio_mode_t mode = mEngine->getPhoneState();
8298 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008299 || (mode == AUDIO_MODE_CALL_SCREEN)
8300 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008301}
8302
Eric Laurentf9cccec2022-11-16 19:12:00 +01008303bool AudioPolicyManager::isInCallOrScreening() const {
8304 audio_mode_t mode = mEngine->getPhoneState();
8305 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8306}
8307
Eric Laurentd60560a2015-04-10 11:31:20 -07008308void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8309{
8310 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008311 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008312 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008313 sourceDesc->sinkDevice()->equals(deviceDesc))
8314 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008315 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008316 }
8317 }
8318
8319 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8320 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8321 bool release = false;
8322 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8323 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8324 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8325 source->ext.device.type == deviceDesc->type()) {
8326 release = true;
8327 }
8328 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008329 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008330 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8331 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8332 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008333 sink->ext.device.type == deviceDesc->type() &&
8334 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8335 || strncmp(sink->ext.device.address, address,
8336 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008337 release = true;
8338 }
8339 }
8340 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008341 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8342 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008343 }
8344 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008345
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008346 mInputs.clearSessionRoutesForDevice(deviceDesc);
8347
Francois Gaffie716e1432019-01-14 16:58:59 +01008348 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008349}
8350
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008351void AudioPolicyManager::modifySurroundFormats(
8352 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008353 std::unordered_set<audio_format_t> enforcedSurround(
8354 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008355 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008356 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008357 allSurround.insert(pair.first);
8358 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8359 }
Phil Burk09bc4612016-02-24 15:58:15 -08008360
8361 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8362 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008363 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008364 // This is the resulting set of formats depending on the surround mode:
8365 // 'all surround' = allSurround
8366 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8367 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8368 // 'manual surround' = mManualSurroundFormats
8369 // AUTO: formats v 'enforced surround'
8370 // ALWAYS: formats v 'all surround' v 'enforced surround'
8371 // NEVER: formats ^ 'non-surround'
8372 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008373
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008374 std::unordered_set<audio_format_t> formatSet;
8375 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8376 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008377 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008378 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008379 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008380 formatSet.insert(*formatIter);
8381 }
8382 }
8383 } else {
8384 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8385 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008386 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008387
jiabin81772902018-04-02 17:52:27 -07008388 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008389 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008390 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8391 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8392 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008393 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008394 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8395 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8396 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008397 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008398 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008399 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008400 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008401 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008402 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008403}
8404
jiabin06e4bab2019-07-29 10:13:34 -07008405void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8406 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008407 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8408 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8409
8410 // If NEVER, then remove support for channelMasks > stereo.
8411 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008412 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8413 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008414 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008415 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008416 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008417 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008418 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008419 }
8420 }
jiabin81772902018-04-02 17:52:27 -07008421 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8422 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8423 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008424 bool supports5dot1 = false;
8425 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008426 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008427 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8428 supports5dot1 = true;
8429 break;
8430 }
8431 }
8432 // If not then add 5.1 support.
8433 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008434 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008435 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008436 }
Phil Burk09bc4612016-02-24 15:58:15 -08008437 }
8438}
8439
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008440void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008441 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008442 const sp<IOProfile>& profile) {
8443 if (!profile->hasDynamicAudioProfile()) {
8444 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008445 }
François Gaffie112b0af2015-11-19 16:13:25 +01008446
jiabin12537fc2023-10-12 17:56:08 +00008447 audio_port_v7 devicePort;
8448 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008449
jiabin12537fc2023-10-12 17:56:08 +00008450 audio_port_v7 mixPort;
8451 profile->toAudioPort(&mixPort);
8452 mixPort.ext.mix.handle = ioHandle;
8453
8454 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8455 if (status != NO_ERROR) {
8456 ALOGE("%s failed to query the attributes of the mix port", __func__);
8457 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008458 }
jiabin12537fc2023-10-12 17:56:08 +00008459
8460 std::set<audio_format_t> supportedFormats;
8461 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8462 supportedFormats.insert(mixPort.audio_profiles[i].format);
8463 }
8464 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8465 mReportedFormatsMap[devDesc] = formats;
8466
8467 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8468 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8469 modifySurroundFormats(devDesc, &formats);
8470 size_t modifiedNumProfiles = 0;
8471 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8472 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8473 formats.end()) {
8474 // Skip the format that is not present after modifying surround formats.
8475 continue;
8476 }
8477 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8478 sizeof(struct audio_profile));
8479 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8480 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8481 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8482 modifySurroundChannelMasks(&channels);
8483 std::copy(channels.begin(), channels.end(),
8484 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8485 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8486 }
8487 mixPort.num_audio_profiles = modifiedNumProfiles;
8488 }
8489 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008490}
Eric Laurentd60560a2015-04-10 11:31:20 -07008491
Mikhail Naganovdc769682018-05-04 15:34:08 -07008492status_t AudioPolicyManager::installPatch(const char *caller,
8493 audio_patch_handle_t *patchHandle,
8494 AudioIODescriptorInterface *ioDescriptor,
8495 const struct audio_patch *patch,
8496 int delayMs)
8497{
8498 ssize_t index = mAudioPatches.indexOfKey(
8499 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8500 *patchHandle : ioDescriptor->getPatchHandle());
8501 sp<AudioPatch> patchDesc;
8502 status_t status = installPatch(
8503 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8504 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008505 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008506 }
8507 return status;
8508}
8509
8510status_t AudioPolicyManager::installPatch(const char *caller,
8511 ssize_t index,
8512 audio_patch_handle_t *patchHandle,
8513 const struct audio_patch *patch,
8514 int delayMs,
8515 uid_t uid,
8516 sp<AudioPatch> *patchDescPtr)
8517{
8518 sp<AudioPatch> patchDesc;
8519 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8520 if (index >= 0) {
8521 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008522 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008523 }
8524
8525 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8526 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8527 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8528 if (status == NO_ERROR) {
8529 if (index < 0) {
8530 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008531 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008532 } else {
8533 patchDesc->mPatch = *patch;
8534 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008535 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008536 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008537 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008538 }
8539 nextAudioPortGeneration();
8540 mpClientInterface->onAudioPatchListUpdate();
8541 }
8542 if (patchDescPtr) *patchDescPtr = patchDesc;
8543 return status;
8544}
8545
jiabinbce0c1d2020-10-05 11:20:18 -07008546bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8547{
8548 const TrackClientVector activeClients = output->getActiveClients();
8549 if (activeClients.empty()) {
8550 return true;
8551 }
8552 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8553 if (index < 0) {
8554 ALOGE("%s, no audio patch found while there are active clients on output %d",
8555 __func__, output->getId());
8556 return false;
8557 }
8558 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8559 DeviceVector routedDevices;
8560 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8561 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8562 patchDesc->mPatch.sinks[i].id);
8563 if (device == nullptr) {
8564 ALOGE("%s, no audio device found with id(%d)",
8565 __func__, patchDesc->mPatch.sinks[i].id);
8566 return false;
8567 }
8568 routedDevices.add(device);
8569 }
8570 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008571 if (client->isInvalid()) {
8572 // No need to take care about invalidated clients.
8573 continue;
8574 }
jiabinbce0c1d2020-10-05 11:20:18 -07008575 sp<DeviceDescriptor> preferredDevice =
8576 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8577 if (mEngine->getOutputDevicesForAttributes(
8578 client->attributes(), preferredDevice, false) == routedDevices) {
8579 return false;
8580 }
8581 }
8582 return true;
8583}
8584
8585sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008586 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008587 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8588 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008589{
8590 for (const auto& device : devices) {
8591 // TODO: This should be checking if the profile supports the device combo.
8592 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008593 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8594 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008595 return nullptr;
8596 }
8597 }
8598 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8599 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008600 status_t status = desc->open(halConfig, mixerConfig, devices,
8601 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008602 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008603 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008604 return nullptr;
8605 }
jiabin14b50cc2023-12-13 19:01:52 +00008606 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8607 auto portConfig = desc->getConfig();
8608 for (const auto& device : devices) {
8609 device->setPreferredConfig(&portConfig);
8610 }
8611 }
jiabinbce0c1d2020-10-05 11:20:18 -07008612
8613 // Here is where the out_set_parameters() for card & device gets called
8614 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8615 const audio_devices_t deviceType = device->type();
8616 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008617 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008618 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8619 mpClientInterface->setParameters(output, String8(param));
8620 free(param);
8621 }
jiabin12537fc2023-10-12 17:56:08 +00008622 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008623 if (!profile->hasValidAudioProfile()) {
8624 ALOGW("%s() missing param", __func__);
8625 desc->close();
8626 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008627 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8628 // Reopen the output with the best audio profile picked by APM when the profile supports
8629 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008630 desc->close();
8631 output = AUDIO_IO_HANDLE_NONE;
8632 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8633 profile->pickAudioProfile(
8634 config.sample_rate, config.channel_mask, config.format);
8635 config.offload_info.sample_rate = config.sample_rate;
8636 config.offload_info.channel_mask = config.channel_mask;
8637 config.offload_info.format = config.format;
8638
jiabina84c3d32022-12-02 18:59:55 +00008639 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008640 if (status != NO_ERROR) {
8641 return nullptr;
8642 }
8643 }
8644
8645 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008646
baek.kim -61c20122022-07-27 10:05:32 +00008647 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8648 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8649
jiabinbce0c1d2020-10-05 11:20:18 -07008650 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8651 sp<AudioPolicyMix> policyMix;
8652 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8653 policyMix->setOutput(desc);
8654 desc->mPolicyMix = policyMix;
8655 } else {
8656 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008657 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008658 }
8659
baek.kim -61c20122022-07-27 10:05:32 +00008660 } else if (hasPrimaryOutput() && speaker != nullptr
8661 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008662 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8663 // no duplicated output for:
8664 // - direct outputs
8665 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008666 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008667 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8668
8669 //TODO: configure audio effect output stage here
8670
8671 // open a duplicating output thread for the new output and the primary output
8672 sp<SwAudioOutputDescriptor> dupOutputDesc =
8673 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8674 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8675 if (status == NO_ERROR) {
8676 // add duplicated output descriptor
8677 addOutput(duplicatedOutput, dupOutputDesc);
8678 } else {
8679 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8680 mPrimaryOutput->mIoHandle, output);
8681 desc->close();
8682 removeOutput(output);
8683 nextAudioPortGeneration();
8684 return nullptr;
8685 }
8686 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008687 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8688 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8689 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008690 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008691 }
jiabinbce0c1d2020-10-05 11:20:18 -07008692 return desc;
8693}
8694
jiabinf1c73972022-04-14 16:28:52 -07008695status_t AudioPolicyManager::getDevicesForAttributes(
8696 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8697 // Devices are determined in the following precedence:
8698 //
8699 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8700 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8701 //
8702 // If no such dynamic policy then
8703 // 2) Devices containing an active client using setPreferredDevice
8704 // with same strategy as the attributes.
8705 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8706 //
8707 // If no corresponding active client with setPreferredDevice then
8708 // 3) Devices associated with the strategy determined by the attributes
8709 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8710 //
8711 // See related getOutputForAttrInt().
8712
8713 // check dynamic policies but only for primary descriptors (secondary not used for audible
8714 // audio routing, only used for duplication for playback capture)
8715 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008716 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008717 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008718 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8719 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8720 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008721 if (status != OK) {
8722 return status;
8723 }
8724
8725 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8726 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8727 // as they are unaffected by device/stream volume
8728 // (per SwAudioOutputDescriptor::isFixedVolume()).
8729 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8730 ) {
8731 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8732 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8733 devices.add(deviceDesc);
8734 } else {
8735 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8736 // which selects setPreferredDevice if active. This means forVolume call
8737 // will take an active setPreferredDevice, if such exists.
8738
8739 devices = mEngine->getOutputDevicesForAttributes(
8740 attr, nullptr /* preferredDevice */, false /* fromCache */);
8741 }
8742
8743 if (forVolume) {
8744 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8745 // for single volume control in AudioService (such relationship should exist if
8746 // SPEAKER_SAFE is present).
8747 //
8748 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8749 DeviceVector speakerSafeDevices =
8750 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8751 if (!speakerSafeDevices.isEmpty()) {
8752 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8753 devices.remove(speakerSafeDevices);
8754 }
8755 }
8756
8757 return NO_ERROR;
8758}
8759
8760status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8761 AudioProfileVector& audioProfiles,
8762 uint32_t flags,
8763 bool isInput) {
8764 for (const auto& hwModule : mHwModules) {
8765 // the MSD module checks for different conditions
8766 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8767 continue;
8768 }
8769 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8770 : hwModule->getOutputProfiles();
8771 for (const auto& profile : ioProfiles) {
8772 if (!profile->areAllDevicesSupported(devices) ||
8773 !profile->isCompatibleProfileForFlags(
8774 flags, false /*exactMatchRequiredForInputFlags*/)) {
8775 continue;
8776 }
8777 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8778 }
8779 }
8780
8781 if (!isInput) {
8782 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8783 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8784 if (msdModule != nullptr) {
8785 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8786 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8787 for (const auto &profile: msdModule->getOutputProfiles()) {
8788 if (!profile->asAudioPort()->isDirectOutput()) {
8789 continue;
8790 }
8791 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8792 }
8793 } else {
8794 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8795 }
8796 }
8797 }
8798
8799 return NO_ERROR;
8800}
8801
jiabin3ff8d7d2022-12-13 06:27:44 +00008802sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8803 const audio_config_t *config,
8804 audio_output_flags_t flags,
8805 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008806 closeOutput(outputDesc->mIoHandle);
8807 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8808 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8809 if (preferredOutput == nullptr) {
8810 ALOGE("%s failed to reopen output device=%d, caller=%s",
8811 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008812 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008813 return preferredOutput;
8814}
8815
8816void AudioPolicyManager::reopenOutputsWithDevices(
8817 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8818 for (const auto& [output, devices] : outputsToReopen) {
8819 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8820 closeOutput(output);
8821 openOutputWithProfileAndDevice(desc->mProfile, devices);
8822 }
jiabina84c3d32022-12-02 18:59:55 +00008823}
8824
jiabinc44b3462022-12-08 12:52:31 -08008825PortHandleVector AudioPolicyManager::getClientsForStream(
8826 audio_stream_type_t streamType) const {
8827 PortHandleVector clients;
8828 for (size_t i = 0; i < mOutputs.size(); ++i) {
8829 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8830 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8831 }
8832 return clients;
8833}
8834
8835void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8836 PortHandleVector clients;
8837 for (auto stream : streams) {
8838 PortHandleVector clientsForStream = getClientsForStream(stream);
8839 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8840 }
8841 mpClientInterface->invalidateTracks(clients);
8842}
8843
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008844} // namespace android